builtin-top.c 32 KB

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