builtin-top.c 32 KB

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