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