builtin-top.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. /*
  2. * builtin-top.c
  3. *
  4. * Builtin top command: Display a continuously updated profile of
  5. * any workload, CPU or specific PID.
  6. *
  7. * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
  8. * 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
  9. *
  10. * Improvements and fixes by:
  11. *
  12. * Arjan van de Ven <arjan@linux.intel.com>
  13. * Yanmin Zhang <yanmin.zhang@intel.com>
  14. * Wu Fengguang <fengguang.wu@intel.com>
  15. * Mike Galbraith <efault@gmx.de>
  16. * Paul Mackerras <paulus@samba.org>
  17. *
  18. * Released under the GPL v2. (and only v2, not any later version)
  19. */
  20. #include "builtin.h"
  21. #include "perf.h"
  22. #include "util/annotate.h"
  23. #include "util/cache.h"
  24. #include "util/color.h"
  25. #include "util/evlist.h"
  26. #include "util/evsel.h"
  27. #include "util/machine.h"
  28. #include "util/session.h"
  29. #include "util/symbol.h"
  30. #include "util/thread.h"
  31. #include "util/thread_map.h"
  32. #include "util/top.h"
  33. #include "util/util.h"
  34. #include <linux/rbtree.h>
  35. #include "util/parse-options.h"
  36. #include "util/parse-events.h"
  37. #include "util/cpumap.h"
  38. #include "util/xyarray.h"
  39. #include "util/sort.h"
  40. #include "util/intlist.h"
  41. #include "arch/common.h"
  42. #include "util/debug.h"
  43. #include <assert.h>
  44. #include <elf.h>
  45. #include <fcntl.h>
  46. #include <stdio.h>
  47. #include <termios.h>
  48. #include <unistd.h>
  49. #include <inttypes.h>
  50. #include <errno.h>
  51. #include <time.h>
  52. #include <sched.h>
  53. #include <sys/syscall.h>
  54. #include <sys/ioctl.h>
  55. #include <sys/poll.h>
  56. #include <sys/prctl.h>
  57. #include <sys/wait.h>
  58. #include <sys/uio.h>
  59. #include <sys/utsname.h>
  60. #include <sys/mman.h>
  61. #include <linux/unistd.h>
  62. #include <linux/types.h>
  63. static volatile int done;
  64. #define HEADER_LINE_NR 5
  65. static void perf_top__update_print_entries(struct perf_top *top)
  66. {
  67. top->print_entries = top->winsize.ws_row - HEADER_LINE_NR;
  68. }
  69. static void perf_top__sig_winch(int sig __maybe_unused,
  70. siginfo_t *info __maybe_unused, void *arg)
  71. {
  72. struct perf_top *top = arg;
  73. get_term_dimensions(&top->winsize);
  74. perf_top__update_print_entries(top);
  75. }
  76. static int perf_top__parse_source(struct perf_top *top, struct hist_entry *he)
  77. {
  78. struct symbol *sym;
  79. struct annotation *notes;
  80. struct map *map;
  81. int err = -1;
  82. if (!he || !he->ms.sym)
  83. return -1;
  84. sym = he->ms.sym;
  85. map = he->ms.map;
  86. /*
  87. * We can't annotate with just /proc/kallsyms
  88. */
  89. if (map->dso->symtab_type == DSO_BINARY_TYPE__KALLSYMS &&
  90. !dso__is_kcore(map->dso)) {
  91. pr_err("Can't annotate %s: No vmlinux file was found in the "
  92. "path\n", sym->name);
  93. sleep(1);
  94. return -1;
  95. }
  96. notes = symbol__annotation(sym);
  97. if (notes->src != NULL) {
  98. pthread_mutex_lock(&notes->lock);
  99. goto out_assign;
  100. }
  101. pthread_mutex_lock(&notes->lock);
  102. if (symbol__alloc_hist(sym) < 0) {
  103. pthread_mutex_unlock(&notes->lock);
  104. pr_err("Not enough memory for annotating '%s' symbol!\n",
  105. sym->name);
  106. sleep(1);
  107. return err;
  108. }
  109. err = symbol__annotate(sym, map, 0);
  110. if (err == 0) {
  111. out_assign:
  112. top->sym_filter_entry = he;
  113. }
  114. pthread_mutex_unlock(&notes->lock);
  115. return err;
  116. }
  117. static void __zero_source_counters(struct hist_entry *he)
  118. {
  119. struct symbol *sym = he->ms.sym;
  120. symbol__annotate_zero_histograms(sym);
  121. }
  122. static void ui__warn_map_erange(struct map *map, struct symbol *sym, u64 ip)
  123. {
  124. struct utsname uts;
  125. int err = uname(&uts);
  126. ui__warning("Out of bounds address found:\n\n"
  127. "Addr: %" PRIx64 "\n"
  128. "DSO: %s %c\n"
  129. "Map: %" PRIx64 "-%" PRIx64 "\n"
  130. "Symbol: %" PRIx64 "-%" PRIx64 " %c %s\n"
  131. "Arch: %s\n"
  132. "Kernel: %s\n"
  133. "Tools: %s\n\n"
  134. "Not all samples will be on the annotation output.\n\n"
  135. "Please report to linux-kernel@vger.kernel.org\n",
  136. ip, map->dso->long_name, dso__symtab_origin(map->dso),
  137. map->start, map->end, sym->start, sym->end,
  138. sym->binding == STB_GLOBAL ? 'g' :
  139. sym->binding == STB_LOCAL ? 'l' : 'w', sym->name,
  140. err ? "[unknown]" : uts.machine,
  141. err ? "[unknown]" : uts.release, perf_version_string);
  142. if (use_browser <= 0)
  143. sleep(5);
  144. map->erange_warned = true;
  145. }
  146. static void perf_top__record_precise_ip(struct perf_top *top,
  147. struct hist_entry *he,
  148. int counter, u64 ip)
  149. {
  150. struct annotation *notes;
  151. struct symbol *sym;
  152. int err;
  153. if (he == NULL || he->ms.sym == NULL ||
  154. ((top->sym_filter_entry == NULL ||
  155. top->sym_filter_entry->ms.sym != he->ms.sym) && use_browser != 1))
  156. return;
  157. sym = he->ms.sym;
  158. notes = symbol__annotation(sym);
  159. if (pthread_mutex_trylock(&notes->lock))
  160. return;
  161. if (notes->src == NULL && symbol__alloc_hist(sym) < 0) {
  162. pthread_mutex_unlock(&notes->lock);
  163. pr_err("Not enough memory for annotating '%s' symbol!\n",
  164. sym->name);
  165. sleep(1);
  166. return;
  167. }
  168. ip = he->ms.map->map_ip(he->ms.map, ip);
  169. err = symbol__inc_addr_samples(sym, he->ms.map, counter, ip);
  170. pthread_mutex_unlock(&notes->lock);
  171. if (err == -ERANGE && !he->ms.map->erange_warned)
  172. ui__warn_map_erange(he->ms.map, sym, ip);
  173. }
  174. static void perf_top__show_details(struct perf_top *top)
  175. {
  176. struct hist_entry *he = top->sym_filter_entry;
  177. struct annotation *notes;
  178. struct symbol *symbol;
  179. int more;
  180. if (!he)
  181. return;
  182. symbol = he->ms.sym;
  183. notes = symbol__annotation(symbol);
  184. pthread_mutex_lock(&notes->lock);
  185. if (notes->src == NULL)
  186. goto out_unlock;
  187. printf("Showing %s for %s\n", perf_evsel__name(top->sym_evsel), symbol->name);
  188. printf(" Events Pcnt (>=%d%%)\n", top->sym_pcnt_filter);
  189. more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel,
  190. 0, top->sym_pcnt_filter, top->print_entries, 4);
  191. if (top->zero)
  192. symbol__annotate_zero_histogram(symbol, top->sym_evsel->idx);
  193. else
  194. symbol__annotate_decay_histogram(symbol, top->sym_evsel->idx);
  195. if (more != 0)
  196. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  197. out_unlock:
  198. pthread_mutex_unlock(&notes->lock);
  199. }
  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, NULL, NULL,
  207. sample->period, sample->weight,
  208. sample->transaction);
  209. pthread_mutex_unlock(&evsel->hists.lock);
  210. if (he == NULL)
  211. return NULL;
  212. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  213. return he;
  214. }
  215. static void perf_top__print_sym_table(struct perf_top *top)
  216. {
  217. char bf[160];
  218. int printed = 0;
  219. const int win_width = top->winsize.ws_col - 1;
  220. puts(CONSOLE_CLEAR);
  221. perf_top__header_snprintf(top, bf, sizeof(bf));
  222. printf("%s\n", bf);
  223. perf_top__reset_sample_counters(top);
  224. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  225. if (top->sym_evsel->hists.stats.nr_lost_warned !=
  226. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  227. top->sym_evsel->hists.stats.nr_lost_warned =
  228. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  229. color_fprintf(stdout, PERF_COLOR_RED,
  230. "WARNING: LOST %d chunks, Check IO/CPU overload",
  231. top->sym_evsel->hists.stats.nr_lost_warned);
  232. ++printed;
  233. }
  234. if (top->sym_filter_entry) {
  235. perf_top__show_details(top);
  236. return;
  237. }
  238. hists__collapse_resort(&top->sym_evsel->hists, NULL);
  239. hists__output_resort(&top->sym_evsel->hists);
  240. hists__decay_entries(&top->sym_evsel->hists,
  241. top->hide_user_symbols,
  242. top->hide_kernel_symbols);
  243. hists__output_recalc_col_len(&top->sym_evsel->hists,
  244. top->print_entries - printed);
  245. putchar('\n');
  246. hists__fprintf(&top->sym_evsel->hists, false,
  247. top->print_entries - printed, win_width,
  248. top->min_percent, 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 bool perf_top__handle_keypress(struct perf_top *top, int c)
  361. {
  362. bool ret = true;
  363. if (!perf_top__key_mapped(top, c)) {
  364. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  365. struct termios tc, save;
  366. perf_top__print_mapped_keys(top);
  367. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  368. fflush(stdout);
  369. tcgetattr(0, &save);
  370. tc = save;
  371. tc.c_lflag &= ~(ICANON | ECHO);
  372. tc.c_cc[VMIN] = 0;
  373. tc.c_cc[VTIME] = 0;
  374. tcsetattr(0, TCSANOW, &tc);
  375. poll(&stdin_poll, 1, -1);
  376. c = getc(stdin);
  377. tcsetattr(0, TCSAFLUSH, &save);
  378. if (!perf_top__key_mapped(top, c))
  379. return ret;
  380. }
  381. switch (c) {
  382. case 'd':
  383. prompt_integer(&top->delay_secs, "Enter display delay");
  384. if (top->delay_secs < 1)
  385. top->delay_secs = 1;
  386. break;
  387. case 'e':
  388. prompt_integer(&top->print_entries, "Enter display entries (lines)");
  389. if (top->print_entries == 0) {
  390. struct sigaction act = {
  391. .sa_sigaction = perf_top__sig_winch,
  392. .sa_flags = SA_SIGINFO,
  393. };
  394. perf_top__sig_winch(SIGWINCH, NULL, top);
  395. sigaction(SIGWINCH, &act, NULL);
  396. } else {
  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. ret = false;
  436. break;
  437. case 's':
  438. perf_top__prompt_symbol(top, "Enter details symbol");
  439. break;
  440. case 'S':
  441. if (!top->sym_filter_entry)
  442. break;
  443. else {
  444. struct hist_entry *syme = top->sym_filter_entry;
  445. top->sym_filter_entry = NULL;
  446. __zero_source_counters(syme);
  447. }
  448. break;
  449. case 'U':
  450. top->hide_user_symbols = !top->hide_user_symbols;
  451. break;
  452. case 'z':
  453. top->zero = !top->zero;
  454. break;
  455. default:
  456. break;
  457. }
  458. return ret;
  459. }
  460. static void perf_top__sort_new_samples(void *arg)
  461. {
  462. struct perf_top *t = arg;
  463. perf_top__reset_sample_counters(t);
  464. if (t->evlist->selected != NULL)
  465. t->sym_evsel = t->evlist->selected;
  466. hists__collapse_resort(&t->sym_evsel->hists, NULL);
  467. hists__output_resort(&t->sym_evsel->hists);
  468. hists__decay_entries(&t->sym_evsel->hists,
  469. t->hide_user_symbols,
  470. t->hide_kernel_symbols);
  471. }
  472. static void *display_thread_tui(void *arg)
  473. {
  474. struct perf_evsel *pos;
  475. struct perf_top *top = arg;
  476. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  477. struct hist_browser_timer hbt = {
  478. .timer = perf_top__sort_new_samples,
  479. .arg = top,
  480. .refresh = top->delay_secs,
  481. };
  482. perf_top__sort_new_samples(top);
  483. /*
  484. * Initialize the uid_filter_str, in the future the TUI will allow
  485. * Zooming in/out UIDs. For now juse use whatever the user passed
  486. * via --uid.
  487. */
  488. list_for_each_entry(pos, &top->evlist->entries, node)
  489. pos->hists.uid_filter_str = top->record_opts.target.uid_str;
  490. perf_evlist__tui_browse_hists(top->evlist, help, &hbt, top->min_percent,
  491. &top->session->header.env);
  492. done = 1;
  493. return NULL;
  494. }
  495. static void *display_thread(void *arg)
  496. {
  497. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  498. struct termios tc, save;
  499. struct perf_top *top = arg;
  500. int delay_msecs, c;
  501. tcgetattr(0, &save);
  502. tc = save;
  503. tc.c_lflag &= ~(ICANON | ECHO);
  504. tc.c_cc[VMIN] = 0;
  505. tc.c_cc[VTIME] = 0;
  506. pthread__unblock_sigwinch();
  507. repeat:
  508. delay_msecs = top->delay_secs * 1000;
  509. tcsetattr(0, TCSANOW, &tc);
  510. /* trash return*/
  511. getc(stdin);
  512. while (!done) {
  513. perf_top__print_sym_table(top);
  514. /*
  515. * Either timeout expired or we got an EINTR due to SIGWINCH,
  516. * refresh screen in both cases.
  517. */
  518. switch (poll(&stdin_poll, 1, delay_msecs)) {
  519. case 0:
  520. continue;
  521. case -1:
  522. if (errno == EINTR)
  523. continue;
  524. /* Fall trhu */
  525. default:
  526. c = getc(stdin);
  527. tcsetattr(0, TCSAFLUSH, &save);
  528. if (perf_top__handle_keypress(top, c))
  529. goto repeat;
  530. done = 1;
  531. }
  532. }
  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 = sample->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, sample->pid)) {
  592. pr_err("Can't find guest [%d]'s kernel information\n",
  593. sample->pid);
  594. intlist__add(seen, sample->pid);
  595. }
  596. return;
  597. }
  598. if (!machine) {
  599. pr_err("%u unprocessable samples recorded.\r",
  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) < 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. top->max_stack);
  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 (sort__has_sym)
  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. goto next_event;
  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. goto next_event;
  701. machine = &session->machines.host;
  702. break;
  703. case PERF_RECORD_MISC_KERNEL:
  704. ++top->kernel_samples;
  705. if (top->hide_kernel_symbols)
  706. goto next_event;
  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,
  712. sample.pid);
  713. break;
  714. case PERF_RECORD_MISC_GUEST_USER:
  715. ++top->guest_us_samples;
  716. /*
  717. * TODO: we don't process guest user from host side
  718. * except simple counting.
  719. */
  720. /* Fall thru */
  721. default:
  722. goto next_event;
  723. }
  724. if (event->header.type == PERF_RECORD_SAMPLE) {
  725. perf_event__process_sample(&top->tool, event, evsel,
  726. &sample, machine);
  727. } else if (event->header.type < PERF_RECORD_MAX) {
  728. hists__inc_nr_events(&evsel->hists, event->header.type);
  729. machine__process_event(machine, event, &sample);
  730. } else
  731. ++session->stats.nr_unknown_events;
  732. next_event:
  733. perf_evlist__mmap_consume(top->evlist, idx);
  734. }
  735. }
  736. static void perf_top__mmap_read(struct perf_top *top)
  737. {
  738. int i;
  739. for (i = 0; i < top->evlist->nr_mmaps; i++)
  740. perf_top__mmap_read_idx(top, i);
  741. }
  742. static int perf_top__start_counters(struct perf_top *top)
  743. {
  744. char msg[512];
  745. struct perf_evsel *counter;
  746. struct perf_evlist *evlist = top->evlist;
  747. struct perf_record_opts *opts = &top->record_opts;
  748. perf_evlist__config(evlist, opts);
  749. list_for_each_entry(counter, &evlist->entries, node) {
  750. try_again:
  751. if (perf_evsel__open(counter, top->evlist->cpus,
  752. top->evlist->threads) < 0) {
  753. if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  754. if (verbose)
  755. ui__warning("%s\n", msg);
  756. goto try_again;
  757. }
  758. perf_evsel__open_strerror(counter, &opts->target,
  759. errno, msg, sizeof(msg));
  760. ui__error("%s\n", msg);
  761. goto out_err;
  762. }
  763. }
  764. if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
  765. ui__error("Failed to mmap with %d (%s)\n",
  766. errno, strerror(errno));
  767. goto out_err;
  768. }
  769. return 0;
  770. out_err:
  771. return -1;
  772. }
  773. static int perf_top__setup_sample_type(struct perf_top *top __maybe_unused)
  774. {
  775. if (!sort__has_sym) {
  776. if (symbol_conf.use_callchain) {
  777. ui__error("Selected -g but \"sym\" not present in --sort/-s.");
  778. return -EINVAL;
  779. }
  780. } else if (callchain_param.mode != CHAIN_NONE) {
  781. if (callchain_register_param(&callchain_param) < 0) {
  782. ui__error("Can't register callchain params.\n");
  783. return -EINVAL;
  784. }
  785. }
  786. return 0;
  787. }
  788. static int __cmd_top(struct perf_top *top)
  789. {
  790. struct perf_record_opts *opts = &top->record_opts;
  791. pthread_t thread;
  792. int ret;
  793. top->session = perf_session__new(NULL, false, NULL);
  794. if (top->session == NULL)
  795. return -ENOMEM;
  796. machines__set_symbol_filter(&top->session->machines, symbol_filter);
  797. if (!objdump_path) {
  798. ret = perf_session_env__lookup_objdump(&top->session->header.env);
  799. if (ret)
  800. goto out_delete;
  801. }
  802. ret = perf_top__setup_sample_type(top);
  803. if (ret)
  804. goto out_delete;
  805. if (perf_target__has_task(&opts->target))
  806. perf_event__synthesize_thread_map(&top->tool, top->evlist->threads,
  807. perf_event__process,
  808. &top->session->machines.host);
  809. else
  810. perf_event__synthesize_threads(&top->tool, perf_event__process,
  811. &top->session->machines.host);
  812. ret = perf_top__start_counters(top);
  813. if (ret)
  814. goto out_delete;
  815. top->session->evlist = top->evlist;
  816. perf_session__set_id_hdr_size(top->session);
  817. /*
  818. * When perf is starting the traced process, all the events (apart from
  819. * group members) have enable_on_exec=1 set, so don't spoil it by
  820. * prematurely enabling them.
  821. *
  822. * XXX 'top' still doesn't start workloads like record, trace, but should,
  823. * so leave the check here.
  824. */
  825. if (!perf_target__none(&opts->target))
  826. perf_evlist__enable(top->evlist);
  827. /* Wait for a minimal set of events before starting the snapshot */
  828. poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  829. perf_top__mmap_read(top);
  830. ret = -1;
  831. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  832. display_thread), top)) {
  833. ui__error("Could not create display thread.\n");
  834. goto out_delete;
  835. }
  836. if (top->realtime_prio) {
  837. struct sched_param param;
  838. param.sched_priority = top->realtime_prio;
  839. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  840. ui__error("Could not set realtime priority.\n");
  841. goto out_delete;
  842. }
  843. }
  844. while (!done) {
  845. u64 hits = top->samples;
  846. perf_top__mmap_read(top);
  847. if (hits == top->samples)
  848. ret = poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  849. }
  850. ret = 0;
  851. out_delete:
  852. perf_session__delete(top->session);
  853. top->session = NULL;
  854. return ret;
  855. }
  856. static int
  857. callchain_opt(const struct option *opt, const char *arg, int unset)
  858. {
  859. symbol_conf.use_callchain = true;
  860. return record_callchain_opt(opt, arg, unset);
  861. }
  862. static int
  863. parse_callchain_opt(const struct option *opt, const char *arg, int unset)
  864. {
  865. symbol_conf.use_callchain = true;
  866. return record_parse_callchain_opt(opt, arg, unset);
  867. }
  868. static int
  869. parse_percent_limit(const struct option *opt, const char *arg,
  870. int unset __maybe_unused)
  871. {
  872. struct perf_top *top = opt->value;
  873. top->min_percent = strtof(arg, NULL);
  874. return 0;
  875. }
  876. int cmd_top(int argc, const char **argv, const char *prefix __maybe_unused)
  877. {
  878. int status = -1;
  879. char errbuf[BUFSIZ];
  880. struct perf_top top = {
  881. .count_filter = 5,
  882. .delay_secs = 2,
  883. .record_opts = {
  884. .mmap_pages = UINT_MAX,
  885. .user_freq = UINT_MAX,
  886. .user_interval = ULLONG_MAX,
  887. .freq = 4000, /* 4 KHz */
  888. .target = {
  889. .uses_mmap = true,
  890. },
  891. },
  892. .max_stack = PERF_MAX_STACK_DEPTH,
  893. .sym_pcnt_filter = 5,
  894. };
  895. struct perf_record_opts *opts = &top.record_opts;
  896. struct perf_target *target = &opts->target;
  897. const struct option options[] = {
  898. OPT_CALLBACK('e', "event", &top.evlist, "event",
  899. "event selector. use 'perf list' to list available events",
  900. parse_events_option),
  901. OPT_U64('c', "count", &opts->user_interval, "event period to sample"),
  902. OPT_STRING('p', "pid", &target->pid, "pid",
  903. "profile events on existing process id"),
  904. OPT_STRING('t', "tid", &target->tid, "tid",
  905. "profile events on existing thread id"),
  906. OPT_BOOLEAN('a', "all-cpus", &target->system_wide,
  907. "system-wide collection from all CPUs"),
  908. OPT_STRING('C', "cpu", &target->cpu_list, "cpu",
  909. "list of cpus to monitor"),
  910. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  911. "file", "vmlinux pathname"),
  912. OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
  913. "don't load vmlinux even if found"),
  914. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  915. "hide kernel symbols"),
  916. OPT_CALLBACK('m', "mmap-pages", &opts->mmap_pages, "pages",
  917. "number of mmap data pages",
  918. perf_evlist__parse_mmap_pages),
  919. OPT_INTEGER('r', "realtime", &top.realtime_prio,
  920. "collect data with this RT SCHED_FIFO priority"),
  921. OPT_INTEGER('d', "delay", &top.delay_secs,
  922. "number of seconds to delay between refreshes"),
  923. OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
  924. "dump the symbol table used for profiling"),
  925. OPT_INTEGER('f', "count-filter", &top.count_filter,
  926. "only display functions with more events than this"),
  927. OPT_BOOLEAN('g', "group", &opts->group,
  928. "put the counters into a counter group"),
  929. OPT_BOOLEAN('i', "no-inherit", &opts->no_inherit,
  930. "child tasks do not inherit counters"),
  931. OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
  932. "symbol to annotate"),
  933. OPT_BOOLEAN('z', "zero", &top.zero, "zero history across updates"),
  934. OPT_UINTEGER('F', "freq", &opts->user_freq, "profile at this frequency"),
  935. OPT_INTEGER('E', "entries", &top.print_entries,
  936. "display this many functions"),
  937. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  938. "hide user symbols"),
  939. OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
  940. OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
  941. OPT_INCR('v', "verbose", &verbose,
  942. "be more verbose (show counter open errors, etc)"),
  943. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  944. "sort by key(s): pid, comm, dso, symbol, parent, weight, local_weight,"
  945. " abort, in_tx, transaction"),
  946. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  947. "Show a column with the number of samples"),
  948. OPT_CALLBACK_NOOPT('G', NULL, &top.record_opts,
  949. NULL, "enables call-graph recording",
  950. &callchain_opt),
  951. OPT_CALLBACK(0, "call-graph", &top.record_opts,
  952. "mode[,dump_size]", record_callchain_help,
  953. &parse_callchain_opt),
  954. OPT_INTEGER(0, "max-stack", &top.max_stack,
  955. "Set the maximum stack depth when parsing the callchain. "
  956. "Default: " __stringify(PERF_MAX_STACK_DEPTH)),
  957. OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
  958. "ignore callees of these functions in call graphs",
  959. report_parse_ignore_callees_opt),
  960. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  961. "Show a column with the sum of periods"),
  962. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  963. "only consider symbols in these dsos"),
  964. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  965. "only consider symbols in these comms"),
  966. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  967. "only consider these symbols"),
  968. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  969. "Interleave source code with assembly code (default)"),
  970. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  971. "Display raw encoding of assembly instructions (default)"),
  972. OPT_STRING(0, "objdump", &objdump_path, "path",
  973. "objdump binary to use for disassembly and annotations"),
  974. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  975. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  976. OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
  977. OPT_CALLBACK(0, "percent-limit", &top, "percent",
  978. "Don't show entries under that percent", parse_percent_limit),
  979. OPT_END()
  980. };
  981. const char * const top_usage[] = {
  982. "perf top [<options>]",
  983. NULL
  984. };
  985. top.evlist = perf_evlist__new();
  986. if (top.evlist == NULL)
  987. return -ENOMEM;
  988. argc = parse_options(argc, argv, options, top_usage, 0);
  989. if (argc)
  990. usage_with_options(top_usage, options);
  991. if (sort_order == default_sort_order)
  992. sort_order = "dso,symbol";
  993. if (setup_sorting() < 0) {
  994. parse_options_usage(top_usage, options, "s", 1);
  995. goto out_delete_evlist;
  996. }
  997. /* display thread wants entries to be collapsed in a different tree */
  998. sort__need_collapse = 1;
  999. if (top.use_stdio)
  1000. use_browser = 0;
  1001. else if (top.use_tui)
  1002. use_browser = 1;
  1003. setup_browser(false);
  1004. status = perf_target__validate(target);
  1005. if (status) {
  1006. perf_target__strerror(target, status, errbuf, BUFSIZ);
  1007. ui__warning("%s", errbuf);
  1008. }
  1009. status = perf_target__parse_uid(target);
  1010. if (status) {
  1011. int saved_errno = errno;
  1012. perf_target__strerror(target, status, errbuf, BUFSIZ);
  1013. ui__error("%s", errbuf);
  1014. status = -saved_errno;
  1015. goto out_delete_evlist;
  1016. }
  1017. if (perf_target__none(target))
  1018. target->system_wide = true;
  1019. if (perf_evlist__create_maps(top.evlist, target) < 0)
  1020. usage_with_options(top_usage, options);
  1021. if (!top.evlist->nr_entries &&
  1022. perf_evlist__add_default(top.evlist) < 0) {
  1023. ui__error("Not enough memory for event selector list\n");
  1024. goto out_delete_maps;
  1025. }
  1026. symbol_conf.nr_events = top.evlist->nr_entries;
  1027. if (top.delay_secs < 1)
  1028. top.delay_secs = 1;
  1029. if (opts->user_interval != ULLONG_MAX)
  1030. opts->default_interval = opts->user_interval;
  1031. if (opts->user_freq != UINT_MAX)
  1032. opts->freq = opts->user_freq;
  1033. /*
  1034. * User specified count overrides default frequency.
  1035. */
  1036. if (opts->default_interval)
  1037. opts->freq = 0;
  1038. else if (opts->freq) {
  1039. opts->default_interval = opts->freq;
  1040. } else {
  1041. ui__error("frequency and count are zero, aborting\n");
  1042. status = -EINVAL;
  1043. goto out_delete_maps;
  1044. }
  1045. top.sym_evsel = perf_evlist__first(top.evlist);
  1046. symbol_conf.priv_size = sizeof(struct annotation);
  1047. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1048. if (symbol__init() < 0)
  1049. return -1;
  1050. sort__setup_elide(stdout);
  1051. get_term_dimensions(&top.winsize);
  1052. if (top.print_entries == 0) {
  1053. struct sigaction act = {
  1054. .sa_sigaction = perf_top__sig_winch,
  1055. .sa_flags = SA_SIGINFO,
  1056. };
  1057. perf_top__update_print_entries(&top);
  1058. sigaction(SIGWINCH, &act, NULL);
  1059. }
  1060. status = __cmd_top(&top);
  1061. out_delete_maps:
  1062. perf_evlist__delete_maps(top.evlist);
  1063. out_delete_evlist:
  1064. perf_evlist__delete(top.evlist);
  1065. return status;
  1066. }