builtin-top.c 31 KB

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