builtin-top.c 32 KB

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