builtin-top.c 31 KB

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