builtin-top.c 33 KB

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