builtin-top.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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 *perf_evsel__add_hist_entry(struct perf_evsel *evsel,
  211. struct addr_location *al,
  212. struct perf_sample *sample)
  213. {
  214. struct hist_entry *he;
  215. he = __hists__add_entry(&evsel->hists, al, NULL, sample->period);
  216. if (he == NULL)
  217. return NULL;
  218. evsel->hists.stats.total_period += sample->period;
  219. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  220. return he;
  221. }
  222. static void print_sym_table(void)
  223. {
  224. char bf[160];
  225. int printed = 0;
  226. const int win_width = winsize.ws_col - 1;
  227. puts(CONSOLE_CLEAR);
  228. perf_top__header_snprintf(&top, bf, sizeof(bf));
  229. printf("%s\n", bf);
  230. perf_top__reset_sample_counters(&top);
  231. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  232. if (top.sym_evsel->hists.stats.nr_lost_warned !=
  233. top.sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  234. top.sym_evsel->hists.stats.nr_lost_warned =
  235. top.sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  236. color_fprintf(stdout, PERF_COLOR_RED,
  237. "WARNING: LOST %d chunks, Check IO/CPU overload",
  238. top.sym_evsel->hists.stats.nr_lost_warned);
  239. ++printed;
  240. }
  241. if (top.sym_filter_entry) {
  242. show_details(top.sym_filter_entry);
  243. return;
  244. }
  245. hists__collapse_resort_threaded(&top.sym_evsel->hists);
  246. hists__output_resort_threaded(&top.sym_evsel->hists);
  247. hists__decay_entries_threaded(&top.sym_evsel->hists,
  248. top.hide_user_symbols,
  249. top.hide_kernel_symbols);
  250. hists__output_recalc_col_len(&top.sym_evsel->hists, winsize.ws_row - 3);
  251. putchar('\n');
  252. hists__fprintf(&top.sym_evsel->hists, NULL, false, false,
  253. winsize.ws_row - 4 - printed, win_width, stdout);
  254. }
  255. static void prompt_integer(int *target, const char *msg)
  256. {
  257. char *buf = malloc(0), *p;
  258. size_t dummy = 0;
  259. int tmp;
  260. fprintf(stdout, "\n%s: ", msg);
  261. if (getline(&buf, &dummy, stdin) < 0)
  262. return;
  263. p = strchr(buf, '\n');
  264. if (p)
  265. *p = 0;
  266. p = buf;
  267. while(*p) {
  268. if (!isdigit(*p))
  269. goto out_free;
  270. p++;
  271. }
  272. tmp = strtoul(buf, NULL, 10);
  273. *target = tmp;
  274. out_free:
  275. free(buf);
  276. }
  277. static void prompt_percent(int *target, const char *msg)
  278. {
  279. int tmp = 0;
  280. prompt_integer(&tmp, msg);
  281. if (tmp >= 0 && tmp <= 100)
  282. *target = tmp;
  283. }
  284. static void prompt_symbol(struct hist_entry **target, const char *msg)
  285. {
  286. char *buf = malloc(0), *p;
  287. struct hist_entry *syme = *target, *n, *found = NULL;
  288. struct rb_node *next;
  289. size_t dummy = 0;
  290. /* zero counters of active symbol */
  291. if (syme) {
  292. __zero_source_counters(syme);
  293. *target = NULL;
  294. }
  295. fprintf(stdout, "\n%s: ", msg);
  296. if (getline(&buf, &dummy, stdin) < 0)
  297. goto out_free;
  298. p = strchr(buf, '\n');
  299. if (p)
  300. *p = 0;
  301. next = rb_first(&top.sym_evsel->hists.entries);
  302. while (next) {
  303. n = rb_entry(next, struct hist_entry, rb_node);
  304. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  305. found = n;
  306. break;
  307. }
  308. next = rb_next(&n->rb_node);
  309. }
  310. if (!found) {
  311. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  312. sleep(1);
  313. return;
  314. } else
  315. parse_source(found);
  316. out_free:
  317. free(buf);
  318. }
  319. static void print_mapped_keys(void)
  320. {
  321. char *name = NULL;
  322. if (top.sym_filter_entry) {
  323. struct symbol *sym = top.sym_filter_entry->ms.sym;
  324. name = sym->name;
  325. }
  326. fprintf(stdout, "\nMapped keys:\n");
  327. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top.delay_secs);
  328. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top.print_entries);
  329. if (top.evlist->nr_entries > 1)
  330. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top.sym_evsel));
  331. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top.count_filter);
  332. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  333. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  334. fprintf(stdout, "\t[S] stop annotation.\n");
  335. fprintf(stdout,
  336. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  337. top.hide_kernel_symbols ? "yes" : "no");
  338. fprintf(stdout,
  339. "\t[U] hide user symbols. \t(%s)\n",
  340. top.hide_user_symbols ? "yes" : "no");
  341. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top.zero ? 1 : 0);
  342. fprintf(stdout, "\t[qQ] quit.\n");
  343. }
  344. static int key_mapped(int c)
  345. {
  346. switch (c) {
  347. case 'd':
  348. case 'e':
  349. case 'f':
  350. case 'z':
  351. case 'q':
  352. case 'Q':
  353. case 'K':
  354. case 'U':
  355. case 'F':
  356. case 's':
  357. case 'S':
  358. return 1;
  359. case 'E':
  360. return top.evlist->nr_entries > 1 ? 1 : 0;
  361. default:
  362. break;
  363. }
  364. return 0;
  365. }
  366. static void handle_keypress(int c)
  367. {
  368. if (!key_mapped(c)) {
  369. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  370. struct termios tc, save;
  371. print_mapped_keys();
  372. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  373. fflush(stdout);
  374. tcgetattr(0, &save);
  375. tc = save;
  376. tc.c_lflag &= ~(ICANON | ECHO);
  377. tc.c_cc[VMIN] = 0;
  378. tc.c_cc[VTIME] = 0;
  379. tcsetattr(0, TCSANOW, &tc);
  380. poll(&stdin_poll, 1, -1);
  381. c = getc(stdin);
  382. tcsetattr(0, TCSAFLUSH, &save);
  383. if (!key_mapped(c))
  384. return;
  385. }
  386. switch (c) {
  387. case 'd':
  388. prompt_integer(&top.delay_secs, "Enter display delay");
  389. if (top.delay_secs < 1)
  390. top.delay_secs = 1;
  391. break;
  392. case 'e':
  393. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  394. if (top.print_entries == 0) {
  395. sig_winch_handler(SIGWINCH);
  396. signal(SIGWINCH, sig_winch_handler);
  397. } else
  398. signal(SIGWINCH, SIG_DFL);
  399. break;
  400. case 'E':
  401. if (top.evlist->nr_entries > 1) {
  402. /* Select 0 as the default event: */
  403. int counter = 0;
  404. fprintf(stderr, "\nAvailable events:");
  405. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  406. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  407. prompt_integer(&counter, "Enter details event counter");
  408. if (counter >= top.evlist->nr_entries) {
  409. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  410. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  411. sleep(1);
  412. break;
  413. }
  414. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  415. if (top.sym_evsel->idx == counter)
  416. break;
  417. } else
  418. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  419. break;
  420. case 'f':
  421. prompt_integer(&top.count_filter, "Enter display event count filter");
  422. break;
  423. case 'F':
  424. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  425. break;
  426. case 'K':
  427. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  428. break;
  429. case 'q':
  430. case 'Q':
  431. printf("exiting.\n");
  432. if (dump_symtab)
  433. perf_session__fprintf_dsos(top.session, stderr);
  434. exit(0);
  435. case 's':
  436. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  437. break;
  438. case 'S':
  439. if (!top.sym_filter_entry)
  440. break;
  441. else {
  442. struct hist_entry *syme = top.sym_filter_entry;
  443. top.sym_filter_entry = NULL;
  444. __zero_source_counters(syme);
  445. }
  446. break;
  447. case 'U':
  448. top.hide_user_symbols = !top.hide_user_symbols;
  449. break;
  450. case 'z':
  451. top.zero = !top.zero;
  452. break;
  453. default:
  454. break;
  455. }
  456. }
  457. static void perf_top__sort_new_samples(void *arg)
  458. {
  459. struct perf_top *t = arg;
  460. perf_top__reset_sample_counters(t);
  461. if (t->evlist->selected != NULL)
  462. t->sym_evsel = t->evlist->selected;
  463. hists__collapse_resort_threaded(&t->sym_evsel->hists);
  464. hists__output_resort_threaded(&t->sym_evsel->hists);
  465. hists__decay_entries_threaded(&t->sym_evsel->hists,
  466. top.hide_user_symbols,
  467. top.hide_kernel_symbols);
  468. }
  469. static void *display_thread_tui(void *arg __used)
  470. {
  471. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  472. perf_top__sort_new_samples(&top);
  473. perf_evlist__tui_browse_hists(top.evlist, help,
  474. perf_top__sort_new_samples,
  475. &top, top.delay_secs);
  476. exit_browser(0);
  477. exit(0);
  478. return NULL;
  479. }
  480. static void *display_thread(void *arg __used)
  481. {
  482. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  483. struct termios tc, save;
  484. int delay_msecs, c;
  485. tcgetattr(0, &save);
  486. tc = save;
  487. tc.c_lflag &= ~(ICANON | ECHO);
  488. tc.c_cc[VMIN] = 0;
  489. tc.c_cc[VTIME] = 0;
  490. pthread__unblock_sigwinch();
  491. repeat:
  492. delay_msecs = top.delay_secs * 1000;
  493. tcsetattr(0, TCSANOW, &tc);
  494. /* trash return*/
  495. getc(stdin);
  496. while (1) {
  497. print_sym_table();
  498. /*
  499. * Either timeout expired or we got an EINTR due to SIGWINCH,
  500. * refresh screen in both cases.
  501. */
  502. switch (poll(&stdin_poll, 1, delay_msecs)) {
  503. case 0:
  504. continue;
  505. case -1:
  506. if (errno == EINTR)
  507. continue;
  508. /* Fall trhu */
  509. default:
  510. goto process_hotkey;
  511. }
  512. }
  513. process_hotkey:
  514. c = getc(stdin);
  515. tcsetattr(0, TCSAFLUSH, &save);
  516. handle_keypress(c);
  517. goto repeat;
  518. return NULL;
  519. }
  520. /* Tag samples to be skipped. */
  521. static const char *skip_symbols[] = {
  522. "default_idle",
  523. "native_safe_halt",
  524. "cpu_idle",
  525. "enter_idle",
  526. "exit_idle",
  527. "mwait_idle",
  528. "mwait_idle_with_hints",
  529. "poll_idle",
  530. "ppc64_runlatch_off",
  531. "pseries_dedicated_idle_sleep",
  532. NULL
  533. };
  534. static int symbol_filter(struct map *map __used, struct symbol *sym)
  535. {
  536. const char *name = sym->name;
  537. int i;
  538. /*
  539. * ppc64 uses function descriptors and appends a '.' to the
  540. * start of every instruction address. Remove it.
  541. */
  542. if (name[0] == '.')
  543. name++;
  544. if (!strcmp(name, "_text") ||
  545. !strcmp(name, "_etext") ||
  546. !strcmp(name, "_sinittext") ||
  547. !strncmp("init_module", name, 11) ||
  548. !strncmp("cleanup_module", name, 14) ||
  549. strstr(name, "_text_start") ||
  550. strstr(name, "_text_end"))
  551. return 1;
  552. for (i = 0; skip_symbols[i]; i++) {
  553. if (!strcmp(skip_symbols[i], name)) {
  554. sym->ignore = true;
  555. break;
  556. }
  557. }
  558. return 0;
  559. }
  560. static void perf_event__process_sample(const union perf_event *event,
  561. struct perf_evsel *evsel,
  562. struct perf_sample *sample,
  563. struct machine *machine)
  564. {
  565. struct symbol *parent = NULL;
  566. u64 ip = event->ip.ip;
  567. struct addr_location al;
  568. int err;
  569. if (!machine && perf_guest) {
  570. pr_err("Can't find guest [%d]'s kernel information\n",
  571. event->ip.pid);
  572. return;
  573. }
  574. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  575. top.exact_samples++;
  576. if (perf_event__preprocess_sample(event, machine, &al, sample,
  577. symbol_filter) < 0 ||
  578. al.filtered)
  579. return;
  580. if (!kptr_restrict_warned &&
  581. symbol_conf.kptr_restrict &&
  582. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  583. ui__warning(
  584. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  585. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  586. "Kernel%s samples will not be resolved.\n",
  587. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  588. " modules" : "");
  589. if (use_browser <= 0)
  590. sleep(5);
  591. kptr_restrict_warned = true;
  592. }
  593. if (al.sym == NULL) {
  594. const char *msg = "Kernel samples will not be resolved.\n";
  595. /*
  596. * As we do lazy loading of symtabs we only will know if the
  597. * specified vmlinux file is invalid when we actually have a
  598. * hit in kernel space and then try to load it. So if we get
  599. * here and there are _no_ symbols in the DSO backing the
  600. * kernel map, bail out.
  601. *
  602. * We may never get here, for instance, if we use -K/
  603. * --hide-kernel-symbols, even if the user specifies an
  604. * invalid --vmlinux ;-)
  605. */
  606. if (!kptr_restrict_warned && !vmlinux_warned &&
  607. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  608. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  609. if (symbol_conf.vmlinux_name) {
  610. ui__warning("The %s file can't be used.\n%s",
  611. symbol_conf.vmlinux_name, msg);
  612. } else {
  613. ui__warning("A vmlinux file was not found.\n%s",
  614. msg);
  615. }
  616. if (use_browser <= 0)
  617. sleep(5);
  618. vmlinux_warned = true;
  619. }
  620. }
  621. if (al.sym == NULL || !al.sym->ignore) {
  622. struct hist_entry *he;
  623. if ((sort__has_parent || symbol_conf.use_callchain) &&
  624. sample->callchain) {
  625. err = machine__resolve_callchain(machine, evsel, al.thread,
  626. sample->callchain, &parent);
  627. if (err)
  628. return;
  629. }
  630. he = perf_evsel__add_hist_entry(evsel, &al, sample);
  631. if (he == NULL) {
  632. pr_err("Problem incrementing symbol period, skipping event\n");
  633. return;
  634. }
  635. if (symbol_conf.use_callchain) {
  636. err = callchain_append(he->callchain, &evsel->hists.callchain_cursor,
  637. sample->period);
  638. if (err)
  639. return;
  640. }
  641. if (sort_has_symbols)
  642. record_precise_ip(he, evsel->idx, ip);
  643. }
  644. return;
  645. }
  646. static void perf_session__mmap_read_idx(struct perf_session *self, int idx)
  647. {
  648. struct perf_sample sample;
  649. struct perf_evsel *evsel;
  650. union perf_event *event;
  651. struct machine *machine;
  652. u8 origin;
  653. int ret;
  654. while ((event = perf_evlist__mmap_read(top.evlist, idx)) != NULL) {
  655. ret = perf_session__parse_sample(self, event, &sample);
  656. if (ret) {
  657. pr_err("Can't parse sample, err = %d\n", ret);
  658. continue;
  659. }
  660. evsel = perf_evlist__id2evsel(self->evlist, sample.id);
  661. assert(evsel != NULL);
  662. origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  663. if (event->header.type == PERF_RECORD_SAMPLE)
  664. ++top.samples;
  665. switch (origin) {
  666. case PERF_RECORD_MISC_USER:
  667. ++top.us_samples;
  668. if (top.hide_user_symbols)
  669. continue;
  670. machine = perf_session__find_host_machine(self);
  671. break;
  672. case PERF_RECORD_MISC_KERNEL:
  673. ++top.kernel_samples;
  674. if (top.hide_kernel_symbols)
  675. continue;
  676. machine = perf_session__find_host_machine(self);
  677. break;
  678. case PERF_RECORD_MISC_GUEST_KERNEL:
  679. ++top.guest_kernel_samples;
  680. machine = perf_session__find_machine(self, event->ip.pid);
  681. break;
  682. case PERF_RECORD_MISC_GUEST_USER:
  683. ++top.guest_us_samples;
  684. /*
  685. * TODO: we don't process guest user from host side
  686. * except simple counting.
  687. */
  688. /* Fall thru */
  689. default:
  690. continue;
  691. }
  692. if (event->header.type == PERF_RECORD_SAMPLE)
  693. perf_event__process_sample(event, evsel, &sample, machine);
  694. else if (event->header.type < PERF_RECORD_MAX) {
  695. hists__inc_nr_events(&evsel->hists, event->header.type);
  696. perf_event__process(&top.tool, event, &sample, machine);
  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.tool, top.evlist->threads,
  816. perf_event__process,
  817. &top.session->host_machine);
  818. else
  819. perf_event__synthesize_threads(&top.tool, perf_event__process,
  820. &top.session->host_machine);
  821. start_counters(top.evlist);
  822. top.session->evlist = top.evlist;
  823. perf_session__update_sample_type(top.session);
  824. /* Wait for a minimal set of events before starting the snapshot */
  825. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  826. perf_session__mmap_read(top.session);
  827. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  828. display_thread), NULL)) {
  829. printf("Could not create display thread.\n");
  830. exit(-1);
  831. }
  832. if (realtime_prio) {
  833. struct sched_param param;
  834. param.sched_priority = realtime_prio;
  835. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  836. printf("Could not set realtime priority.\n");
  837. exit(-1);
  838. }
  839. }
  840. while (1) {
  841. u64 hits = top.samples;
  842. perf_session__mmap_read(top.session);
  843. if (hits == top.samples)
  844. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  845. }
  846. out_delete:
  847. perf_session__delete(top.session);
  848. top.session = NULL;
  849. return 0;
  850. }
  851. static int
  852. parse_callchain_opt(const struct option *opt __used, const char *arg,
  853. int unset)
  854. {
  855. char *tok, *tok2;
  856. char *endptr;
  857. /*
  858. * --no-call-graph
  859. */
  860. if (unset) {
  861. dont_use_callchains = true;
  862. return 0;
  863. }
  864. symbol_conf.use_callchain = true;
  865. if (!arg)
  866. return 0;
  867. tok = strtok((char *)arg, ",");
  868. if (!tok)
  869. return -1;
  870. /* get the output mode */
  871. if (!strncmp(tok, "graph", strlen(arg)))
  872. callchain_param.mode = CHAIN_GRAPH_ABS;
  873. else if (!strncmp(tok, "flat", strlen(arg)))
  874. callchain_param.mode = CHAIN_FLAT;
  875. else if (!strncmp(tok, "fractal", strlen(arg)))
  876. callchain_param.mode = CHAIN_GRAPH_REL;
  877. else if (!strncmp(tok, "none", strlen(arg))) {
  878. callchain_param.mode = CHAIN_NONE;
  879. symbol_conf.use_callchain = false;
  880. return 0;
  881. }
  882. else
  883. return -1;
  884. /* get the min percentage */
  885. tok = strtok(NULL, ",");
  886. if (!tok)
  887. goto setup;
  888. callchain_param.min_percent = strtod(tok, &endptr);
  889. if (tok == endptr)
  890. return -1;
  891. /* get the print limit */
  892. tok2 = strtok(NULL, ",");
  893. if (!tok2)
  894. goto setup;
  895. if (tok2[0] != 'c') {
  896. callchain_param.print_limit = strtod(tok2, &endptr);
  897. tok2 = strtok(NULL, ",");
  898. if (!tok2)
  899. goto setup;
  900. }
  901. /* get the call chain order */
  902. if (!strcmp(tok2, "caller"))
  903. callchain_param.order = ORDER_CALLER;
  904. else if (!strcmp(tok2, "callee"))
  905. callchain_param.order = ORDER_CALLEE;
  906. else
  907. return -1;
  908. setup:
  909. if (callchain_register_param(&callchain_param) < 0) {
  910. fprintf(stderr, "Can't register callchain params\n");
  911. return -1;
  912. }
  913. return 0;
  914. }
  915. static const char * const top_usage[] = {
  916. "perf top [<options>]",
  917. NULL
  918. };
  919. static const struct option options[] = {
  920. OPT_CALLBACK('e', "event", &top.evlist, "event",
  921. "event selector. use 'perf list' to list available events",
  922. parse_events_option),
  923. OPT_INTEGER('c', "count", &default_interval,
  924. "event period to sample"),
  925. OPT_INTEGER('p', "pid", &top.target_pid,
  926. "profile events on existing process id"),
  927. OPT_INTEGER('t', "tid", &top.target_tid,
  928. "profile events on existing thread id"),
  929. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  930. "system-wide collection from all CPUs"),
  931. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  932. "list of cpus to monitor"),
  933. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  934. "file", "vmlinux pathname"),
  935. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  936. "hide kernel symbols"),
  937. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  938. OPT_INTEGER('r', "realtime", &realtime_prio,
  939. "collect data with this RT SCHED_FIFO priority"),
  940. OPT_INTEGER('d', "delay", &top.delay_secs,
  941. "number of seconds to delay between refreshes"),
  942. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  943. "dump the symbol table used for profiling"),
  944. OPT_INTEGER('f', "count-filter", &top.count_filter,
  945. "only display functions with more events than this"),
  946. OPT_BOOLEAN('g', "group", &group,
  947. "put the counters into a counter group"),
  948. OPT_BOOLEAN('i', "inherit", &inherit,
  949. "child tasks inherit counters"),
  950. OPT_STRING(0, "sym-annotate", &sym_filter, "symbol name",
  951. "symbol to annotate"),
  952. OPT_BOOLEAN('z', "zero", &top.zero,
  953. "zero history across updates"),
  954. OPT_INTEGER('F', "freq", &top.freq,
  955. "profile at this frequency"),
  956. OPT_INTEGER('E', "entries", &top.print_entries,
  957. "display this many functions"),
  958. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  959. "hide user symbols"),
  960. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  961. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  962. OPT_INCR('v', "verbose", &verbose,
  963. "be more verbose (show counter open errors, etc)"),
  964. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  965. "sort by key(s): pid, comm, dso, symbol, parent"),
  966. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  967. "Show a column with the number of samples"),
  968. OPT_CALLBACK_DEFAULT('G', "call-graph", NULL, "output_type,min_percent, call_order",
  969. "Display callchains using output_type (graph, flat, fractal, or none), min percent threshold and callchain order. "
  970. "Default: fractal,0.5,callee", &parse_callchain_opt,
  971. callchain_default_opt),
  972. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  973. "Show a column with the sum of periods"),
  974. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  975. "only consider symbols in these dsos"),
  976. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  977. "only consider symbols in these comms"),
  978. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  979. "only consider these symbols"),
  980. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  981. "Interleave source code with assembly code (default)"),
  982. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  983. "Display raw encoding of assembly instructions (default)"),
  984. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  985. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  986. OPT_END()
  987. };
  988. int cmd_top(int argc, const char **argv, const char *prefix __used)
  989. {
  990. struct perf_evsel *pos;
  991. int status = -ENOMEM;
  992. top.evlist = perf_evlist__new(NULL, NULL);
  993. if (top.evlist == NULL)
  994. return -ENOMEM;
  995. symbol_conf.exclude_other = false;
  996. argc = parse_options(argc, argv, options, top_usage, 0);
  997. if (argc)
  998. usage_with_options(top_usage, options);
  999. if (sort_order == default_sort_order)
  1000. sort_order = "dso,symbol";
  1001. setup_sorting(top_usage, options);
  1002. if (use_stdio)
  1003. use_browser = 0;
  1004. else if (use_tui)
  1005. use_browser = 1;
  1006. setup_browser(false);
  1007. /* CPU and PID are mutually exclusive */
  1008. if (top.target_tid > 0 && top.cpu_list) {
  1009. printf("WARNING: PID switch overriding CPU\n");
  1010. sleep(1);
  1011. top.cpu_list = NULL;
  1012. }
  1013. if (top.target_pid != -1)
  1014. top.target_tid = top.target_pid;
  1015. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  1016. top.target_tid, top.cpu_list) < 0)
  1017. usage_with_options(top_usage, options);
  1018. if (!top.evlist->nr_entries &&
  1019. perf_evlist__add_default(top.evlist) < 0) {
  1020. pr_err("Not enough memory for event selector list\n");
  1021. return -ENOMEM;
  1022. }
  1023. symbol_conf.nr_events = top.evlist->nr_entries;
  1024. if (top.delay_secs < 1)
  1025. top.delay_secs = 1;
  1026. /*
  1027. * User specified count overrides default frequency.
  1028. */
  1029. if (default_interval)
  1030. top.freq = 0;
  1031. else if (top.freq) {
  1032. default_interval = top.freq;
  1033. } else {
  1034. fprintf(stderr, "frequency and count are zero, aborting\n");
  1035. exit(EXIT_FAILURE);
  1036. }
  1037. list_for_each_entry(pos, &top.evlist->entries, node) {
  1038. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  1039. top.evlist->threads->nr) < 0)
  1040. goto out_free_fd;
  1041. /*
  1042. * Fill in the ones not specifically initialized via -c:
  1043. */
  1044. if (pos->attr.sample_period)
  1045. continue;
  1046. pos->attr.sample_period = default_interval;
  1047. }
  1048. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  1049. perf_evlist__alloc_mmap(top.evlist) < 0)
  1050. goto out_free_fd;
  1051. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  1052. symbol_conf.priv_size = sizeof(struct annotation);
  1053. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1054. if (symbol__init() < 0)
  1055. return -1;
  1056. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  1057. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  1058. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  1059. /*
  1060. * Avoid annotation data structures overhead when symbols aren't on the
  1061. * sort list.
  1062. */
  1063. sort_has_symbols = sort_sym.list.next != NULL;
  1064. get_term_dimensions(&winsize);
  1065. if (top.print_entries == 0) {
  1066. update_print_entries(&winsize);
  1067. signal(SIGWINCH, sig_winch_handler);
  1068. }
  1069. status = __cmd_top();
  1070. out_free_fd:
  1071. perf_evlist__delete(top.evlist);
  1072. return status;
  1073. }