builtin-top.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. * 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
  9. *
  10. * Improvements and fixes by:
  11. *
  12. * Arjan van de Ven <arjan@linux.intel.com>
  13. * Yanmin Zhang <yanmin.zhang@intel.com>
  14. * Wu Fengguang <fengguang.wu@intel.com>
  15. * Mike Galbraith <efault@gmx.de>
  16. * Paul Mackerras <paulus@samba.org>
  17. *
  18. * Released under the GPL v2. (and only v2, not any later version)
  19. */
  20. #include "builtin.h"
  21. #include "perf.h"
  22. #include "util/annotate.h"
  23. #include "util/cache.h"
  24. #include "util/color.h"
  25. #include "util/evlist.h"
  26. #include "util/evsel.h"
  27. #include "util/session.h"
  28. #include "util/symbol.h"
  29. #include "util/thread.h"
  30. #include "util/thread_map.h"
  31. #include "util/top.h"
  32. #include "util/util.h"
  33. #include <linux/rbtree.h>
  34. #include "util/parse-options.h"
  35. #include "util/parse-events.h"
  36. #include "util/cpumap.h"
  37. #include "util/xyarray.h"
  38. #include "util/sort.h"
  39. #include "util/debug.h"
  40. #include <assert.h>
  41. #include <fcntl.h>
  42. #include <stdio.h>
  43. #include <termios.h>
  44. #include <unistd.h>
  45. #include <inttypes.h>
  46. #include <errno.h>
  47. #include <time.h>
  48. #include <sched.h>
  49. #include <sys/syscall.h>
  50. #include <sys/ioctl.h>
  51. #include <sys/poll.h>
  52. #include <sys/prctl.h>
  53. #include <sys/wait.h>
  54. #include <sys/uio.h>
  55. #include <sys/mman.h>
  56. #include <linux/unistd.h>
  57. #include <linux/types.h>
  58. static struct perf_top top = {
  59. .count_filter = 5,
  60. .delay_secs = 2,
  61. .target_pid = -1,
  62. .target_tid = -1,
  63. .freq = 1000, /* 1 KHz */
  64. };
  65. static bool system_wide = false;
  66. static bool use_tui, use_stdio;
  67. static bool sort_has_symbols;
  68. static bool dont_use_callchains;
  69. static char callchain_default_opt[] = "fractal,0.5,callee";
  70. static int default_interval = 0;
  71. static bool kptr_restrict_warned;
  72. static bool vmlinux_warned;
  73. static bool inherit = false;
  74. static int realtime_prio = 0;
  75. static bool group = false;
  76. static bool sample_id_all_avail = true;
  77. static unsigned int mmap_pages = 128;
  78. static bool dump_symtab = false;
  79. static struct winsize winsize;
  80. static const char *sym_filter = NULL;
  81. static int sym_pcnt_filter = 5;
  82. /*
  83. * Source functions
  84. */
  85. void get_term_dimensions(struct winsize *ws)
  86. {
  87. char *s = getenv("LINES");
  88. if (s != NULL) {
  89. ws->ws_row = atoi(s);
  90. s = getenv("COLUMNS");
  91. if (s != NULL) {
  92. ws->ws_col = atoi(s);
  93. if (ws->ws_row && ws->ws_col)
  94. return;
  95. }
  96. }
  97. #ifdef TIOCGWINSZ
  98. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  99. ws->ws_row && ws->ws_col)
  100. return;
  101. #endif
  102. ws->ws_row = 25;
  103. ws->ws_col = 80;
  104. }
  105. static void update_print_entries(struct winsize *ws)
  106. {
  107. top.print_entries = ws->ws_row;
  108. if (top.print_entries > 9)
  109. top.print_entries -= 9;
  110. }
  111. static void sig_winch_handler(int sig __used)
  112. {
  113. get_term_dimensions(&winsize);
  114. update_print_entries(&winsize);
  115. }
  116. static int parse_source(struct hist_entry *he)
  117. {
  118. struct symbol *sym;
  119. struct annotation *notes;
  120. struct map *map;
  121. int err = -1;
  122. if (!he || !he->ms.sym)
  123. return -1;
  124. sym = he->ms.sym;
  125. map = he->ms.map;
  126. /*
  127. * We can't annotate with just /proc/kallsyms
  128. */
  129. if (map->dso->symtab_type == SYMTAB__KALLSYMS) {
  130. pr_err("Can't annotate %s: No vmlinux file was found in the "
  131. "path\n", sym->name);
  132. sleep(1);
  133. return -1;
  134. }
  135. notes = symbol__annotation(sym);
  136. if (notes->src != NULL) {
  137. pthread_mutex_lock(&notes->lock);
  138. goto out_assign;
  139. }
  140. pthread_mutex_lock(&notes->lock);
  141. if (symbol__alloc_hist(sym) < 0) {
  142. pthread_mutex_unlock(&notes->lock);
  143. pr_err("Not enough memory for annotating '%s' symbol!\n",
  144. sym->name);
  145. sleep(1);
  146. return err;
  147. }
  148. err = symbol__annotate(sym, map, 0);
  149. if (err == 0) {
  150. out_assign:
  151. top.sym_filter_entry = he;
  152. }
  153. pthread_mutex_unlock(&notes->lock);
  154. return err;
  155. }
  156. static void __zero_source_counters(struct hist_entry *he)
  157. {
  158. struct symbol *sym = he->ms.sym;
  159. symbol__annotate_zero_histograms(sym);
  160. }
  161. static void record_precise_ip(struct hist_entry *he, int counter, u64 ip)
  162. {
  163. struct annotation *notes;
  164. struct symbol *sym;
  165. if (he == NULL || he->ms.sym == NULL ||
  166. ((top.sym_filter_entry == NULL ||
  167. top.sym_filter_entry->ms.sym != he->ms.sym) && use_browser != 1))
  168. return;
  169. sym = he->ms.sym;
  170. notes = symbol__annotation(sym);
  171. if (pthread_mutex_trylock(&notes->lock))
  172. return;
  173. if (notes->src == NULL && symbol__alloc_hist(sym) < 0) {
  174. pthread_mutex_unlock(&notes->lock);
  175. pr_err("Not enough memory for annotating '%s' symbol!\n",
  176. sym->name);
  177. sleep(1);
  178. return;
  179. }
  180. ip = he->ms.map->map_ip(he->ms.map, ip);
  181. symbol__inc_addr_samples(sym, he->ms.map, counter, ip);
  182. pthread_mutex_unlock(&notes->lock);
  183. }
  184. static void show_details(struct hist_entry *he)
  185. {
  186. struct annotation *notes;
  187. struct symbol *symbol;
  188. int more;
  189. if (!he)
  190. return;
  191. symbol = he->ms.sym;
  192. notes = symbol__annotation(symbol);
  193. pthread_mutex_lock(&notes->lock);
  194. if (notes->src == NULL)
  195. goto out_unlock;
  196. printf("Showing %s for %s\n", event_name(top.sym_evsel), symbol->name);
  197. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  198. more = symbol__annotate_printf(symbol, he->ms.map, top.sym_evsel->idx,
  199. 0, sym_pcnt_filter, top.print_entries, 4);
  200. if (top.zero)
  201. symbol__annotate_zero_histogram(symbol, top.sym_evsel->idx);
  202. else
  203. symbol__annotate_decay_histogram(symbol, top.sym_evsel->idx);
  204. if (more != 0)
  205. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  206. out_unlock:
  207. pthread_mutex_unlock(&notes->lock);
  208. }
  209. static const char CONSOLE_CLEAR[] = "";
  210. static struct hist_entry *
  211. perf_session__add_hist_entry(struct perf_session *session,
  212. struct addr_location *al,
  213. struct perf_sample *sample,
  214. struct perf_evsel *evsel)
  215. {
  216. struct hist_entry *he;
  217. he = __hists__add_entry(&evsel->hists, al, NULL, sample->period);
  218. if (he == NULL)
  219. return NULL;
  220. session->hists.stats.total_period += sample->period;
  221. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  222. return he;
  223. }
  224. static void print_sym_table(void)
  225. {
  226. char bf[160];
  227. int printed = 0;
  228. const int win_width = winsize.ws_col - 1;
  229. puts(CONSOLE_CLEAR);
  230. perf_top__header_snprintf(&top, bf, sizeof(bf));
  231. printf("%s\n", bf);
  232. perf_top__reset_sample_counters(&top);
  233. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  234. if (top.sym_evsel->hists.stats.nr_lost_warned !=
  235. top.sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  236. top.sym_evsel->hists.stats.nr_lost_warned =
  237. top.sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  238. color_fprintf(stdout, PERF_COLOR_RED,
  239. "WARNING: LOST %d chunks, Check IO/CPU overload",
  240. top.sym_evsel->hists.stats.nr_lost_warned);
  241. ++printed;
  242. }
  243. if (top.sym_filter_entry) {
  244. show_details(top.sym_filter_entry);
  245. return;
  246. }
  247. hists__collapse_resort_threaded(&top.sym_evsel->hists);
  248. hists__output_resort_threaded(&top.sym_evsel->hists);
  249. hists__decay_entries_threaded(&top.sym_evsel->hists,
  250. top.hide_user_symbols,
  251. top.hide_kernel_symbols);
  252. hists__output_recalc_col_len(&top.sym_evsel->hists, winsize.ws_row - 3);
  253. putchar('\n');
  254. hists__fprintf(&top.sym_evsel->hists, NULL, false, false,
  255. winsize.ws_row - 4 - printed, win_width, stdout);
  256. }
  257. static void prompt_integer(int *target, const char *msg)
  258. {
  259. char *buf = malloc(0), *p;
  260. size_t dummy = 0;
  261. int tmp;
  262. fprintf(stdout, "\n%s: ", msg);
  263. if (getline(&buf, &dummy, stdin) < 0)
  264. return;
  265. p = strchr(buf, '\n');
  266. if (p)
  267. *p = 0;
  268. p = buf;
  269. while(*p) {
  270. if (!isdigit(*p))
  271. goto out_free;
  272. p++;
  273. }
  274. tmp = strtoul(buf, NULL, 10);
  275. *target = tmp;
  276. out_free:
  277. free(buf);
  278. }
  279. static void prompt_percent(int *target, const char *msg)
  280. {
  281. int tmp = 0;
  282. prompt_integer(&tmp, msg);
  283. if (tmp >= 0 && tmp <= 100)
  284. *target = tmp;
  285. }
  286. static void prompt_symbol(struct hist_entry **target, const char *msg)
  287. {
  288. char *buf = malloc(0), *p;
  289. struct hist_entry *syme = *target, *n, *found = NULL;
  290. struct rb_node *next;
  291. size_t dummy = 0;
  292. /* zero counters of active symbol */
  293. if (syme) {
  294. __zero_source_counters(syme);
  295. *target = NULL;
  296. }
  297. fprintf(stdout, "\n%s: ", msg);
  298. if (getline(&buf, &dummy, stdin) < 0)
  299. goto out_free;
  300. p = strchr(buf, '\n');
  301. if (p)
  302. *p = 0;
  303. next = rb_first(&top.sym_evsel->hists.entries);
  304. while (next) {
  305. n = rb_entry(next, struct hist_entry, rb_node);
  306. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  307. found = n;
  308. break;
  309. }
  310. next = rb_next(&n->rb_node);
  311. }
  312. if (!found) {
  313. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  314. sleep(1);
  315. return;
  316. } else
  317. parse_source(found);
  318. out_free:
  319. free(buf);
  320. }
  321. static void print_mapped_keys(void)
  322. {
  323. char *name = NULL;
  324. if (top.sym_filter_entry) {
  325. struct symbol *sym = top.sym_filter_entry->ms.sym;
  326. name = sym->name;
  327. }
  328. fprintf(stdout, "\nMapped keys:\n");
  329. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top.delay_secs);
  330. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top.print_entries);
  331. if (top.evlist->nr_entries > 1)
  332. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top.sym_evsel));
  333. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top.count_filter);
  334. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  335. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  336. fprintf(stdout, "\t[S] stop annotation.\n");
  337. fprintf(stdout,
  338. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  339. top.hide_kernel_symbols ? "yes" : "no");
  340. fprintf(stdout,
  341. "\t[U] hide user symbols. \t(%s)\n",
  342. top.hide_user_symbols ? "yes" : "no");
  343. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top.zero ? 1 : 0);
  344. fprintf(stdout, "\t[qQ] quit.\n");
  345. }
  346. static int key_mapped(int c)
  347. {
  348. switch (c) {
  349. case 'd':
  350. case 'e':
  351. case 'f':
  352. case 'z':
  353. case 'q':
  354. case 'Q':
  355. case 'K':
  356. case 'U':
  357. case 'F':
  358. case 's':
  359. case 'S':
  360. return 1;
  361. case 'E':
  362. return top.evlist->nr_entries > 1 ? 1 : 0;
  363. default:
  364. break;
  365. }
  366. return 0;
  367. }
  368. static void handle_keypress(int c)
  369. {
  370. if (!key_mapped(c)) {
  371. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  372. struct termios tc, save;
  373. print_mapped_keys();
  374. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  375. fflush(stdout);
  376. tcgetattr(0, &save);
  377. tc = save;
  378. tc.c_lflag &= ~(ICANON | ECHO);
  379. tc.c_cc[VMIN] = 0;
  380. tc.c_cc[VTIME] = 0;
  381. tcsetattr(0, TCSANOW, &tc);
  382. poll(&stdin_poll, 1, -1);
  383. c = getc(stdin);
  384. tcsetattr(0, TCSAFLUSH, &save);
  385. if (!key_mapped(c))
  386. return;
  387. }
  388. switch (c) {
  389. case 'd':
  390. prompt_integer(&top.delay_secs, "Enter display delay");
  391. if (top.delay_secs < 1)
  392. top.delay_secs = 1;
  393. break;
  394. case 'e':
  395. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  396. if (top.print_entries == 0) {
  397. sig_winch_handler(SIGWINCH);
  398. signal(SIGWINCH, sig_winch_handler);
  399. } else
  400. signal(SIGWINCH, SIG_DFL);
  401. break;
  402. case 'E':
  403. if (top.evlist->nr_entries > 1) {
  404. /* Select 0 as the default event: */
  405. int counter = 0;
  406. fprintf(stderr, "\nAvailable events:");
  407. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  408. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  409. prompt_integer(&counter, "Enter details event counter");
  410. if (counter >= top.evlist->nr_entries) {
  411. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  412. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  413. sleep(1);
  414. break;
  415. }
  416. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  417. if (top.sym_evsel->idx == counter)
  418. break;
  419. } else
  420. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  421. break;
  422. case 'f':
  423. prompt_integer(&top.count_filter, "Enter display event count filter");
  424. break;
  425. case 'F':
  426. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  427. break;
  428. case 'K':
  429. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  430. break;
  431. case 'q':
  432. case 'Q':
  433. printf("exiting.\n");
  434. if (dump_symtab)
  435. perf_session__fprintf_dsos(top.session, stderr);
  436. exit(0);
  437. case 's':
  438. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  439. break;
  440. case 'S':
  441. if (!top.sym_filter_entry)
  442. break;
  443. else {
  444. struct hist_entry *syme = top.sym_filter_entry;
  445. top.sym_filter_entry = NULL;
  446. __zero_source_counters(syme);
  447. }
  448. break;
  449. case 'U':
  450. top.hide_user_symbols = !top.hide_user_symbols;
  451. break;
  452. case 'z':
  453. top.zero = !top.zero;
  454. break;
  455. default:
  456. break;
  457. }
  458. }
  459. static void perf_top__sort_new_samples(void *arg)
  460. {
  461. struct perf_top *t = arg;
  462. perf_top__reset_sample_counters(t);
  463. if (t->evlist->selected != NULL)
  464. t->sym_evsel = t->evlist->selected;
  465. hists__collapse_resort_threaded(&t->sym_evsel->hists);
  466. hists__output_resort_threaded(&t->sym_evsel->hists);
  467. hists__decay_entries_threaded(&t->sym_evsel->hists,
  468. top.hide_user_symbols,
  469. top.hide_kernel_symbols);
  470. }
  471. static void *display_thread_tui(void *arg __used)
  472. {
  473. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  474. perf_top__sort_new_samples(&top);
  475. perf_evlist__tui_browse_hists(top.evlist, help,
  476. perf_top__sort_new_samples,
  477. &top, top.delay_secs);
  478. exit_browser(0);
  479. exit(0);
  480. return NULL;
  481. }
  482. static void *display_thread(void *arg __used)
  483. {
  484. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  485. struct termios tc, save;
  486. int delay_msecs, c;
  487. tcgetattr(0, &save);
  488. tc = save;
  489. tc.c_lflag &= ~(ICANON | ECHO);
  490. tc.c_cc[VMIN] = 0;
  491. tc.c_cc[VTIME] = 0;
  492. pthread__unblock_sigwinch();
  493. repeat:
  494. delay_msecs = top.delay_secs * 1000;
  495. tcsetattr(0, TCSANOW, &tc);
  496. /* trash return*/
  497. getc(stdin);
  498. while (1) {
  499. print_sym_table();
  500. /*
  501. * Either timeout expired or we got an EINTR due to SIGWINCH,
  502. * refresh screen in both cases.
  503. */
  504. switch (poll(&stdin_poll, 1, delay_msecs)) {
  505. case 0:
  506. continue;
  507. case -1:
  508. if (errno == EINTR)
  509. continue;
  510. /* Fall trhu */
  511. default:
  512. goto process_hotkey;
  513. }
  514. }
  515. process_hotkey:
  516. c = getc(stdin);
  517. tcsetattr(0, TCSAFLUSH, &save);
  518. handle_keypress(c);
  519. goto repeat;
  520. return NULL;
  521. }
  522. /* Tag samples to be skipped. */
  523. static const char *skip_symbols[] = {
  524. "default_idle",
  525. "native_safe_halt",
  526. "cpu_idle",
  527. "enter_idle",
  528. "exit_idle",
  529. "mwait_idle",
  530. "mwait_idle_with_hints",
  531. "poll_idle",
  532. "ppc64_runlatch_off",
  533. "pseries_dedicated_idle_sleep",
  534. NULL
  535. };
  536. static int symbol_filter(struct map *map __used, struct symbol *sym)
  537. {
  538. const char *name = sym->name;
  539. int i;
  540. /*
  541. * ppc64 uses function descriptors and appends a '.' to the
  542. * start of every instruction address. Remove it.
  543. */
  544. if (name[0] == '.')
  545. name++;
  546. if (!strcmp(name, "_text") ||
  547. !strcmp(name, "_etext") ||
  548. !strcmp(name, "_sinittext") ||
  549. !strncmp("init_module", name, 11) ||
  550. !strncmp("cleanup_module", name, 14) ||
  551. strstr(name, "_text_start") ||
  552. strstr(name, "_text_end"))
  553. return 1;
  554. for (i = 0; skip_symbols[i]; i++) {
  555. if (!strcmp(skip_symbols[i], name)) {
  556. sym->ignore = true;
  557. break;
  558. }
  559. }
  560. return 0;
  561. }
  562. static void perf_event__process_sample(const union perf_event *event,
  563. struct perf_evsel *evsel,
  564. struct perf_sample *sample,
  565. struct perf_session *session)
  566. {
  567. struct symbol *parent = NULL;
  568. u64 ip = event->ip.ip;
  569. struct addr_location al;
  570. struct machine *machine;
  571. int err;
  572. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  573. ++top.samples;
  574. switch (origin) {
  575. case PERF_RECORD_MISC_USER:
  576. ++top.us_samples;
  577. if (top.hide_user_symbols)
  578. return;
  579. machine = perf_session__find_host_machine(session);
  580. break;
  581. case PERF_RECORD_MISC_KERNEL:
  582. ++top.kernel_samples;
  583. if (top.hide_kernel_symbols)
  584. return;
  585. machine = perf_session__find_host_machine(session);
  586. break;
  587. case PERF_RECORD_MISC_GUEST_KERNEL:
  588. ++top.guest_kernel_samples;
  589. machine = perf_session__find_machine(session, event->ip.pid);
  590. break;
  591. case PERF_RECORD_MISC_GUEST_USER:
  592. ++top.guest_us_samples;
  593. /*
  594. * TODO: we don't process guest user from host side
  595. * except simple counting.
  596. */
  597. return;
  598. default:
  599. return;
  600. }
  601. if (!machine && perf_guest) {
  602. pr_err("Can't find guest [%d]'s kernel information\n",
  603. event->ip.pid);
  604. return;
  605. }
  606. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  607. top.exact_samples++;
  608. if (perf_event__preprocess_sample(event, session, &al, sample,
  609. symbol_filter) < 0 ||
  610. al.filtered)
  611. return;
  612. if (!kptr_restrict_warned &&
  613. symbol_conf.kptr_restrict &&
  614. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  615. ui__warning(
  616. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  617. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  618. "Kernel%s samples will not be resolved.\n",
  619. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  620. " modules" : "");
  621. if (use_browser <= 0)
  622. sleep(5);
  623. kptr_restrict_warned = true;
  624. }
  625. if (al.sym == NULL) {
  626. const char *msg = "Kernel samples will not be resolved.\n";
  627. /*
  628. * As we do lazy loading of symtabs we only will know if the
  629. * specified vmlinux file is invalid when we actually have a
  630. * hit in kernel space and then try to load it. So if we get
  631. * here and there are _no_ symbols in the DSO backing the
  632. * kernel map, bail out.
  633. *
  634. * We may never get here, for instance, if we use -K/
  635. * --hide-kernel-symbols, even if the user specifies an
  636. * invalid --vmlinux ;-)
  637. */
  638. if (!kptr_restrict_warned && !vmlinux_warned &&
  639. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  640. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  641. if (symbol_conf.vmlinux_name) {
  642. ui__warning("The %s file can't be used.\n%s",
  643. symbol_conf.vmlinux_name, msg);
  644. } else {
  645. ui__warning("A vmlinux file was not found.\n%s",
  646. msg);
  647. }
  648. if (use_browser <= 0)
  649. sleep(5);
  650. vmlinux_warned = true;
  651. }
  652. }
  653. if (al.sym == NULL || !al.sym->ignore) {
  654. struct hist_entry *he;
  655. if ((sort__has_parent || symbol_conf.use_callchain) &&
  656. sample->callchain) {
  657. err = perf_session__resolve_callchain(session, evsel, al.thread,
  658. sample->callchain, &parent);
  659. if (err)
  660. return;
  661. }
  662. he = perf_session__add_hist_entry(session, &al, sample, evsel);
  663. if (he == NULL) {
  664. pr_err("Problem incrementing symbol period, skipping event\n");
  665. return;
  666. }
  667. if (symbol_conf.use_callchain) {
  668. err = callchain_append(he->callchain, &evsel->hists.callchain_cursor,
  669. sample->period);
  670. if (err)
  671. return;
  672. }
  673. if (sort_has_symbols)
  674. record_precise_ip(he, evsel->idx, ip);
  675. }
  676. return;
  677. }
  678. static void perf_session__mmap_read_idx(struct perf_session *self, int idx)
  679. {
  680. struct perf_sample sample;
  681. struct perf_evsel *evsel;
  682. union perf_event *event;
  683. int ret;
  684. while ((event = perf_evlist__mmap_read(top.evlist, idx)) != NULL) {
  685. ret = perf_session__parse_sample(self, event, &sample);
  686. if (ret) {
  687. pr_err("Can't parse sample, err = %d\n", ret);
  688. continue;
  689. }
  690. evsel = perf_evlist__id2evsel(self->evlist, sample.id);
  691. assert(evsel != NULL);
  692. if (event->header.type == PERF_RECORD_SAMPLE)
  693. perf_event__process_sample(event, evsel, &sample, self);
  694. else if (event->header.type < PERF_RECORD_MAX) {
  695. hists__inc_nr_events(&evsel->hists, event->header.type);
  696. perf_event__process(event, &sample, self);
  697. } else
  698. ++self->hists.stats.nr_unknown_events;
  699. }
  700. }
  701. static void perf_session__mmap_read(struct perf_session *self)
  702. {
  703. int i;
  704. for (i = 0; i < top.evlist->nr_mmaps; i++)
  705. perf_session__mmap_read_idx(self, i);
  706. }
  707. static void start_counters(struct perf_evlist *evlist)
  708. {
  709. struct perf_evsel *counter, *first;
  710. first = list_entry(evlist->entries.next, struct perf_evsel, node);
  711. list_for_each_entry(counter, &evlist->entries, node) {
  712. struct perf_event_attr *attr = &counter->attr;
  713. struct xyarray *group_fd = NULL;
  714. if (group && counter != first)
  715. group_fd = first->fd;
  716. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  717. if (top.freq) {
  718. attr->sample_type |= PERF_SAMPLE_PERIOD;
  719. attr->freq = 1;
  720. attr->sample_freq = top.freq;
  721. }
  722. if (evlist->nr_entries > 1) {
  723. attr->sample_type |= PERF_SAMPLE_ID;
  724. attr->read_format |= PERF_FORMAT_ID;
  725. }
  726. if (symbol_conf.use_callchain)
  727. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  728. attr->mmap = 1;
  729. attr->comm = 1;
  730. attr->inherit = inherit;
  731. retry_sample_id:
  732. attr->sample_id_all = sample_id_all_avail ? 1 : 0;
  733. try_again:
  734. if (perf_evsel__open(counter, top.evlist->cpus,
  735. top.evlist->threads, group,
  736. group_fd) < 0) {
  737. int err = errno;
  738. if (err == EPERM || err == EACCES) {
  739. ui__error_paranoid();
  740. goto out_err;
  741. } else if (err == EINVAL && sample_id_all_avail) {
  742. /*
  743. * Old kernel, no attr->sample_id_type_all field
  744. */
  745. sample_id_all_avail = false;
  746. goto retry_sample_id;
  747. }
  748. /*
  749. * If it's cycles then fall back to hrtimer
  750. * based cpu-clock-tick sw counter, which
  751. * is always available even if no PMU support:
  752. */
  753. if (attr->type == PERF_TYPE_HARDWARE &&
  754. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  755. if (verbose)
  756. ui__warning("Cycles event not supported,\n"
  757. "trying to fall back to cpu-clock-ticks\n");
  758. attr->type = PERF_TYPE_SOFTWARE;
  759. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  760. goto try_again;
  761. }
  762. if (err == ENOENT) {
  763. ui__warning("The %s event is not supported.\n",
  764. event_name(counter));
  765. goto out_err;
  766. }
  767. ui__warning("The sys_perf_event_open() syscall "
  768. "returned with %d (%s). /bin/dmesg "
  769. "may provide additional information.\n"
  770. "No CONFIG_PERF_EVENTS=y kernel support "
  771. "configured?\n", err, strerror(err));
  772. goto out_err;
  773. }
  774. }
  775. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0) {
  776. ui__warning("Failed to mmap with %d (%s)\n",
  777. errno, strerror(errno));
  778. goto out_err;
  779. }
  780. return;
  781. out_err:
  782. exit_browser(0);
  783. exit(0);
  784. }
  785. static int setup_sample_type(void)
  786. {
  787. if (!sort_has_symbols) {
  788. if (symbol_conf.use_callchain) {
  789. ui__warning("Selected -g but \"sym\" not present in --sort/-s.");
  790. return -EINVAL;
  791. }
  792. } else if (!dont_use_callchains && callchain_param.mode != CHAIN_NONE) {
  793. if (callchain_register_param(&callchain_param) < 0) {
  794. ui__warning("Can't register callchain params.\n");
  795. return -EINVAL;
  796. }
  797. }
  798. return 0;
  799. }
  800. static int __cmd_top(void)
  801. {
  802. pthread_t thread;
  803. int ret;
  804. /*
  805. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  806. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  807. */
  808. top.session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  809. if (top.session == NULL)
  810. return -ENOMEM;
  811. ret = setup_sample_type();
  812. if (ret)
  813. goto out_delete;
  814. if (top.target_tid != -1)
  815. perf_event__synthesize_thread_map(top.evlist->threads,
  816. perf_event__process, top.session);
  817. else
  818. perf_event__synthesize_threads(perf_event__process, top.session);
  819. start_counters(top.evlist);
  820. top.session->evlist = top.evlist;
  821. perf_session__update_sample_type(top.session);
  822. /* Wait for a minimal set of events before starting the snapshot */
  823. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  824. perf_session__mmap_read(top.session);
  825. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  826. display_thread), NULL)) {
  827. printf("Could not create display thread.\n");
  828. exit(-1);
  829. }
  830. if (realtime_prio) {
  831. struct sched_param param;
  832. param.sched_priority = realtime_prio;
  833. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  834. printf("Could not set realtime priority.\n");
  835. exit(-1);
  836. }
  837. }
  838. while (1) {
  839. u64 hits = top.samples;
  840. perf_session__mmap_read(top.session);
  841. if (hits == top.samples)
  842. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  843. }
  844. out_delete:
  845. perf_session__delete(top.session);
  846. top.session = NULL;
  847. return 0;
  848. }
  849. static int
  850. parse_callchain_opt(const struct option *opt __used, const char *arg,
  851. int unset)
  852. {
  853. char *tok, *tok2;
  854. char *endptr;
  855. /*
  856. * --no-call-graph
  857. */
  858. if (unset) {
  859. dont_use_callchains = true;
  860. return 0;
  861. }
  862. symbol_conf.use_callchain = true;
  863. if (!arg)
  864. return 0;
  865. tok = strtok((char *)arg, ",");
  866. if (!tok)
  867. return -1;
  868. /* get the output mode */
  869. if (!strncmp(tok, "graph", strlen(arg)))
  870. callchain_param.mode = CHAIN_GRAPH_ABS;
  871. else if (!strncmp(tok, "flat", strlen(arg)))
  872. callchain_param.mode = CHAIN_FLAT;
  873. else if (!strncmp(tok, "fractal", strlen(arg)))
  874. callchain_param.mode = CHAIN_GRAPH_REL;
  875. else if (!strncmp(tok, "none", strlen(arg))) {
  876. callchain_param.mode = CHAIN_NONE;
  877. symbol_conf.use_callchain = false;
  878. return 0;
  879. }
  880. else
  881. return -1;
  882. /* get the min percentage */
  883. tok = strtok(NULL, ",");
  884. if (!tok)
  885. goto setup;
  886. callchain_param.min_percent = strtod(tok, &endptr);
  887. if (tok == endptr)
  888. return -1;
  889. /* get the print limit */
  890. tok2 = strtok(NULL, ",");
  891. if (!tok2)
  892. goto setup;
  893. if (tok2[0] != 'c') {
  894. callchain_param.print_limit = strtod(tok2, &endptr);
  895. tok2 = strtok(NULL, ",");
  896. if (!tok2)
  897. goto setup;
  898. }
  899. /* get the call chain order */
  900. if (!strcmp(tok2, "caller"))
  901. callchain_param.order = ORDER_CALLER;
  902. else if (!strcmp(tok2, "callee"))
  903. callchain_param.order = ORDER_CALLEE;
  904. else
  905. return -1;
  906. setup:
  907. if (callchain_register_param(&callchain_param) < 0) {
  908. fprintf(stderr, "Can't register callchain params\n");
  909. return -1;
  910. }
  911. return 0;
  912. }
  913. static const char * const top_usage[] = {
  914. "perf top [<options>]",
  915. NULL
  916. };
  917. static const struct option options[] = {
  918. OPT_CALLBACK('e', "event", &top.evlist, "event",
  919. "event selector. use 'perf list' to list available events",
  920. parse_events_option),
  921. OPT_INTEGER('c', "count", &default_interval,
  922. "event period to sample"),
  923. OPT_INTEGER('p', "pid", &top.target_pid,
  924. "profile events on existing process id"),
  925. OPT_INTEGER('t', "tid", &top.target_tid,
  926. "profile events on existing thread id"),
  927. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  928. "system-wide collection from all CPUs"),
  929. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  930. "list of cpus to monitor"),
  931. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  932. "file", "vmlinux pathname"),
  933. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  934. "hide kernel symbols"),
  935. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  936. OPT_INTEGER('r', "realtime", &realtime_prio,
  937. "collect data with this RT SCHED_FIFO priority"),
  938. OPT_INTEGER('d', "delay", &top.delay_secs,
  939. "number of seconds to delay between refreshes"),
  940. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  941. "dump the symbol table used for profiling"),
  942. OPT_INTEGER('f', "count-filter", &top.count_filter,
  943. "only display functions with more events than this"),
  944. OPT_BOOLEAN('g', "group", &group,
  945. "put the counters into a counter group"),
  946. OPT_BOOLEAN('i', "inherit", &inherit,
  947. "child tasks inherit counters"),
  948. OPT_STRING(0, "sym-annotate", &sym_filter, "symbol name",
  949. "symbol to annotate"),
  950. OPT_BOOLEAN('z', "zero", &top.zero,
  951. "zero history across updates"),
  952. OPT_INTEGER('F', "freq", &top.freq,
  953. "profile at this frequency"),
  954. OPT_INTEGER('E', "entries", &top.print_entries,
  955. "display this many functions"),
  956. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  957. "hide user symbols"),
  958. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  959. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  960. OPT_INCR('v', "verbose", &verbose,
  961. "be more verbose (show counter open errors, etc)"),
  962. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  963. "sort by key(s): pid, comm, dso, symbol, parent"),
  964. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  965. "Show a column with the number of samples"),
  966. OPT_CALLBACK_DEFAULT('G', "call-graph", NULL, "output_type,min_percent, call_order",
  967. "Display callchains using output_type (graph, flat, fractal, or none), min percent threshold and callchain order. "
  968. "Default: fractal,0.5,callee", &parse_callchain_opt,
  969. callchain_default_opt),
  970. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  971. "Show a column with the sum of periods"),
  972. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  973. "only consider symbols in these dsos"),
  974. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  975. "only consider symbols in these comms"),
  976. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  977. "only consider these symbols"),
  978. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  979. "Interleave source code with assembly code (default)"),
  980. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  981. "Display raw encoding of assembly instructions (default)"),
  982. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  983. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  984. OPT_END()
  985. };
  986. int cmd_top(int argc, const char **argv, const char *prefix __used)
  987. {
  988. struct perf_evsel *pos;
  989. int status = -ENOMEM;
  990. top.evlist = perf_evlist__new(NULL, NULL);
  991. if (top.evlist == NULL)
  992. return -ENOMEM;
  993. symbol_conf.exclude_other = false;
  994. argc = parse_options(argc, argv, options, top_usage, 0);
  995. if (argc)
  996. usage_with_options(top_usage, options);
  997. if (sort_order == default_sort_order)
  998. sort_order = "dso,symbol";
  999. setup_sorting(top_usage, options);
  1000. if (use_stdio)
  1001. use_browser = 0;
  1002. else if (use_tui)
  1003. use_browser = 1;
  1004. setup_browser(false);
  1005. /* CPU and PID are mutually exclusive */
  1006. if (top.target_tid > 0 && top.cpu_list) {
  1007. printf("WARNING: PID switch overriding CPU\n");
  1008. sleep(1);
  1009. top.cpu_list = NULL;
  1010. }
  1011. if (top.target_pid != -1)
  1012. top.target_tid = top.target_pid;
  1013. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  1014. top.target_tid, top.cpu_list) < 0)
  1015. usage_with_options(top_usage, options);
  1016. if (!top.evlist->nr_entries &&
  1017. perf_evlist__add_default(top.evlist) < 0) {
  1018. pr_err("Not enough memory for event selector list\n");
  1019. return -ENOMEM;
  1020. }
  1021. symbol_conf.nr_events = top.evlist->nr_entries;
  1022. if (top.delay_secs < 1)
  1023. top.delay_secs = 1;
  1024. /*
  1025. * User specified count overrides default frequency.
  1026. */
  1027. if (default_interval)
  1028. top.freq = 0;
  1029. else if (top.freq) {
  1030. default_interval = top.freq;
  1031. } else {
  1032. fprintf(stderr, "frequency and count are zero, aborting\n");
  1033. exit(EXIT_FAILURE);
  1034. }
  1035. list_for_each_entry(pos, &top.evlist->entries, node) {
  1036. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  1037. top.evlist->threads->nr) < 0)
  1038. goto out_free_fd;
  1039. /*
  1040. * Fill in the ones not specifically initialized via -c:
  1041. */
  1042. if (pos->attr.sample_period)
  1043. continue;
  1044. pos->attr.sample_period = default_interval;
  1045. }
  1046. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  1047. perf_evlist__alloc_mmap(top.evlist) < 0)
  1048. goto out_free_fd;
  1049. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  1050. symbol_conf.priv_size = sizeof(struct annotation);
  1051. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1052. if (symbol__init() < 0)
  1053. return -1;
  1054. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  1055. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  1056. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  1057. /*
  1058. * Avoid annotation data structures overhead when symbols aren't on the
  1059. * sort list.
  1060. */
  1061. sort_has_symbols = sort_sym.list.next != NULL;
  1062. get_term_dimensions(&winsize);
  1063. if (top.print_entries == 0) {
  1064. update_print_entries(&winsize);
  1065. signal(SIGWINCH, sig_winch_handler);
  1066. }
  1067. status = __cmd_top();
  1068. out_free_fd:
  1069. perf_evlist__delete(top.evlist);
  1070. return status;
  1071. }