builtin-top.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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. 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;
  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. if (notes->src == NULL && symbol__alloc_hist(sym) < 0) {
  161. pthread_mutex_unlock(&notes->lock);
  162. pr_err("Not enough memory for annotating '%s' symbol!\n",
  163. sym->name);
  164. sleep(1);
  165. return;
  166. }
  167. ip = he->ms.map->map_ip(he->ms.map, ip);
  168. err = symbol__inc_addr_samples(sym, he->ms.map, counter, ip);
  169. pthread_mutex_unlock(&notes->lock);
  170. if (err == -ERANGE && !he->ms.map->erange_warned)
  171. ui__warn_map_erange(he->ms.map, sym, ip);
  172. }
  173. static void perf_top__show_details(struct perf_top *top)
  174. {
  175. struct hist_entry *he = top->sym_filter_entry;
  176. struct annotation *notes;
  177. struct symbol *symbol;
  178. int more;
  179. if (!he)
  180. return;
  181. symbol = he->ms.sym;
  182. notes = symbol__annotation(symbol);
  183. pthread_mutex_lock(&notes->lock);
  184. if (notes->src == NULL)
  185. goto out_unlock;
  186. printf("Showing %s for %s\n", perf_evsel__name(top->sym_evsel), symbol->name);
  187. printf(" Events Pcnt (>=%d%%)\n", top->sym_pcnt_filter);
  188. more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel,
  189. 0, top->sym_pcnt_filter, top->print_entries, 4);
  190. if (top->zero)
  191. symbol__annotate_zero_histogram(symbol, top->sym_evsel->idx);
  192. else
  193. symbol__annotate_decay_histogram(symbol, top->sym_evsel->idx);
  194. if (more != 0)
  195. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  196. out_unlock:
  197. pthread_mutex_unlock(&notes->lock);
  198. }
  199. static const char CONSOLE_CLEAR[] = "";
  200. static struct hist_entry *perf_evsel__add_hist_entry(struct perf_evsel *evsel,
  201. struct addr_location *al,
  202. struct perf_sample *sample)
  203. {
  204. struct hist_entry *he;
  205. pthread_mutex_lock(&evsel->hists.lock);
  206. he = __hists__add_entry(&evsel->hists, al, NULL, sample->period,
  207. sample->weight);
  208. pthread_mutex_unlock(&evsel->hists.lock);
  209. if (he == NULL)
  210. return NULL;
  211. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  212. return he;
  213. }
  214. static void perf_top__print_sym_table(struct perf_top *top)
  215. {
  216. char bf[160];
  217. int printed = 0;
  218. const int win_width = top->winsize.ws_col - 1;
  219. puts(CONSOLE_CLEAR);
  220. perf_top__header_snprintf(top, bf, sizeof(bf));
  221. printf("%s\n", bf);
  222. perf_top__reset_sample_counters(top);
  223. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  224. if (top->sym_evsel->hists.stats.nr_lost_warned !=
  225. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  226. top->sym_evsel->hists.stats.nr_lost_warned =
  227. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  228. color_fprintf(stdout, PERF_COLOR_RED,
  229. "WARNING: LOST %d chunks, Check IO/CPU overload",
  230. top->sym_evsel->hists.stats.nr_lost_warned);
  231. ++printed;
  232. }
  233. if (top->sym_filter_entry) {
  234. perf_top__show_details(top);
  235. return;
  236. }
  237. hists__collapse_resort(&top->sym_evsel->hists);
  238. hists__output_resort(&top->sym_evsel->hists);
  239. hists__decay_entries(&top->sym_evsel->hists,
  240. top->hide_user_symbols,
  241. top->hide_kernel_symbols);
  242. hists__output_recalc_col_len(&top->sym_evsel->hists,
  243. top->print_entries - printed);
  244. putchar('\n');
  245. hists__fprintf(&top->sym_evsel->hists, false,
  246. top->print_entries - printed, win_width,
  247. top->min_percent, stdout);
  248. }
  249. static void prompt_integer(int *target, const char *msg)
  250. {
  251. char *buf = malloc(0), *p;
  252. size_t dummy = 0;
  253. int tmp;
  254. fprintf(stdout, "\n%s: ", msg);
  255. if (getline(&buf, &dummy, stdin) < 0)
  256. return;
  257. p = strchr(buf, '\n');
  258. if (p)
  259. *p = 0;
  260. p = buf;
  261. while(*p) {
  262. if (!isdigit(*p))
  263. goto out_free;
  264. p++;
  265. }
  266. tmp = strtoul(buf, NULL, 10);
  267. *target = tmp;
  268. out_free:
  269. free(buf);
  270. }
  271. static void prompt_percent(int *target, const char *msg)
  272. {
  273. int tmp = 0;
  274. prompt_integer(&tmp, msg);
  275. if (tmp >= 0 && tmp <= 100)
  276. *target = tmp;
  277. }
  278. static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
  279. {
  280. char *buf = malloc(0), *p;
  281. struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
  282. struct rb_node *next;
  283. size_t dummy = 0;
  284. /* zero counters of active symbol */
  285. if (syme) {
  286. __zero_source_counters(syme);
  287. top->sym_filter_entry = NULL;
  288. }
  289. fprintf(stdout, "\n%s: ", msg);
  290. if (getline(&buf, &dummy, stdin) < 0)
  291. goto out_free;
  292. p = strchr(buf, '\n');
  293. if (p)
  294. *p = 0;
  295. next = rb_first(&top->sym_evsel->hists.entries);
  296. while (next) {
  297. n = rb_entry(next, struct hist_entry, rb_node);
  298. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  299. found = n;
  300. break;
  301. }
  302. next = rb_next(&n->rb_node);
  303. }
  304. if (!found) {
  305. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  306. sleep(1);
  307. } else
  308. perf_top__parse_source(top, found);
  309. out_free:
  310. free(buf);
  311. }
  312. static void perf_top__print_mapped_keys(struct perf_top *top)
  313. {
  314. char *name = NULL;
  315. if (top->sym_filter_entry) {
  316. struct symbol *sym = top->sym_filter_entry->ms.sym;
  317. name = sym->name;
  318. }
  319. fprintf(stdout, "\nMapped keys:\n");
  320. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
  321. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
  322. if (top->evlist->nr_entries > 1)
  323. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel));
  324. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
  325. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->sym_pcnt_filter);
  326. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  327. fprintf(stdout, "\t[S] stop annotation.\n");
  328. fprintf(stdout,
  329. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  330. top->hide_kernel_symbols ? "yes" : "no");
  331. fprintf(stdout,
  332. "\t[U] hide user symbols. \t(%s)\n",
  333. top->hide_user_symbols ? "yes" : "no");
  334. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
  335. fprintf(stdout, "\t[qQ] quit.\n");
  336. }
  337. static int perf_top__key_mapped(struct perf_top *top, int c)
  338. {
  339. switch (c) {
  340. case 'd':
  341. case 'e':
  342. case 'f':
  343. case 'z':
  344. case 'q':
  345. case 'Q':
  346. case 'K':
  347. case 'U':
  348. case 'F':
  349. case 's':
  350. case 'S':
  351. return 1;
  352. case 'E':
  353. return top->evlist->nr_entries > 1 ? 1 : 0;
  354. default:
  355. break;
  356. }
  357. return 0;
  358. }
  359. static bool perf_top__handle_keypress(struct perf_top *top, int c)
  360. {
  361. bool ret = true;
  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 ret;
  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. signal(SIGWINCH, SIG_DFL);
  397. }
  398. break;
  399. case 'E':
  400. if (top->evlist->nr_entries > 1) {
  401. /* Select 0 as the default event: */
  402. int counter = 0;
  403. fprintf(stderr, "\nAvailable events:");
  404. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  405. fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel));
  406. prompt_integer(&counter, "Enter details event counter");
  407. if (counter >= top->evlist->nr_entries) {
  408. top->sym_evsel = perf_evlist__first(top->evlist);
  409. fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel));
  410. sleep(1);
  411. break;
  412. }
  413. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  414. if (top->sym_evsel->idx == counter)
  415. break;
  416. } else
  417. top->sym_evsel = perf_evlist__first(top->evlist);
  418. break;
  419. case 'f':
  420. prompt_integer(&top->count_filter, "Enter display event count filter");
  421. break;
  422. case 'F':
  423. prompt_percent(&top->sym_pcnt_filter,
  424. "Enter details display event filter (percent)");
  425. break;
  426. case 'K':
  427. top->hide_kernel_symbols = !top->hide_kernel_symbols;
  428. break;
  429. case 'q':
  430. case 'Q':
  431. printf("exiting.\n");
  432. if (top->dump_symtab)
  433. perf_session__fprintf_dsos(top->session, stderr);
  434. ret = false;
  435. break;
  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. return ret;
  458. }
  459. static void perf_top__sort_new_samples(void *arg)
  460. {
  461. struct perf_top *t = arg;
  462. perf_top__reset_sample_counters(t);
  463. if (t->evlist->selected != NULL)
  464. t->sym_evsel = t->evlist->selected;
  465. hists__collapse_resort(&t->sym_evsel->hists);
  466. hists__output_resort(&t->sym_evsel->hists);
  467. hists__decay_entries(&t->sym_evsel->hists,
  468. t->hide_user_symbols,
  469. t->hide_kernel_symbols);
  470. }
  471. static void *display_thread_tui(void *arg)
  472. {
  473. struct perf_evsel *pos;
  474. struct perf_top *top = arg;
  475. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  476. struct hist_browser_timer hbt = {
  477. .timer = perf_top__sort_new_samples,
  478. .arg = top,
  479. .refresh = top->delay_secs,
  480. };
  481. perf_top__sort_new_samples(top);
  482. /*
  483. * Initialize the uid_filter_str, in the future the TUI will allow
  484. * Zooming in/out UIDs. For now juse use whatever the user passed
  485. * via --uid.
  486. */
  487. list_for_each_entry(pos, &top->evlist->entries, node)
  488. pos->hists.uid_filter_str = top->record_opts.target.uid_str;
  489. perf_evlist__tui_browse_hists(top->evlist, help, &hbt, top->min_percent,
  490. &top->session->header.env);
  491. done = 1;
  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 (!done) {
  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. c = getc(stdin);
  526. tcsetattr(0, TCSAFLUSH, &save);
  527. if (perf_top__handle_keypress(top, c))
  528. goto repeat;
  529. done = 1;
  530. }
  531. }
  532. return NULL;
  533. }
  534. /* Tag samples to be skipped. */
  535. static const char *skip_symbols[] = {
  536. "intel_idle",
  537. "default_idle",
  538. "native_safe_halt",
  539. "cpu_idle",
  540. "enter_idle",
  541. "exit_idle",
  542. "mwait_idle",
  543. "mwait_idle_with_hints",
  544. "poll_idle",
  545. "ppc64_runlatch_off",
  546. "pseries_dedicated_idle_sleep",
  547. NULL
  548. };
  549. static int symbol_filter(struct map *map __maybe_unused, struct symbol *sym)
  550. {
  551. const char *name = sym->name;
  552. int i;
  553. /*
  554. * ppc64 uses function descriptors and appends a '.' to the
  555. * start of every instruction address. Remove it.
  556. */
  557. if (name[0] == '.')
  558. name++;
  559. if (!strcmp(name, "_text") ||
  560. !strcmp(name, "_etext") ||
  561. !strcmp(name, "_sinittext") ||
  562. !strncmp("init_module", name, 11) ||
  563. !strncmp("cleanup_module", name, 14) ||
  564. strstr(name, "_text_start") ||
  565. strstr(name, "_text_end"))
  566. return 1;
  567. for (i = 0; skip_symbols[i]; i++) {
  568. if (!strcmp(skip_symbols[i], name)) {
  569. sym->ignore = true;
  570. break;
  571. }
  572. }
  573. return 0;
  574. }
  575. static void perf_event__process_sample(struct perf_tool *tool,
  576. const union perf_event *event,
  577. struct perf_evsel *evsel,
  578. struct perf_sample *sample,
  579. struct machine *machine)
  580. {
  581. struct perf_top *top = container_of(tool, struct perf_top, tool);
  582. struct symbol *parent = NULL;
  583. u64 ip = event->ip.ip;
  584. struct addr_location al;
  585. int err;
  586. if (!machine && perf_guest) {
  587. static struct intlist *seen;
  588. if (!seen)
  589. seen = intlist__new(NULL);
  590. if (!intlist__has_entry(seen, event->ip.pid)) {
  591. pr_err("Can't find guest [%d]'s kernel information\n",
  592. event->ip.pid);
  593. intlist__add(seen, event->ip.pid);
  594. }
  595. return;
  596. }
  597. if (!machine) {
  598. pr_err("%u unprocessable samples recorded.\r",
  599. top->session->stats.nr_unprocessable_samples++);
  600. return;
  601. }
  602. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  603. top->exact_samples++;
  604. if (perf_event__preprocess_sample(event, machine, &al, sample,
  605. symbol_filter) < 0 ||
  606. al.filtered)
  607. return;
  608. if (!top->kptr_restrict_warned &&
  609. symbol_conf.kptr_restrict &&
  610. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  611. ui__warning(
  612. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  613. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  614. "Kernel%s samples will not be resolved.\n",
  615. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  616. " modules" : "");
  617. if (use_browser <= 0)
  618. sleep(5);
  619. top->kptr_restrict_warned = true;
  620. }
  621. if (al.sym == NULL) {
  622. const char *msg = "Kernel samples will not be resolved.\n";
  623. /*
  624. * As we do lazy loading of symtabs we only will know if the
  625. * specified vmlinux file is invalid when we actually have a
  626. * hit in kernel space and then try to load it. So if we get
  627. * here and there are _no_ symbols in the DSO backing the
  628. * kernel map, bail out.
  629. *
  630. * We may never get here, for instance, if we use -K/
  631. * --hide-kernel-symbols, even if the user specifies an
  632. * invalid --vmlinux ;-)
  633. */
  634. if (!top->kptr_restrict_warned && !top->vmlinux_warned &&
  635. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  636. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  637. if (symbol_conf.vmlinux_name) {
  638. ui__warning("The %s file can't be used.\n%s",
  639. symbol_conf.vmlinux_name, msg);
  640. } else {
  641. ui__warning("A vmlinux file was not found.\n%s",
  642. msg);
  643. }
  644. if (use_browser <= 0)
  645. sleep(5);
  646. top->vmlinux_warned = true;
  647. }
  648. }
  649. if (al.sym == NULL || !al.sym->ignore) {
  650. struct hist_entry *he;
  651. if ((sort__has_parent || symbol_conf.use_callchain) &&
  652. sample->callchain) {
  653. err = machine__resolve_callchain(machine, evsel,
  654. al.thread, sample,
  655. &parent, &al);
  656. if (err)
  657. return;
  658. }
  659. he = perf_evsel__add_hist_entry(evsel, &al, sample);
  660. if (he == NULL) {
  661. pr_err("Problem incrementing symbol period, skipping event\n");
  662. return;
  663. }
  664. if (symbol_conf.use_callchain) {
  665. err = callchain_append(he->callchain, &callchain_cursor,
  666. sample->period);
  667. if (err)
  668. return;
  669. }
  670. if (sort__has_sym)
  671. perf_top__record_precise_ip(top, he, evsel->idx, ip);
  672. }
  673. return;
  674. }
  675. static void perf_top__mmap_read_idx(struct perf_top *top, int idx)
  676. {
  677. struct perf_sample sample;
  678. struct perf_evsel *evsel;
  679. struct perf_session *session = top->session;
  680. union perf_event *event;
  681. struct machine *machine;
  682. u8 origin;
  683. int ret;
  684. while ((event = perf_evlist__mmap_read(top->evlist, idx)) != NULL) {
  685. ret = perf_evlist__parse_sample(top->evlist, event, &sample);
  686. if (ret) {
  687. pr_err("Can't parse sample, err = %d\n", ret);
  688. continue;
  689. }
  690. evsel = perf_evlist__id2evsel(session->evlist, sample.id);
  691. assert(evsel != NULL);
  692. origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  693. if (event->header.type == PERF_RECORD_SAMPLE)
  694. ++top->samples;
  695. switch (origin) {
  696. case PERF_RECORD_MISC_USER:
  697. ++top->us_samples;
  698. if (top->hide_user_symbols)
  699. continue;
  700. machine = &session->machines.host;
  701. break;
  702. case PERF_RECORD_MISC_KERNEL:
  703. ++top->kernel_samples;
  704. if (top->hide_kernel_symbols)
  705. continue;
  706. machine = &session->machines.host;
  707. break;
  708. case PERF_RECORD_MISC_GUEST_KERNEL:
  709. ++top->guest_kernel_samples;
  710. machine = perf_session__find_machine(session, event->ip.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. continue;
  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, event->header.type);
  727. machine__process_event(machine, event);
  728. } else
  729. ++session->stats.nr_unknown_events;
  730. }
  731. }
  732. static void perf_top__mmap_read(struct perf_top *top)
  733. {
  734. int i;
  735. for (i = 0; i < top->evlist->nr_mmaps; i++)
  736. perf_top__mmap_read_idx(top, i);
  737. }
  738. static int perf_top__start_counters(struct perf_top *top)
  739. {
  740. char msg[512];
  741. struct perf_evsel *counter;
  742. struct perf_evlist *evlist = top->evlist;
  743. struct perf_record_opts *opts = &top->record_opts;
  744. perf_evlist__config(evlist, opts);
  745. list_for_each_entry(counter, &evlist->entries, node) {
  746. try_again:
  747. if (perf_evsel__open(counter, top->evlist->cpus,
  748. top->evlist->threads) < 0) {
  749. if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  750. if (verbose)
  751. ui__warning("%s\n", msg);
  752. goto try_again;
  753. }
  754. perf_evsel__open_strerror(counter, &opts->target,
  755. errno, msg, sizeof(msg));
  756. ui__error("%s\n", msg);
  757. goto out_err;
  758. }
  759. }
  760. if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
  761. ui__error("Failed to mmap with %d (%s)\n",
  762. errno, strerror(errno));
  763. goto out_err;
  764. }
  765. return 0;
  766. out_err:
  767. return -1;
  768. }
  769. static int perf_top__setup_sample_type(struct perf_top *top __maybe_unused)
  770. {
  771. if (!sort__has_sym) {
  772. if (symbol_conf.use_callchain) {
  773. ui__error("Selected -g but \"sym\" not present in --sort/-s.");
  774. return -EINVAL;
  775. }
  776. } else if (callchain_param.mode != CHAIN_NONE) {
  777. if (callchain_register_param(&callchain_param) < 0) {
  778. ui__error("Can't register callchain params.\n");
  779. return -EINVAL;
  780. }
  781. }
  782. return 0;
  783. }
  784. static int __cmd_top(struct perf_top *top)
  785. {
  786. struct perf_record_opts *opts = &top->record_opts;
  787. pthread_t thread;
  788. int ret;
  789. /*
  790. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  791. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  792. */
  793. top->session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  794. if (top->session == NULL)
  795. return -ENOMEM;
  796. if (!objdump_path) {
  797. ret = perf_session_env__lookup_objdump(&top->session->header.env);
  798. if (ret)
  799. goto out_delete;
  800. }
  801. ret = perf_top__setup_sample_type(top);
  802. if (ret)
  803. goto out_delete;
  804. if (perf_target__has_task(&opts->target))
  805. perf_event__synthesize_thread_map(&top->tool, top->evlist->threads,
  806. perf_event__process,
  807. &top->session->machines.host);
  808. else
  809. perf_event__synthesize_threads(&top->tool, perf_event__process,
  810. &top->session->machines.host);
  811. ret = perf_top__start_counters(top);
  812. if (ret)
  813. goto out_delete;
  814. top->session->evlist = top->evlist;
  815. perf_session__set_id_hdr_size(top->session);
  816. /*
  817. * When perf is starting the traced process, all the events (apart from
  818. * group members) have enable_on_exec=1 set, so don't spoil it by
  819. * prematurely enabling them.
  820. *
  821. * XXX 'top' still doesn't start workloads like record, trace, but should,
  822. * so leave the check here.
  823. */
  824. if (!perf_target__none(&opts->target))
  825. perf_evlist__enable(top->evlist);
  826. /* Wait for a minimal set of events before starting the snapshot */
  827. poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  828. perf_top__mmap_read(top);
  829. ret = -1;
  830. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  831. display_thread), top)) {
  832. ui__error("Could not create display thread.\n");
  833. goto out_delete;
  834. }
  835. if (top->realtime_prio) {
  836. struct sched_param param;
  837. param.sched_priority = top->realtime_prio;
  838. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  839. ui__error("Could not set realtime priority.\n");
  840. goto out_delete;
  841. }
  842. }
  843. while (!done) {
  844. u64 hits = top->samples;
  845. perf_top__mmap_read(top);
  846. if (hits == top->samples)
  847. ret = poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  848. }
  849. ret = 0;
  850. out_delete:
  851. perf_session__delete(top->session);
  852. top->session = NULL;
  853. return ret;
  854. }
  855. static int
  856. parse_callchain_opt(const struct option *opt, const char *arg, int unset)
  857. {
  858. /*
  859. * --no-call-graph
  860. */
  861. if (unset)
  862. return 0;
  863. symbol_conf.use_callchain = true;
  864. return record_parse_callchain_opt(opt, arg, unset);
  865. }
  866. static int
  867. parse_percent_limit(const struct option *opt, const char *arg,
  868. int unset __maybe_unused)
  869. {
  870. struct perf_top *top = opt->value;
  871. top->min_percent = strtof(arg, NULL);
  872. return 0;
  873. }
  874. int cmd_top(int argc, const char **argv, const char *prefix __maybe_unused)
  875. {
  876. int status;
  877. char errbuf[BUFSIZ];
  878. struct perf_top top = {
  879. .count_filter = 5,
  880. .delay_secs = 2,
  881. .record_opts = {
  882. .mmap_pages = UINT_MAX,
  883. .user_freq = UINT_MAX,
  884. .user_interval = ULLONG_MAX,
  885. .freq = 4000, /* 4 KHz */
  886. .target = {
  887. .uses_mmap = true,
  888. },
  889. },
  890. .sym_pcnt_filter = 5,
  891. };
  892. struct perf_record_opts *opts = &top.record_opts;
  893. struct perf_target *target = &opts->target;
  894. const struct option options[] = {
  895. OPT_CALLBACK('e', "event", &top.evlist, "event",
  896. "event selector. use 'perf list' to list available events",
  897. parse_events_option),
  898. OPT_U64('c', "count", &opts->user_interval, "event period to sample"),
  899. OPT_STRING('p', "pid", &target->pid, "pid",
  900. "profile events on existing process id"),
  901. OPT_STRING('t', "tid", &target->tid, "tid",
  902. "profile events on existing thread id"),
  903. OPT_BOOLEAN('a', "all-cpus", &target->system_wide,
  904. "system-wide collection from all CPUs"),
  905. OPT_STRING('C', "cpu", &target->cpu_list, "cpu",
  906. "list of cpus to monitor"),
  907. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  908. "file", "vmlinux pathname"),
  909. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  910. "hide kernel symbols"),
  911. OPT_UINTEGER('m', "mmap-pages", &opts->mmap_pages,
  912. "number of mmap data pages"),
  913. OPT_INTEGER('r', "realtime", &top.realtime_prio,
  914. "collect data with this RT SCHED_FIFO priority"),
  915. OPT_INTEGER('d', "delay", &top.delay_secs,
  916. "number of seconds to delay between refreshes"),
  917. OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
  918. "dump the symbol table used for profiling"),
  919. OPT_INTEGER('f', "count-filter", &top.count_filter,
  920. "only display functions with more events than this"),
  921. OPT_BOOLEAN('g', "group", &opts->group,
  922. "put the counters into a counter group"),
  923. OPT_BOOLEAN('i', "no-inherit", &opts->no_inherit,
  924. "child tasks do not inherit counters"),
  925. OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
  926. "symbol to annotate"),
  927. OPT_BOOLEAN('z', "zero", &top.zero, "zero history across updates"),
  928. OPT_UINTEGER('F', "freq", &opts->user_freq, "profile at this frequency"),
  929. OPT_INTEGER('E', "entries", &top.print_entries,
  930. "display this many functions"),
  931. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  932. "hide user symbols"),
  933. OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
  934. OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
  935. OPT_INCR('v', "verbose", &verbose,
  936. "be more verbose (show counter open errors, etc)"),
  937. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  938. "sort by key(s): pid, comm, dso, symbol, parent, weight, local_weight"),
  939. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  940. "Show a column with the number of samples"),
  941. OPT_CALLBACK_DEFAULT('G', "call-graph", &top.record_opts,
  942. "mode[,dump_size]", record_callchain_help,
  943. &parse_callchain_opt, "fp"),
  944. OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
  945. "ignore callees of these functions in call graphs",
  946. report_parse_ignore_callees_opt),
  947. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  948. "Show a column with the sum of periods"),
  949. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  950. "only consider symbols in these dsos"),
  951. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  952. "only consider symbols in these comms"),
  953. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  954. "only consider these symbols"),
  955. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  956. "Interleave source code with assembly code (default)"),
  957. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  958. "Display raw encoding of assembly instructions (default)"),
  959. OPT_STRING(0, "objdump", &objdump_path, "path",
  960. "objdump binary to use for disassembly and annotations"),
  961. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  962. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  963. OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
  964. OPT_CALLBACK(0, "percent-limit", &top, "percent",
  965. "Don't show entries under that percent", parse_percent_limit),
  966. OPT_END()
  967. };
  968. const char * const top_usage[] = {
  969. "perf top [<options>]",
  970. NULL
  971. };
  972. top.evlist = perf_evlist__new();
  973. if (top.evlist == NULL)
  974. return -ENOMEM;
  975. argc = parse_options(argc, argv, options, top_usage, 0);
  976. if (argc)
  977. usage_with_options(top_usage, options);
  978. if (sort_order == default_sort_order)
  979. sort_order = "dso,symbol";
  980. if (setup_sorting() < 0)
  981. usage_with_options(top_usage, options);
  982. /* display thread wants entries to be collapsed in a different tree */
  983. sort__need_collapse = 1;
  984. if (top.use_stdio)
  985. use_browser = 0;
  986. else if (top.use_tui)
  987. use_browser = 1;
  988. setup_browser(false);
  989. status = perf_target__validate(target);
  990. if (status) {
  991. perf_target__strerror(target, status, errbuf, BUFSIZ);
  992. ui__warning("%s", errbuf);
  993. }
  994. status = perf_target__parse_uid(target);
  995. if (status) {
  996. int saved_errno = errno;
  997. perf_target__strerror(target, status, errbuf, BUFSIZ);
  998. ui__error("%s", errbuf);
  999. status = -saved_errno;
  1000. goto out_delete_evlist;
  1001. }
  1002. if (perf_target__none(target))
  1003. target->system_wide = true;
  1004. if (perf_evlist__create_maps(top.evlist, target) < 0)
  1005. usage_with_options(top_usage, options);
  1006. if (!top.evlist->nr_entries &&
  1007. perf_evlist__add_default(top.evlist) < 0) {
  1008. ui__error("Not enough memory for event selector list\n");
  1009. goto out_delete_maps;
  1010. }
  1011. symbol_conf.nr_events = top.evlist->nr_entries;
  1012. if (top.delay_secs < 1)
  1013. top.delay_secs = 1;
  1014. if (opts->user_interval != ULLONG_MAX)
  1015. opts->default_interval = opts->user_interval;
  1016. if (opts->user_freq != UINT_MAX)
  1017. opts->freq = opts->user_freq;
  1018. /*
  1019. * User specified count overrides default frequency.
  1020. */
  1021. if (opts->default_interval)
  1022. opts->freq = 0;
  1023. else if (opts->freq) {
  1024. opts->default_interval = opts->freq;
  1025. } else {
  1026. ui__error("frequency and count are zero, aborting\n");
  1027. status = -EINVAL;
  1028. goto out_delete_maps;
  1029. }
  1030. top.sym_evsel = perf_evlist__first(top.evlist);
  1031. symbol_conf.priv_size = sizeof(struct annotation);
  1032. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1033. if (symbol__init() < 0)
  1034. return -1;
  1035. sort__setup_elide(stdout);
  1036. get_term_dimensions(&top.winsize);
  1037. if (top.print_entries == 0) {
  1038. struct sigaction act = {
  1039. .sa_sigaction = perf_top__sig_winch,
  1040. .sa_flags = SA_SIGINFO,
  1041. };
  1042. perf_top__update_print_entries(&top);
  1043. sigaction(SIGWINCH, &act, NULL);
  1044. }
  1045. status = __cmd_top(&top);
  1046. out_delete_maps:
  1047. perf_evlist__delete_maps(top.evlist);
  1048. out_delete_evlist:
  1049. perf_evlist__delete(top.evlist);
  1050. return status;
  1051. }