builtin-top.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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/machine.h"
  28. #include "util/session.h"
  29. #include "util/symbol.h"
  30. #include "util/thread.h"
  31. #include "util/thread_map.h"
  32. #include "util/top.h"
  33. #include "util/util.h"
  34. #include <linux/rbtree.h>
  35. #include "util/parse-options.h"
  36. #include "util/parse-events.h"
  37. #include "util/cpumap.h"
  38. #include "util/xyarray.h"
  39. #include "util/sort.h"
  40. #include "util/intlist.h"
  41. #include "arch/common.h"
  42. #include "util/debug.h"
  43. #include <assert.h>
  44. #include <elf.h>
  45. #include <fcntl.h>
  46. #include <stdio.h>
  47. #include <termios.h>
  48. #include <unistd.h>
  49. #include <inttypes.h>
  50. #include <errno.h>
  51. #include <time.h>
  52. #include <sched.h>
  53. #include <sys/syscall.h>
  54. #include <sys/ioctl.h>
  55. #include <sys/poll.h>
  56. #include <sys/prctl.h>
  57. #include <sys/wait.h>
  58. #include <sys/uio.h>
  59. #include <sys/utsname.h>
  60. #include <sys/mman.h>
  61. #include <linux/unistd.h>
  62. #include <linux/types.h>
  63. static volatile int done;
  64. #define HEADER_LINE_NR 5
  65. static void perf_top__update_print_entries(struct perf_top *top)
  66. {
  67. top->print_entries = top->winsize.ws_row - HEADER_LINE_NR;
  68. }
  69. static void perf_top__sig_winch(int sig __maybe_unused,
  70. siginfo_t *info __maybe_unused, void *arg)
  71. {
  72. struct perf_top *top = arg;
  73. get_term_dimensions(&top->winsize);
  74. perf_top__update_print_entries(top);
  75. }
  76. static int perf_top__parse_source(struct perf_top *top, struct hist_entry *he)
  77. {
  78. struct symbol *sym;
  79. struct annotation *notes;
  80. struct map *map;
  81. int err = -1;
  82. if (!he || !he->ms.sym)
  83. return -1;
  84. sym = he->ms.sym;
  85. map = he->ms.map;
  86. /*
  87. * We can't annotate with just /proc/kallsyms
  88. */
  89. if (map->dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
  90. !dso__is_kcore(map->dso)) {
  91. pr_err("Can't annotate %s: No vmlinux file was found in the "
  92. "path\n", sym->name);
  93. sleep(1);
  94. return -1;
  95. }
  96. notes = symbol__annotation(sym);
  97. if (notes->src != NULL) {
  98. pthread_mutex_lock(&notes->lock);
  99. goto out_assign;
  100. }
  101. pthread_mutex_lock(&notes->lock);
  102. if (symbol__alloc_hist(sym) < 0) {
  103. pthread_mutex_unlock(&notes->lock);
  104. pr_err("Not enough memory for annotating '%s' symbol!\n",
  105. sym->name);
  106. sleep(1);
  107. return err;
  108. }
  109. err = symbol__annotate(sym, map, 0);
  110. if (err == 0) {
  111. out_assign:
  112. top->sym_filter_entry = he;
  113. }
  114. pthread_mutex_unlock(&notes->lock);
  115. return err;
  116. }
  117. static void __zero_source_counters(struct hist_entry *he)
  118. {
  119. struct symbol *sym = he->ms.sym;
  120. symbol__annotate_zero_histograms(sym);
  121. }
  122. static void ui__warn_map_erange(struct map *map, struct symbol *sym, u64 ip)
  123. {
  124. struct utsname uts;
  125. int err = uname(&uts);
  126. ui__warning("Out of bounds address found:\n\n"
  127. "Addr: %" PRIx64 "\n"
  128. "DSO: %s %c\n"
  129. "Map: %" PRIx64 "-%" PRIx64 "\n"
  130. "Symbol: %" PRIx64 "-%" PRIx64 " %c %s\n"
  131. "Arch: %s\n"
  132. "Kernel: %s\n"
  133. "Tools: %s\n\n"
  134. "Not all samples will be on the annotation output.\n\n"
  135. "Please report to linux-kernel@vger.kernel.org\n",
  136. ip, map->dso->long_name, dso__symtab_origin(map->dso),
  137. map->start, map->end, sym->start, sym->end,
  138. sym->binding == STB_GLOBAL ? 'g' :
  139. sym->binding == STB_LOCAL ? 'l' : 'w', sym->name,
  140. err ? "[unknown]" : uts.machine,
  141. err ? "[unknown]" : uts.release, perf_version_string);
  142. if (use_browser <= 0)
  143. sleep(5);
  144. map->erange_warned = true;
  145. }
  146. static void perf_top__record_precise_ip(struct perf_top *top,
  147. struct hist_entry *he,
  148. int counter, u64 ip)
  149. {
  150. struct annotation *notes;
  151. struct symbol *sym;
  152. int err = 0;
  153. if (he == NULL || he->ms.sym == NULL ||
  154. ((top->sym_filter_entry == NULL ||
  155. top->sym_filter_entry->ms.sym != he->ms.sym) && use_browser != 1))
  156. return;
  157. sym = he->ms.sym;
  158. notes = symbol__annotation(sym);
  159. if (pthread_mutex_trylock(&notes->lock))
  160. return;
  161. ip = he->ms.map->map_ip(he->ms.map, ip);
  162. if (ui__has_annotation())
  163. err = hist_entry__inc_addr_samples(he, counter, ip);
  164. pthread_mutex_unlock(&notes->lock);
  165. /*
  166. * This function is now called with he->hists->lock held.
  167. * Release it before going to sleep.
  168. */
  169. pthread_mutex_unlock(&he->hists->lock);
  170. if (err == -ERANGE && !he->ms.map->erange_warned)
  171. ui__warn_map_erange(he->ms.map, sym, ip);
  172. else if (err == -ENOMEM) {
  173. pr_err("Not enough memory for annotating '%s' symbol!\n",
  174. sym->name);
  175. sleep(1);
  176. }
  177. pthread_mutex_lock(&he->hists->lock);
  178. }
  179. static void perf_top__show_details(struct perf_top *top)
  180. {
  181. struct hist_entry *he = top->sym_filter_entry;
  182. struct annotation *notes;
  183. struct symbol *symbol;
  184. int more;
  185. if (!he)
  186. return;
  187. symbol = he->ms.sym;
  188. notes = symbol__annotation(symbol);
  189. pthread_mutex_lock(&notes->lock);
  190. if (notes->src == NULL)
  191. goto out_unlock;
  192. printf("Showing %s for %s\n", perf_evsel__name(top->sym_evsel), symbol->name);
  193. printf(" Events Pcnt (>=%d%%)\n", top->sym_pcnt_filter);
  194. more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel,
  195. 0, top->sym_pcnt_filter, top->print_entries, 4);
  196. if (top->zero)
  197. symbol__annotate_zero_histogram(symbol, top->sym_evsel->idx);
  198. else
  199. symbol__annotate_decay_histogram(symbol, top->sym_evsel->idx);
  200. if (more != 0)
  201. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  202. out_unlock:
  203. pthread_mutex_unlock(&notes->lock);
  204. }
  205. static void perf_top__print_sym_table(struct perf_top *top)
  206. {
  207. char bf[160];
  208. int printed = 0;
  209. const int win_width = top->winsize.ws_col - 1;
  210. puts(CONSOLE_CLEAR);
  211. perf_top__header_snprintf(top, bf, sizeof(bf));
  212. printf("%s\n", bf);
  213. perf_top__reset_sample_counters(top);
  214. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  215. if (top->sym_evsel->hists.stats.nr_lost_warned !=
  216. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  217. top->sym_evsel->hists.stats.nr_lost_warned =
  218. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  219. color_fprintf(stdout, PERF_COLOR_RED,
  220. "WARNING: LOST %d chunks, Check IO/CPU overload",
  221. top->sym_evsel->hists.stats.nr_lost_warned);
  222. ++printed;
  223. }
  224. if (top->sym_filter_entry) {
  225. perf_top__show_details(top);
  226. return;
  227. }
  228. hists__collapse_resort(&top->sym_evsel->hists, NULL);
  229. hists__output_resort(&top->sym_evsel->hists);
  230. hists__decay_entries(&top->sym_evsel->hists,
  231. top->hide_user_symbols,
  232. top->hide_kernel_symbols);
  233. hists__output_recalc_col_len(&top->sym_evsel->hists,
  234. top->print_entries - printed);
  235. putchar('\n');
  236. hists__fprintf(&top->sym_evsel->hists, false,
  237. top->print_entries - printed, win_width,
  238. top->min_percent, stdout);
  239. }
  240. static void prompt_integer(int *target, const char *msg)
  241. {
  242. char *buf = malloc(0), *p;
  243. size_t dummy = 0;
  244. int tmp;
  245. fprintf(stdout, "\n%s: ", msg);
  246. if (getline(&buf, &dummy, stdin) < 0)
  247. return;
  248. p = strchr(buf, '\n');
  249. if (p)
  250. *p = 0;
  251. p = buf;
  252. while(*p) {
  253. if (!isdigit(*p))
  254. goto out_free;
  255. p++;
  256. }
  257. tmp = strtoul(buf, NULL, 10);
  258. *target = tmp;
  259. out_free:
  260. free(buf);
  261. }
  262. static void prompt_percent(int *target, const char *msg)
  263. {
  264. int tmp = 0;
  265. prompt_integer(&tmp, msg);
  266. if (tmp >= 0 && tmp <= 100)
  267. *target = tmp;
  268. }
  269. static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
  270. {
  271. char *buf = malloc(0), *p;
  272. struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
  273. struct rb_node *next;
  274. size_t dummy = 0;
  275. /* zero counters of active symbol */
  276. if (syme) {
  277. __zero_source_counters(syme);
  278. top->sym_filter_entry = NULL;
  279. }
  280. fprintf(stdout, "\n%s: ", msg);
  281. if (getline(&buf, &dummy, stdin) < 0)
  282. goto out_free;
  283. p = strchr(buf, '\n');
  284. if (p)
  285. *p = 0;
  286. next = rb_first(&top->sym_evsel->hists.entries);
  287. while (next) {
  288. n = rb_entry(next, struct hist_entry, rb_node);
  289. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  290. found = n;
  291. break;
  292. }
  293. next = rb_next(&n->rb_node);
  294. }
  295. if (!found) {
  296. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  297. sleep(1);
  298. } else
  299. perf_top__parse_source(top, found);
  300. out_free:
  301. free(buf);
  302. }
  303. static void perf_top__print_mapped_keys(struct perf_top *top)
  304. {
  305. char *name = NULL;
  306. if (top->sym_filter_entry) {
  307. struct symbol *sym = top->sym_filter_entry->ms.sym;
  308. name = sym->name;
  309. }
  310. fprintf(stdout, "\nMapped keys:\n");
  311. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
  312. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
  313. if (top->evlist->nr_entries > 1)
  314. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel));
  315. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
  316. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->sym_pcnt_filter);
  317. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  318. fprintf(stdout, "\t[S] stop annotation.\n");
  319. fprintf(stdout,
  320. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  321. top->hide_kernel_symbols ? "yes" : "no");
  322. fprintf(stdout,
  323. "\t[U] hide user symbols. \t(%s)\n",
  324. top->hide_user_symbols ? "yes" : "no");
  325. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
  326. fprintf(stdout, "\t[qQ] quit.\n");
  327. }
  328. static int perf_top__key_mapped(struct perf_top *top, int c)
  329. {
  330. switch (c) {
  331. case 'd':
  332. case 'e':
  333. case 'f':
  334. case 'z':
  335. case 'q':
  336. case 'Q':
  337. case 'K':
  338. case 'U':
  339. case 'F':
  340. case 's':
  341. case 'S':
  342. return 1;
  343. case 'E':
  344. return top->evlist->nr_entries > 1 ? 1 : 0;
  345. default:
  346. break;
  347. }
  348. return 0;
  349. }
  350. static bool perf_top__handle_keypress(struct perf_top *top, int c)
  351. {
  352. bool ret = true;
  353. if (!perf_top__key_mapped(top, c)) {
  354. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  355. struct termios tc, save;
  356. perf_top__print_mapped_keys(top);
  357. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  358. fflush(stdout);
  359. tcgetattr(0, &save);
  360. tc = save;
  361. tc.c_lflag &= ~(ICANON | ECHO);
  362. tc.c_cc[VMIN] = 0;
  363. tc.c_cc[VTIME] = 0;
  364. tcsetattr(0, TCSANOW, &tc);
  365. poll(&stdin_poll, 1, -1);
  366. c = getc(stdin);
  367. tcsetattr(0, TCSAFLUSH, &save);
  368. if (!perf_top__key_mapped(top, c))
  369. return ret;
  370. }
  371. switch (c) {
  372. case 'd':
  373. prompt_integer(&top->delay_secs, "Enter display delay");
  374. if (top->delay_secs < 1)
  375. top->delay_secs = 1;
  376. break;
  377. case 'e':
  378. prompt_integer(&top->print_entries, "Enter display entries (lines)");
  379. if (top->print_entries == 0) {
  380. struct sigaction act = {
  381. .sa_sigaction = perf_top__sig_winch,
  382. .sa_flags = SA_SIGINFO,
  383. };
  384. perf_top__sig_winch(SIGWINCH, NULL, top);
  385. sigaction(SIGWINCH, &act, NULL);
  386. } else {
  387. signal(SIGWINCH, SIG_DFL);
  388. }
  389. break;
  390. case 'E':
  391. if (top->evlist->nr_entries > 1) {
  392. /* Select 0 as the default event: */
  393. int counter = 0;
  394. fprintf(stderr, "\nAvailable events:");
  395. evlist__for_each(top->evlist, top->sym_evsel)
  396. fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel));
  397. prompt_integer(&counter, "Enter details event counter");
  398. if (counter >= top->evlist->nr_entries) {
  399. top->sym_evsel = perf_evlist__first(top->evlist);
  400. fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel));
  401. sleep(1);
  402. break;
  403. }
  404. evlist__for_each(top->evlist, top->sym_evsel)
  405. if (top->sym_evsel->idx == counter)
  406. break;
  407. } else
  408. top->sym_evsel = perf_evlist__first(top->evlist);
  409. break;
  410. case 'f':
  411. prompt_integer(&top->count_filter, "Enter display event count filter");
  412. break;
  413. case 'F':
  414. prompt_percent(&top->sym_pcnt_filter,
  415. "Enter details display event filter (percent)");
  416. break;
  417. case 'K':
  418. top->hide_kernel_symbols = !top->hide_kernel_symbols;
  419. break;
  420. case 'q':
  421. case 'Q':
  422. printf("exiting.\n");
  423. if (top->dump_symtab)
  424. perf_session__fprintf_dsos(top->session, stderr);
  425. ret = false;
  426. break;
  427. case 's':
  428. perf_top__prompt_symbol(top, "Enter details symbol");
  429. break;
  430. case 'S':
  431. if (!top->sym_filter_entry)
  432. break;
  433. else {
  434. struct hist_entry *syme = top->sym_filter_entry;
  435. top->sym_filter_entry = NULL;
  436. __zero_source_counters(syme);
  437. }
  438. break;
  439. case 'U':
  440. top->hide_user_symbols = !top->hide_user_symbols;
  441. break;
  442. case 'z':
  443. top->zero = !top->zero;
  444. break;
  445. default:
  446. break;
  447. }
  448. return ret;
  449. }
  450. static void perf_top__sort_new_samples(void *arg)
  451. {
  452. struct perf_top *t = arg;
  453. perf_top__reset_sample_counters(t);
  454. if (t->evlist->selected != NULL)
  455. t->sym_evsel = t->evlist->selected;
  456. hists__collapse_resort(&t->sym_evsel->hists, NULL);
  457. hists__output_resort(&t->sym_evsel->hists);
  458. hists__decay_entries(&t->sym_evsel->hists,
  459. t->hide_user_symbols,
  460. t->hide_kernel_symbols);
  461. }
  462. static void *display_thread_tui(void *arg)
  463. {
  464. struct perf_evsel *pos;
  465. struct perf_top *top = arg;
  466. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  467. struct hist_browser_timer hbt = {
  468. .timer = perf_top__sort_new_samples,
  469. .arg = top,
  470. .refresh = top->delay_secs,
  471. };
  472. perf_top__sort_new_samples(top);
  473. /*
  474. * Initialize the uid_filter_str, in the future the TUI will allow
  475. * Zooming in/out UIDs. For now juse use whatever the user passed
  476. * via --uid.
  477. */
  478. evlist__for_each(top->evlist, pos)
  479. pos->hists.uid_filter_str = top->record_opts.target.uid_str;
  480. perf_evlist__tui_browse_hists(top->evlist, help, &hbt, top->min_percent,
  481. &top->session->header.env);
  482. done = 1;
  483. return NULL;
  484. }
  485. static void *display_thread(void *arg)
  486. {
  487. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  488. struct termios tc, save;
  489. struct perf_top *top = arg;
  490. int delay_msecs, c;
  491. tcgetattr(0, &save);
  492. tc = save;
  493. tc.c_lflag &= ~(ICANON | ECHO);
  494. tc.c_cc[VMIN] = 0;
  495. tc.c_cc[VTIME] = 0;
  496. pthread__unblock_sigwinch();
  497. repeat:
  498. delay_msecs = top->delay_secs * 1000;
  499. tcsetattr(0, TCSANOW, &tc);
  500. /* trash return*/
  501. getc(stdin);
  502. while (!done) {
  503. perf_top__print_sym_table(top);
  504. /*
  505. * Either timeout expired or we got an EINTR due to SIGWINCH,
  506. * refresh screen in both cases.
  507. */
  508. switch (poll(&stdin_poll, 1, delay_msecs)) {
  509. case 0:
  510. continue;
  511. case -1:
  512. if (errno == EINTR)
  513. continue;
  514. /* Fall trhu */
  515. default:
  516. c = getc(stdin);
  517. tcsetattr(0, TCSAFLUSH, &save);
  518. if (perf_top__handle_keypress(top, c))
  519. goto repeat;
  520. done = 1;
  521. }
  522. }
  523. return NULL;
  524. }
  525. static int symbol_filter(struct map *map __maybe_unused, struct symbol *sym)
  526. {
  527. const char *name = sym->name;
  528. /*
  529. * ppc64 uses function descriptors and appends a '.' to the
  530. * start of every instruction address. Remove it.
  531. */
  532. if (name[0] == '.')
  533. name++;
  534. if (!strcmp(name, "_text") ||
  535. !strcmp(name, "_etext") ||
  536. !strcmp(name, "_sinittext") ||
  537. !strncmp("init_module", name, 11) ||
  538. !strncmp("cleanup_module", name, 14) ||
  539. strstr(name, "_text_start") ||
  540. strstr(name, "_text_end"))
  541. return 1;
  542. if (symbol__is_idle(sym))
  543. sym->ignore = true;
  544. return 0;
  545. }
  546. static int hist_iter__top_callback(struct hist_entry_iter *iter,
  547. struct addr_location *al, bool single,
  548. void *arg)
  549. {
  550. struct perf_top *top = arg;
  551. struct hist_entry *he = iter->he;
  552. struct perf_evsel *evsel = iter->evsel;
  553. if (sort__has_sym && single) {
  554. u64 ip = al->addr;
  555. if (al->map)
  556. ip = al->map->unmap_ip(al->map, ip);
  557. perf_top__record_precise_ip(top, he, evsel->idx, ip);
  558. }
  559. return 0;
  560. }
  561. static void perf_event__process_sample(struct perf_tool *tool,
  562. const union perf_event *event,
  563. struct perf_evsel *evsel,
  564. struct perf_sample *sample,
  565. struct machine *machine)
  566. {
  567. struct perf_top *top = container_of(tool, struct perf_top, tool);
  568. struct addr_location al;
  569. int err;
  570. if (!machine && perf_guest) {
  571. static struct intlist *seen;
  572. if (!seen)
  573. seen = intlist__new(NULL);
  574. if (!intlist__has_entry(seen, sample->pid)) {
  575. pr_err("Can't find guest [%d]'s kernel information\n",
  576. sample->pid);
  577. intlist__add(seen, sample->pid);
  578. }
  579. return;
  580. }
  581. if (!machine) {
  582. pr_err("%u unprocessable samples recorded.\r",
  583. top->session->stats.nr_unprocessable_samples++);
  584. return;
  585. }
  586. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  587. top->exact_samples++;
  588. if (perf_event__preprocess_sample(event, machine, &al, sample) < 0)
  589. return;
  590. if (!top->kptr_restrict_warned &&
  591. symbol_conf.kptr_restrict &&
  592. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  593. ui__warning(
  594. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  595. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  596. "Kernel%s samples will not be resolved.\n",
  597. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  598. " modules" : "");
  599. if (use_browser <= 0)
  600. sleep(5);
  601. top->kptr_restrict_warned = true;
  602. }
  603. if (al.sym == NULL) {
  604. const char *msg = "Kernel samples will not be resolved.\n";
  605. /*
  606. * As we do lazy loading of symtabs we only will know if the
  607. * specified vmlinux file is invalid when we actually have a
  608. * hit in kernel space and then try to load it. So if we get
  609. * here and there are _no_ symbols in the DSO backing the
  610. * kernel map, bail out.
  611. *
  612. * We may never get here, for instance, if we use -K/
  613. * --hide-kernel-symbols, even if the user specifies an
  614. * invalid --vmlinux ;-)
  615. */
  616. if (!top->kptr_restrict_warned && !top->vmlinux_warned &&
  617. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  618. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  619. if (symbol_conf.vmlinux_name) {
  620. ui__warning("The %s file can't be used.\n%s",
  621. symbol_conf.vmlinux_name, msg);
  622. } else {
  623. ui__warning("A vmlinux file was not found.\n%s",
  624. msg);
  625. }
  626. if (use_browser <= 0)
  627. sleep(5);
  628. top->vmlinux_warned = true;
  629. }
  630. }
  631. if (al.sym == NULL || !al.sym->ignore) {
  632. struct hist_entry_iter iter = {
  633. .add_entry_cb = hist_iter__top_callback,
  634. };
  635. if (symbol_conf.cumulate_callchain)
  636. iter.ops = &hist_iter_cumulative;
  637. else
  638. iter.ops = &hist_iter_normal;
  639. pthread_mutex_lock(&evsel->hists.lock);
  640. err = hist_entry_iter__add(&iter, &al, evsel, sample,
  641. top->max_stack, top);
  642. if (err < 0)
  643. pr_err("Problem incrementing symbol period, skipping event\n");
  644. pthread_mutex_unlock(&evsel->hists.lock);
  645. }
  646. return;
  647. }
  648. static void perf_top__mmap_read_idx(struct perf_top *top, int idx)
  649. {
  650. struct perf_sample sample;
  651. struct perf_evsel *evsel;
  652. struct perf_session *session = top->session;
  653. union perf_event *event;
  654. struct machine *machine;
  655. u8 origin;
  656. int ret;
  657. while ((event = perf_evlist__mmap_read(top->evlist, idx)) != NULL) {
  658. ret = perf_evlist__parse_sample(top->evlist, event, &sample);
  659. if (ret) {
  660. pr_err("Can't parse sample, err = %d\n", ret);
  661. goto next_event;
  662. }
  663. evsel = perf_evlist__id2evsel(session->evlist, sample.id);
  664. assert(evsel != NULL);
  665. origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  666. if (event->header.type == PERF_RECORD_SAMPLE)
  667. ++top->samples;
  668. switch (origin) {
  669. case PERF_RECORD_MISC_USER:
  670. ++top->us_samples;
  671. if (top->hide_user_symbols)
  672. goto next_event;
  673. machine = &session->machines.host;
  674. break;
  675. case PERF_RECORD_MISC_KERNEL:
  676. ++top->kernel_samples;
  677. if (top->hide_kernel_symbols)
  678. goto next_event;
  679. machine = &session->machines.host;
  680. break;
  681. case PERF_RECORD_MISC_GUEST_KERNEL:
  682. ++top->guest_kernel_samples;
  683. machine = perf_session__find_machine(session,
  684. sample.pid);
  685. break;
  686. case PERF_RECORD_MISC_GUEST_USER:
  687. ++top->guest_us_samples;
  688. /*
  689. * TODO: we don't process guest user from host side
  690. * except simple counting.
  691. */
  692. /* Fall thru */
  693. default:
  694. goto next_event;
  695. }
  696. if (event->header.type == PERF_RECORD_SAMPLE) {
  697. perf_event__process_sample(&top->tool, event, evsel,
  698. &sample, machine);
  699. } else if (event->header.type < PERF_RECORD_MAX) {
  700. hists__inc_nr_events(&evsel->hists, event->header.type);
  701. machine__process_event(machine, event, &sample);
  702. } else
  703. ++session->stats.nr_unknown_events;
  704. next_event:
  705. perf_evlist__mmap_consume(top->evlist, idx);
  706. }
  707. }
  708. static void perf_top__mmap_read(struct perf_top *top)
  709. {
  710. int i;
  711. for (i = 0; i < top->evlist->nr_mmaps; i++)
  712. perf_top__mmap_read_idx(top, i);
  713. }
  714. static int perf_top__start_counters(struct perf_top *top)
  715. {
  716. char msg[512];
  717. struct perf_evsel *counter;
  718. struct perf_evlist *evlist = top->evlist;
  719. struct record_opts *opts = &top->record_opts;
  720. perf_evlist__config(evlist, opts);
  721. evlist__for_each(evlist, counter) {
  722. try_again:
  723. if (perf_evsel__open(counter, top->evlist->cpus,
  724. top->evlist->threads) < 0) {
  725. if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  726. if (verbose)
  727. ui__warning("%s\n", msg);
  728. goto try_again;
  729. }
  730. perf_evsel__open_strerror(counter, &opts->target,
  731. errno, msg, sizeof(msg));
  732. ui__error("%s\n", msg);
  733. goto out_err;
  734. }
  735. }
  736. if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
  737. ui__error("Failed to mmap with %d (%s)\n",
  738. errno, strerror(errno));
  739. goto out_err;
  740. }
  741. return 0;
  742. out_err:
  743. return -1;
  744. }
  745. static int perf_top__setup_sample_type(struct perf_top *top __maybe_unused)
  746. {
  747. if (!sort__has_sym) {
  748. if (symbol_conf.use_callchain) {
  749. ui__error("Selected -g but \"sym\" not present in --sort/-s.");
  750. return -EINVAL;
  751. }
  752. } else if (callchain_param.mode != CHAIN_NONE) {
  753. if (callchain_register_param(&callchain_param) < 0) {
  754. ui__error("Can't register callchain params.\n");
  755. return -EINVAL;
  756. }
  757. }
  758. return 0;
  759. }
  760. static int __cmd_top(struct perf_top *top)
  761. {
  762. struct record_opts *opts = &top->record_opts;
  763. pthread_t thread;
  764. int ret;
  765. top->session = perf_session__new(NULL, false, NULL);
  766. if (top->session == NULL)
  767. return -ENOMEM;
  768. machines__set_symbol_filter(&top->session->machines, symbol_filter);
  769. if (!objdump_path) {
  770. ret = perf_session_env__lookup_objdump(&top->session->header.env);
  771. if (ret)
  772. goto out_delete;
  773. }
  774. ret = perf_top__setup_sample_type(top);
  775. if (ret)
  776. goto out_delete;
  777. machine__synthesize_threads(&top->session->machines.host, &opts->target,
  778. top->evlist->threads, false);
  779. ret = perf_top__start_counters(top);
  780. if (ret)
  781. goto out_delete;
  782. top->session->evlist = top->evlist;
  783. perf_session__set_id_hdr_size(top->session);
  784. /*
  785. * When perf is starting the traced process, all the events (apart from
  786. * group members) have enable_on_exec=1 set, so don't spoil it by
  787. * prematurely enabling them.
  788. *
  789. * XXX 'top' still doesn't start workloads like record, trace, but should,
  790. * so leave the check here.
  791. */
  792. if (!target__none(&opts->target))
  793. perf_evlist__enable(top->evlist);
  794. /* Wait for a minimal set of events before starting the snapshot */
  795. poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  796. perf_top__mmap_read(top);
  797. ret = -1;
  798. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  799. display_thread), top)) {
  800. ui__error("Could not create display thread.\n");
  801. goto out_delete;
  802. }
  803. if (top->realtime_prio) {
  804. struct sched_param param;
  805. param.sched_priority = top->realtime_prio;
  806. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  807. ui__error("Could not set realtime priority.\n");
  808. goto out_delete;
  809. }
  810. }
  811. while (!done) {
  812. u64 hits = top->samples;
  813. perf_top__mmap_read(top);
  814. if (hits == top->samples)
  815. ret = poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  816. }
  817. ret = 0;
  818. out_delete:
  819. perf_session__delete(top->session);
  820. top->session = NULL;
  821. return ret;
  822. }
  823. static int
  824. callchain_opt(const struct option *opt, const char *arg, int unset)
  825. {
  826. symbol_conf.use_callchain = true;
  827. return record_callchain_opt(opt, arg, unset);
  828. }
  829. static int
  830. parse_callchain_opt(const struct option *opt, const char *arg, int unset)
  831. {
  832. symbol_conf.use_callchain = true;
  833. return record_parse_callchain_opt(opt, arg, unset);
  834. }
  835. static int perf_top_config(const char *var, const char *value, void *cb)
  836. {
  837. struct perf_top *top = cb;
  838. if (!strcmp(var, "top.call-graph"))
  839. return record_parse_callchain(value, &top->record_opts);
  840. if (!strcmp(var, "top.children")) {
  841. symbol_conf.cumulate_callchain = perf_config_bool(var, value);
  842. return 0;
  843. }
  844. return perf_default_config(var, value, cb);
  845. }
  846. static int
  847. parse_percent_limit(const struct option *opt, const char *arg,
  848. int unset __maybe_unused)
  849. {
  850. struct perf_top *top = opt->value;
  851. top->min_percent = strtof(arg, NULL);
  852. return 0;
  853. }
  854. int cmd_top(int argc, const char **argv, const char *prefix __maybe_unused)
  855. {
  856. int status = -1;
  857. char errbuf[BUFSIZ];
  858. struct perf_top top = {
  859. .count_filter = 5,
  860. .delay_secs = 2,
  861. .record_opts = {
  862. .mmap_pages = UINT_MAX,
  863. .user_freq = UINT_MAX,
  864. .user_interval = ULLONG_MAX,
  865. .freq = 4000, /* 4 KHz */
  866. .target = {
  867. .uses_mmap = true,
  868. },
  869. },
  870. .max_stack = PERF_MAX_STACK_DEPTH,
  871. .sym_pcnt_filter = 5,
  872. };
  873. struct record_opts *opts = &top.record_opts;
  874. struct target *target = &opts->target;
  875. const struct option options[] = {
  876. OPT_CALLBACK('e', "event", &top.evlist, "event",
  877. "event selector. use 'perf list' to list available events",
  878. parse_events_option),
  879. OPT_U64('c', "count", &opts->user_interval, "event period to sample"),
  880. OPT_STRING('p', "pid", &target->pid, "pid",
  881. "profile events on existing process id"),
  882. OPT_STRING('t', "tid", &target->tid, "tid",
  883. "profile events on existing thread id"),
  884. OPT_BOOLEAN('a', "all-cpus", &target->system_wide,
  885. "system-wide collection from all CPUs"),
  886. OPT_STRING('C', "cpu", &target->cpu_list, "cpu",
  887. "list of cpus to monitor"),
  888. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  889. "file", "vmlinux pathname"),
  890. OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
  891. "don't load vmlinux even if found"),
  892. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  893. "hide kernel symbols"),
  894. OPT_CALLBACK('m', "mmap-pages", &opts->mmap_pages, "pages",
  895. "number of mmap data pages",
  896. perf_evlist__parse_mmap_pages),
  897. OPT_INTEGER('r', "realtime", &top.realtime_prio,
  898. "collect data with this RT SCHED_FIFO priority"),
  899. OPT_INTEGER('d', "delay", &top.delay_secs,
  900. "number of seconds to delay between refreshes"),
  901. OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
  902. "dump the symbol table used for profiling"),
  903. OPT_INTEGER('f', "count-filter", &top.count_filter,
  904. "only display functions with more events than this"),
  905. OPT_BOOLEAN(0, "group", &opts->group,
  906. "put the counters into a counter group"),
  907. OPT_BOOLEAN('i', "no-inherit", &opts->no_inherit,
  908. "child tasks do not inherit counters"),
  909. OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
  910. "symbol to annotate"),
  911. OPT_BOOLEAN('z', "zero", &top.zero, "zero history across updates"),
  912. OPT_UINTEGER('F', "freq", &opts->user_freq, "profile at this frequency"),
  913. OPT_INTEGER('E', "entries", &top.print_entries,
  914. "display this many functions"),
  915. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  916. "hide user symbols"),
  917. OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
  918. OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
  919. OPT_INCR('v', "verbose", &verbose,
  920. "be more verbose (show counter open errors, etc)"),
  921. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  922. "sort by key(s): pid, comm, dso, symbol, parent, cpu, srcline, ..."
  923. " Please refer the man page for the complete list."),
  924. OPT_STRING(0, "fields", &field_order, "key[,keys...]",
  925. "output field(s): overhead, period, sample plus all of sort keys"),
  926. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  927. "Show a column with the number of samples"),
  928. OPT_CALLBACK_NOOPT('g', NULL, &top.record_opts,
  929. NULL, "enables call-graph recording",
  930. &callchain_opt),
  931. OPT_CALLBACK(0, "call-graph", &top.record_opts,
  932. "mode[,dump_size]", record_callchain_help,
  933. &parse_callchain_opt),
  934. OPT_BOOLEAN(0, "children", &symbol_conf.cumulate_callchain,
  935. "Accumulate callchains of children and show total overhead as well"),
  936. OPT_INTEGER(0, "max-stack", &top.max_stack,
  937. "Set the maximum stack depth when parsing the callchain. "
  938. "Default: " __stringify(PERF_MAX_STACK_DEPTH)),
  939. OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
  940. "ignore callees of these functions in call graphs",
  941. report_parse_ignore_callees_opt),
  942. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  943. "Show a column with the sum of periods"),
  944. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  945. "only consider symbols in these dsos"),
  946. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  947. "only consider symbols in these comms"),
  948. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  949. "only consider these symbols"),
  950. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  951. "Interleave source code with assembly code (default)"),
  952. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  953. "Display raw encoding of assembly instructions (default)"),
  954. OPT_STRING(0, "objdump", &objdump_path, "path",
  955. "objdump binary to use for disassembly and annotations"),
  956. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  957. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  958. OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
  959. OPT_CALLBACK(0, "percent-limit", &top, "percent",
  960. "Don't show entries under that percent", parse_percent_limit),
  961. OPT_CALLBACK(0, "percentage", NULL, "relative|absolute",
  962. "How to display percentage of filtered entries", parse_filter_percentage),
  963. OPT_END()
  964. };
  965. const char * const top_usage[] = {
  966. "perf top [<options>]",
  967. NULL
  968. };
  969. top.evlist = perf_evlist__new();
  970. if (top.evlist == NULL)
  971. return -ENOMEM;
  972. perf_config(perf_top_config, &top);
  973. argc = parse_options(argc, argv, options, top_usage, 0);
  974. if (argc)
  975. usage_with_options(top_usage, options);
  976. sort__mode = SORT_MODE__TOP;
  977. /* display thread wants entries to be collapsed in a different tree */
  978. sort__need_collapse = 1;
  979. if (setup_sorting() < 0) {
  980. if (sort_order)
  981. parse_options_usage(top_usage, options, "s", 1);
  982. if (field_order)
  983. parse_options_usage(sort_order ? NULL : top_usage,
  984. options, "fields", 0);
  985. goto out_delete_evlist;
  986. }
  987. if (top.use_stdio)
  988. use_browser = 0;
  989. else if (top.use_tui)
  990. use_browser = 1;
  991. setup_browser(false);
  992. status = target__validate(target);
  993. if (status) {
  994. target__strerror(target, status, errbuf, BUFSIZ);
  995. ui__warning("%s\n", errbuf);
  996. }
  997. status = target__parse_uid(target);
  998. if (status) {
  999. int saved_errno = errno;
  1000. target__strerror(target, status, errbuf, BUFSIZ);
  1001. ui__error("%s\n", errbuf);
  1002. status = -saved_errno;
  1003. goto out_delete_evlist;
  1004. }
  1005. if (target__none(target))
  1006. target->system_wide = true;
  1007. if (perf_evlist__create_maps(top.evlist, target) < 0)
  1008. usage_with_options(top_usage, options);
  1009. if (!top.evlist->nr_entries &&
  1010. perf_evlist__add_default(top.evlist) < 0) {
  1011. ui__error("Not enough memory for event selector list\n");
  1012. goto out_delete_evlist;
  1013. }
  1014. symbol_conf.nr_events = top.evlist->nr_entries;
  1015. if (top.delay_secs < 1)
  1016. top.delay_secs = 1;
  1017. if (record_opts__config(opts)) {
  1018. status = -EINVAL;
  1019. goto out_delete_evlist;
  1020. }
  1021. top.sym_evsel = perf_evlist__first(top.evlist);
  1022. if (!symbol_conf.use_callchain) {
  1023. symbol_conf.cumulate_callchain = false;
  1024. perf_hpp__cancel_cumulate();
  1025. }
  1026. symbol_conf.priv_size = sizeof(struct annotation);
  1027. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1028. if (symbol__init() < 0)
  1029. return -1;
  1030. sort__setup_elide(stdout);
  1031. get_term_dimensions(&top.winsize);
  1032. if (top.print_entries == 0) {
  1033. struct sigaction act = {
  1034. .sa_sigaction = perf_top__sig_winch,
  1035. .sa_flags = SA_SIGINFO,
  1036. };
  1037. perf_top__update_print_entries(&top);
  1038. sigaction(SIGWINCH, &act, NULL);
  1039. }
  1040. status = __cmd_top(&top);
  1041. out_delete_evlist:
  1042. perf_evlist__delete(top.evlist);
  1043. return status;
  1044. }