builtin-top.c 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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. static struct perf_top top = {
  59. .count_filter = 5,
  60. .delay_secs = 2,
  61. .target_pid = -1,
  62. .target_tid = -1,
  63. .freq = 1000, /* 1 KHz */
  64. };
  65. static bool system_wide = false;
  66. static bool use_tui, use_stdio;
  67. static int default_interval = 0;
  68. static bool kptr_restrict_warned;
  69. static bool vmlinux_warned;
  70. static bool inherit = false;
  71. static int realtime_prio = 0;
  72. static bool group = false;
  73. static unsigned int mmap_pages = 128;
  74. static bool dump_symtab = false;
  75. static struct winsize winsize;
  76. static const char *sym_filter = NULL;
  77. static int sym_pcnt_filter = 5;
  78. /*
  79. * Source functions
  80. */
  81. void get_term_dimensions(struct winsize *ws)
  82. {
  83. char *s = getenv("LINES");
  84. if (s != NULL) {
  85. ws->ws_row = atoi(s);
  86. s = getenv("COLUMNS");
  87. if (s != NULL) {
  88. ws->ws_col = atoi(s);
  89. if (ws->ws_row && ws->ws_col)
  90. return;
  91. }
  92. }
  93. #ifdef TIOCGWINSZ
  94. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  95. ws->ws_row && ws->ws_col)
  96. return;
  97. #endif
  98. ws->ws_row = 25;
  99. ws->ws_col = 80;
  100. }
  101. static void update_print_entries(struct winsize *ws)
  102. {
  103. top.print_entries = ws->ws_row;
  104. if (top.print_entries > 9)
  105. top.print_entries -= 9;
  106. }
  107. static void sig_winch_handler(int sig __used)
  108. {
  109. get_term_dimensions(&winsize);
  110. update_print_entries(&winsize);
  111. }
  112. static int parse_source(struct hist_entry *he)
  113. {
  114. struct symbol *sym;
  115. struct annotation *notes;
  116. struct map *map;
  117. int err = -1;
  118. if (!he || !he->ms.sym)
  119. return -1;
  120. sym = he->ms.sym;
  121. map = he->ms.map;
  122. /*
  123. * We can't annotate with just /proc/kallsyms
  124. */
  125. if (map->dso->symtab_type == SYMTAB__KALLSYMS) {
  126. pr_err("Can't annotate %s: No vmlinux file was found in the "
  127. "path\n", sym->name);
  128. sleep(1);
  129. return -1;
  130. }
  131. notes = symbol__annotation(sym);
  132. if (notes->src != NULL) {
  133. pthread_mutex_lock(&notes->lock);
  134. goto out_assign;
  135. }
  136. pthread_mutex_lock(&notes->lock);
  137. if (symbol__alloc_hist(sym, top.evlist->nr_entries) < 0) {
  138. pthread_mutex_unlock(&notes->lock);
  139. pr_err("Not enough memory for annotating '%s' symbol!\n",
  140. sym->name);
  141. sleep(1);
  142. return err;
  143. }
  144. err = symbol__annotate(sym, map, 0);
  145. if (err == 0) {
  146. out_assign:
  147. top.sym_filter_entry = he;
  148. }
  149. pthread_mutex_unlock(&notes->lock);
  150. return err;
  151. }
  152. static void __zero_source_counters(struct hist_entry *he)
  153. {
  154. struct symbol *sym = he->ms.sym;
  155. symbol__annotate_zero_histograms(sym);
  156. }
  157. static void record_precise_ip(struct hist_entry *he, int counter, u64 ip)
  158. {
  159. struct annotation *notes;
  160. struct symbol *sym;
  161. if (he == NULL || he->ms.sym == NULL ||
  162. (he != top.sym_filter_entry && use_browser != 1))
  163. return;
  164. sym = he->ms.sym;
  165. notes = symbol__annotation(sym);
  166. if (pthread_mutex_trylock(&notes->lock))
  167. return;
  168. if (notes->src == NULL &&
  169. symbol__alloc_hist(sym, top.evlist->nr_entries) < 0) {
  170. pthread_mutex_unlock(&notes->lock);
  171. pr_err("Not enough memory for annotating '%s' symbol!\n",
  172. sym->name);
  173. sleep(1);
  174. return;
  175. }
  176. ip = he->ms.map->map_ip(he->ms.map, ip);
  177. symbol__inc_addr_samples(sym, he->ms.map, counter, ip);
  178. pthread_mutex_unlock(&notes->lock);
  179. }
  180. static void show_details(struct hist_entry *he)
  181. {
  182. struct annotation *notes;
  183. struct symbol *symbol;
  184. int more;
  185. if (!he)
  186. return;
  187. symbol = he->ms.sym;
  188. notes = symbol__annotation(symbol);
  189. pthread_mutex_lock(&notes->lock);
  190. if (notes->src == NULL)
  191. goto out_unlock;
  192. printf("Showing %s for %s\n", event_name(top.sym_evsel), symbol->name);
  193. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  194. more = symbol__annotate_printf(symbol, he->ms.map, top.sym_evsel->idx,
  195. 0, sym_pcnt_filter, top.print_entries, 4);
  196. if (top.zero)
  197. symbol__annotate_zero_histogram(symbol, top.sym_evsel->idx);
  198. else
  199. symbol__annotate_decay_histogram(symbol, top.sym_evsel->idx);
  200. if (more != 0)
  201. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  202. out_unlock:
  203. pthread_mutex_unlock(&notes->lock);
  204. }
  205. static const char CONSOLE_CLEAR[] = "";
  206. static struct hist_entry *
  207. perf_session__add_hist_entry(struct perf_session *session,
  208. struct addr_location *al,
  209. struct perf_sample *sample,
  210. struct perf_evsel *evsel)
  211. {
  212. struct hist_entry *he;
  213. he = __hists__add_entry(&evsel->hists, al, NULL, sample->period);
  214. if (he == NULL)
  215. return NULL;
  216. session->hists.stats.total_period += sample->period;
  217. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  218. return he;
  219. }
  220. static void print_sym_table(void)
  221. {
  222. char bf[160];
  223. int printed = 0;
  224. const int win_width = winsize.ws_col - 1;
  225. puts(CONSOLE_CLEAR);
  226. perf_top__header_snprintf(&top, bf, sizeof(bf));
  227. printf("%s\n", bf);
  228. perf_top__reset_sample_counters(&top);
  229. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  230. if (top.total_lost_warned != top.session->hists.stats.total_lost) {
  231. top.total_lost_warned = top.session->hists.stats.total_lost;
  232. color_fprintf(stdout, PERF_COLOR_RED, "WARNING:");
  233. printf(" LOST %" PRIu64 " events, Check IO/CPU overload\n",
  234. top.total_lost_warned);
  235. ++printed;
  236. }
  237. if (top.sym_filter_entry) {
  238. show_details(top.sym_filter_entry);
  239. return;
  240. }
  241. hists__collapse_resort_threaded(&top.sym_evsel->hists);
  242. hists__output_resort_threaded(&top.sym_evsel->hists);
  243. hists__decay_entries(&top.sym_evsel->hists);
  244. hists__output_recalc_col_len(&top.sym_evsel->hists, winsize.ws_row - 3);
  245. putchar('\n');
  246. hists__fprintf(&top.sym_evsel->hists, NULL, false, false,
  247. winsize.ws_row - 4 - printed, win_width, stdout);
  248. }
  249. static void prompt_integer(int *target, const char *msg)
  250. {
  251. char *buf = malloc(0), *p;
  252. size_t dummy = 0;
  253. int tmp;
  254. fprintf(stdout, "\n%s: ", msg);
  255. if (getline(&buf, &dummy, stdin) < 0)
  256. return;
  257. p = strchr(buf, '\n');
  258. if (p)
  259. *p = 0;
  260. p = buf;
  261. while(*p) {
  262. if (!isdigit(*p))
  263. goto out_free;
  264. p++;
  265. }
  266. tmp = strtoul(buf, NULL, 10);
  267. *target = tmp;
  268. out_free:
  269. free(buf);
  270. }
  271. static void prompt_percent(int *target, const char *msg)
  272. {
  273. int tmp = 0;
  274. prompt_integer(&tmp, msg);
  275. if (tmp >= 0 && tmp <= 100)
  276. *target = tmp;
  277. }
  278. static void prompt_symbol(struct hist_entry **target, const char *msg)
  279. {
  280. char *buf = malloc(0), *p;
  281. struct hist_entry *syme = *target, *n, *found = NULL;
  282. struct rb_node *next;
  283. size_t dummy = 0;
  284. /* zero counters of active symbol */
  285. if (syme) {
  286. __zero_source_counters(syme);
  287. *target = NULL;
  288. }
  289. fprintf(stdout, "\n%s: ", msg);
  290. if (getline(&buf, &dummy, stdin) < 0)
  291. goto out_free;
  292. p = strchr(buf, '\n');
  293. if (p)
  294. *p = 0;
  295. next = rb_first(&top.sym_evsel->hists.entries);
  296. while (next) {
  297. n = rb_entry(next, struct hist_entry, rb_node);
  298. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  299. found = n;
  300. break;
  301. }
  302. next = rb_next(&n->rb_node);
  303. }
  304. if (!found) {
  305. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  306. sleep(1);
  307. return;
  308. } else
  309. parse_source(found);
  310. out_free:
  311. free(buf);
  312. }
  313. static void print_mapped_keys(void)
  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", event_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", 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 key_mapped(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. default:
  355. break;
  356. }
  357. return 0;
  358. }
  359. static void handle_keypress(int c)
  360. {
  361. if (!key_mapped(c)) {
  362. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  363. struct termios tc, save;
  364. print_mapped_keys();
  365. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  366. fflush(stdout);
  367. tcgetattr(0, &save);
  368. tc = save;
  369. tc.c_lflag &= ~(ICANON | ECHO);
  370. tc.c_cc[VMIN] = 0;
  371. tc.c_cc[VTIME] = 0;
  372. tcsetattr(0, TCSANOW, &tc);
  373. poll(&stdin_poll, 1, -1);
  374. c = getc(stdin);
  375. tcsetattr(0, TCSAFLUSH, &save);
  376. if (!key_mapped(c))
  377. return;
  378. }
  379. switch (c) {
  380. case 'd':
  381. prompt_integer(&top.delay_secs, "Enter display delay");
  382. if (top.delay_secs < 1)
  383. top.delay_secs = 1;
  384. break;
  385. case 'e':
  386. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  387. if (top.print_entries == 0) {
  388. sig_winch_handler(SIGWINCH);
  389. signal(SIGWINCH, sig_winch_handler);
  390. } else
  391. signal(SIGWINCH, SIG_DFL);
  392. break;
  393. case 'E':
  394. if (top.evlist->nr_entries > 1) {
  395. /* Select 0 as the default event: */
  396. int counter = 0;
  397. fprintf(stderr, "\nAvailable events:");
  398. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  399. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  400. prompt_integer(&counter, "Enter details event counter");
  401. if (counter >= top.evlist->nr_entries) {
  402. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  403. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  404. sleep(1);
  405. break;
  406. }
  407. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  408. if (top.sym_evsel->idx == counter)
  409. break;
  410. } else
  411. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  412. break;
  413. case 'f':
  414. prompt_integer(&top.count_filter, "Enter display event count filter");
  415. break;
  416. case 'F':
  417. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  418. break;
  419. case 'K':
  420. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  421. break;
  422. case 'q':
  423. case 'Q':
  424. printf("exiting.\n");
  425. if (dump_symtab)
  426. perf_session__fprintf_dsos(top.session, stderr);
  427. exit(0);
  428. case 's':
  429. prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
  430. break;
  431. case 'S':
  432. if (!top.sym_filter_entry)
  433. break;
  434. else {
  435. struct hist_entry *syme = top.sym_filter_entry;
  436. top.sym_filter_entry = NULL;
  437. __zero_source_counters(syme);
  438. }
  439. break;
  440. case 'U':
  441. top.hide_user_symbols = !top.hide_user_symbols;
  442. break;
  443. case 'z':
  444. top.zero = !top.zero;
  445. break;
  446. default:
  447. break;
  448. }
  449. }
  450. static void perf_top__sort_new_samples(void *arg)
  451. {
  452. struct perf_top *t = arg;
  453. perf_top__reset_sample_counters(t);
  454. if (t->evlist->selected != NULL)
  455. t->sym_evsel = t->evlist->selected;
  456. hists__collapse_resort_threaded(&t->sym_evsel->hists);
  457. hists__output_resort_threaded(&t->sym_evsel->hists);
  458. hists__decay_entries(&t->sym_evsel->hists);
  459. hists__output_recalc_col_len(&t->sym_evsel->hists, winsize.ws_row - 3);
  460. }
  461. static void *display_thread_tui(void *arg __used)
  462. {
  463. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  464. perf_top__sort_new_samples(&top);
  465. perf_evlist__tui_browse_hists(top.evlist, help,
  466. perf_top__sort_new_samples,
  467. &top, top.delay_secs);
  468. exit_browser(0);
  469. exit(0);
  470. return NULL;
  471. }
  472. static void *display_thread(void *arg __used)
  473. {
  474. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  475. struct termios tc, save;
  476. int delay_msecs, c;
  477. tcgetattr(0, &save);
  478. tc = save;
  479. tc.c_lflag &= ~(ICANON | ECHO);
  480. tc.c_cc[VMIN] = 0;
  481. tc.c_cc[VTIME] = 0;
  482. repeat:
  483. delay_msecs = top.delay_secs * 1000;
  484. tcsetattr(0, TCSANOW, &tc);
  485. /* trash return*/
  486. getc(stdin);
  487. do {
  488. print_sym_table();
  489. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  490. c = getc(stdin);
  491. tcsetattr(0, TCSAFLUSH, &save);
  492. handle_keypress(c);
  493. goto repeat;
  494. return NULL;
  495. }
  496. /* Tag samples to be skipped. */
  497. static const char *skip_symbols[] = {
  498. "default_idle",
  499. "native_safe_halt",
  500. "cpu_idle",
  501. "enter_idle",
  502. "exit_idle",
  503. "mwait_idle",
  504. "mwait_idle_with_hints",
  505. "poll_idle",
  506. "ppc64_runlatch_off",
  507. "pseries_dedicated_idle_sleep",
  508. NULL
  509. };
  510. static int symbol_filter(struct map *map __used, struct symbol *sym)
  511. {
  512. const char *name = sym->name;
  513. int i;
  514. /*
  515. * ppc64 uses function descriptors and appends a '.' to the
  516. * start of every instruction address. Remove it.
  517. */
  518. if (name[0] == '.')
  519. name++;
  520. if (!strcmp(name, "_text") ||
  521. !strcmp(name, "_etext") ||
  522. !strcmp(name, "_sinittext") ||
  523. !strncmp("init_module", name, 11) ||
  524. !strncmp("cleanup_module", name, 14) ||
  525. strstr(name, "_text_start") ||
  526. strstr(name, "_text_end"))
  527. return 1;
  528. for (i = 0; skip_symbols[i]; i++) {
  529. if (!strcmp(skip_symbols[i], name)) {
  530. sym->ignore = true;
  531. break;
  532. }
  533. }
  534. return 0;
  535. }
  536. static void perf_event__process_sample(const union perf_event *event,
  537. struct perf_sample *sample,
  538. struct perf_session *session)
  539. {
  540. u64 ip = event->ip.ip;
  541. struct addr_location al;
  542. struct machine *machine;
  543. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  544. ++top.samples;
  545. switch (origin) {
  546. case PERF_RECORD_MISC_USER:
  547. ++top.us_samples;
  548. if (top.hide_user_symbols)
  549. return;
  550. machine = perf_session__find_host_machine(session);
  551. break;
  552. case PERF_RECORD_MISC_KERNEL:
  553. ++top.kernel_samples;
  554. if (top.hide_kernel_symbols)
  555. return;
  556. machine = perf_session__find_host_machine(session);
  557. break;
  558. case PERF_RECORD_MISC_GUEST_KERNEL:
  559. ++top.guest_kernel_samples;
  560. machine = perf_session__find_machine(session, event->ip.pid);
  561. break;
  562. case PERF_RECORD_MISC_GUEST_USER:
  563. ++top.guest_us_samples;
  564. /*
  565. * TODO: we don't process guest user from host side
  566. * except simple counting.
  567. */
  568. return;
  569. default:
  570. return;
  571. }
  572. if (!machine && perf_guest) {
  573. pr_err("Can't find guest [%d]'s kernel information\n",
  574. event->ip.pid);
  575. return;
  576. }
  577. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  578. top.exact_samples++;
  579. if (perf_event__preprocess_sample(event, session, &al, sample,
  580. symbol_filter) < 0 ||
  581. al.filtered)
  582. return;
  583. if (!kptr_restrict_warned &&
  584. symbol_conf.kptr_restrict &&
  585. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  586. ui__warning(
  587. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  588. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  589. "Kernel%s samples will not be resolved.\n",
  590. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  591. " modules" : "");
  592. if (use_browser <= 0)
  593. sleep(5);
  594. kptr_restrict_warned = true;
  595. }
  596. if (al.sym == NULL) {
  597. const char *msg = "Kernel samples will not be resolved.\n";
  598. /*
  599. * As we do lazy loading of symtabs we only will know if the
  600. * specified vmlinux file is invalid when we actually have a
  601. * hit in kernel space and then try to load it. So if we get
  602. * here and there are _no_ symbols in the DSO backing the
  603. * kernel map, bail out.
  604. *
  605. * We may never get here, for instance, if we use -K/
  606. * --hide-kernel-symbols, even if the user specifies an
  607. * invalid --vmlinux ;-)
  608. */
  609. if (!kptr_restrict_warned && !vmlinux_warned &&
  610. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  611. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  612. if (symbol_conf.vmlinux_name) {
  613. ui__warning("The %s file can't be used.\n%s",
  614. symbol_conf.vmlinux_name, msg);
  615. } else {
  616. ui__warning("A vmlinux file was not found.\n%s",
  617. msg);
  618. }
  619. if (use_browser <= 0)
  620. sleep(5);
  621. vmlinux_warned = true;
  622. }
  623. }
  624. if (al.sym == NULL || !al.sym->ignore) {
  625. struct perf_evsel *evsel;
  626. struct hist_entry *he;
  627. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  628. assert(evsel != NULL);
  629. he = perf_session__add_hist_entry(session, &al, sample, evsel);
  630. if (he == NULL) {
  631. pr_err("Problem incrementing symbol period, skipping event\n");
  632. return;
  633. }
  634. record_precise_ip(he, evsel->idx, ip);
  635. }
  636. return;
  637. }
  638. static void perf_session__mmap_read_idx(struct perf_session *self, int idx)
  639. {
  640. struct perf_sample sample;
  641. union perf_event *event;
  642. int ret;
  643. while ((event = perf_evlist__mmap_read(top.evlist, idx)) != NULL) {
  644. ret = perf_session__parse_sample(self, event, &sample);
  645. if (ret) {
  646. pr_err("Can't parse sample, err = %d\n", ret);
  647. continue;
  648. }
  649. if (event->header.type == PERF_RECORD_SAMPLE)
  650. perf_event__process_sample(event, &sample, self);
  651. else
  652. perf_event__process(event, &sample, self);
  653. }
  654. }
  655. static void perf_session__mmap_read(struct perf_session *self)
  656. {
  657. int i;
  658. for (i = 0; i < top.evlist->nr_mmaps; i++)
  659. perf_session__mmap_read_idx(self, i);
  660. }
  661. static void start_counters(struct perf_evlist *evlist)
  662. {
  663. struct perf_evsel *counter;
  664. list_for_each_entry(counter, &evlist->entries, node) {
  665. struct perf_event_attr *attr = &counter->attr;
  666. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  667. if (top.freq) {
  668. attr->sample_type |= PERF_SAMPLE_PERIOD;
  669. attr->freq = 1;
  670. attr->sample_freq = top.freq;
  671. }
  672. if (evlist->nr_entries > 1) {
  673. attr->sample_type |= PERF_SAMPLE_ID;
  674. attr->read_format |= PERF_FORMAT_ID;
  675. }
  676. attr->mmap = 1;
  677. attr->comm = 1;
  678. attr->inherit = inherit;
  679. try_again:
  680. if (perf_evsel__open(counter, top.evlist->cpus,
  681. top.evlist->threads, group) < 0) {
  682. int err = errno;
  683. if (err == EPERM || err == EACCES) {
  684. ui__warning_paranoid();
  685. goto out_err;
  686. }
  687. /*
  688. * If it's cycles then fall back to hrtimer
  689. * based cpu-clock-tick sw counter, which
  690. * is always available even if no PMU support:
  691. */
  692. if (attr->type == PERF_TYPE_HARDWARE &&
  693. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  694. if (verbose)
  695. ui__warning("Cycles event not supported,\n"
  696. "trying to fall back to cpu-clock-ticks\n");
  697. attr->type = PERF_TYPE_SOFTWARE;
  698. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  699. goto try_again;
  700. }
  701. if (err == ENOENT) {
  702. ui__warning("The %s event is not supported.\n",
  703. event_name(counter));
  704. goto out_err;
  705. }
  706. ui__warning("The sys_perf_event_open() syscall "
  707. "returned with %d (%s). /bin/dmesg "
  708. "may provide additional information.\n"
  709. "No CONFIG_PERF_EVENTS=y kernel support "
  710. "configured?\n", err, strerror(err));
  711. goto out_err;
  712. }
  713. }
  714. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0) {
  715. ui__warning("Failed to mmap with %d (%s)\n",
  716. errno, strerror(errno));
  717. goto out_err;
  718. }
  719. return;
  720. out_err:
  721. exit_browser(0);
  722. exit(0);
  723. }
  724. static int __cmd_top(void)
  725. {
  726. pthread_t thread;
  727. int ret __used;
  728. /*
  729. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  730. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  731. */
  732. top.session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  733. if (top.session == NULL)
  734. return -ENOMEM;
  735. if (top.target_tid != -1)
  736. perf_event__synthesize_thread_map(top.evlist->threads,
  737. perf_event__process, top.session);
  738. else
  739. perf_event__synthesize_threads(perf_event__process, top.session);
  740. start_counters(top.evlist);
  741. top.session->evlist = top.evlist;
  742. perf_session__update_sample_type(top.session);
  743. /* Wait for a minimal set of events before starting the snapshot */
  744. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  745. perf_session__mmap_read(top.session);
  746. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  747. display_thread), NULL)) {
  748. printf("Could not create display thread.\n");
  749. exit(-1);
  750. }
  751. if (realtime_prio) {
  752. struct sched_param param;
  753. param.sched_priority = realtime_prio;
  754. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  755. printf("Could not set realtime priority.\n");
  756. exit(-1);
  757. }
  758. }
  759. while (1) {
  760. u64 hits = top.samples;
  761. perf_session__mmap_read(top.session);
  762. if (hits == top.samples)
  763. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  764. }
  765. return 0;
  766. }
  767. static const char * const top_usage[] = {
  768. "perf top [<options>]",
  769. NULL
  770. };
  771. static const struct option options[] = {
  772. OPT_CALLBACK('e', "event", &top.evlist, "event",
  773. "event selector. use 'perf list' to list available events",
  774. parse_events_option),
  775. OPT_INTEGER('c', "count", &default_interval,
  776. "event period to sample"),
  777. OPT_INTEGER('p', "pid", &top.target_pid,
  778. "profile events on existing process id"),
  779. OPT_INTEGER('t', "tid", &top.target_tid,
  780. "profile events on existing thread id"),
  781. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  782. "system-wide collection from all CPUs"),
  783. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  784. "list of cpus to monitor"),
  785. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  786. "file", "vmlinux pathname"),
  787. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  788. "hide kernel symbols"),
  789. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  790. OPT_INTEGER('r', "realtime", &realtime_prio,
  791. "collect data with this RT SCHED_FIFO priority"),
  792. OPT_INTEGER('d', "delay", &top.delay_secs,
  793. "number of seconds to delay between refreshes"),
  794. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  795. "dump the symbol table used for profiling"),
  796. OPT_INTEGER('f', "count-filter", &top.count_filter,
  797. "only display functions with more events than this"),
  798. OPT_BOOLEAN('g', "group", &group,
  799. "put the counters into a counter group"),
  800. OPT_BOOLEAN('i', "inherit", &inherit,
  801. "child tasks inherit counters"),
  802. OPT_STRING(0, "sym-annotate", &sym_filter, "symbol name",
  803. "symbol to annotate"),
  804. OPT_BOOLEAN('z', "zero", &top.zero,
  805. "zero history across updates"),
  806. OPT_INTEGER('F', "freq", &top.freq,
  807. "profile at this frequency"),
  808. OPT_INTEGER('E', "entries", &top.print_entries,
  809. "display this many functions"),
  810. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  811. "hide user symbols"),
  812. OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
  813. OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
  814. OPT_INCR('v', "verbose", &verbose,
  815. "be more verbose (show counter open errors, etc)"),
  816. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  817. "sort by key(s): pid, comm, dso, symbol, parent"),
  818. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  819. "Show a column with the number of samples"),
  820. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  821. "Show a column with the sum of periods"),
  822. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  823. "only consider symbols in these dsos"),
  824. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  825. "only consider symbols in these comms"),
  826. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  827. "only consider these symbols"),
  828. OPT_END()
  829. };
  830. int cmd_top(int argc, const char **argv, const char *prefix __used)
  831. {
  832. struct perf_evsel *pos;
  833. int status = -ENOMEM;
  834. top.evlist = perf_evlist__new(NULL, NULL);
  835. if (top.evlist == NULL)
  836. return -ENOMEM;
  837. symbol_conf.exclude_other = false;
  838. argc = parse_options(argc, argv, options, top_usage, 0);
  839. if (argc)
  840. usage_with_options(top_usage, options);
  841. if (sort_order == default_sort_order)
  842. sort_order = "dso,symbol";
  843. setup_sorting(top_usage, options);
  844. /*
  845. * XXX For now start disabled, only using TUI if explicitely asked for.
  846. * Change that when handle_keys equivalent gets written, live annotation
  847. * done, etc.
  848. */
  849. use_browser = 0;
  850. if (use_stdio)
  851. use_browser = 0;
  852. else if (use_tui)
  853. use_browser = 1;
  854. setup_browser(false);
  855. /* CPU and PID are mutually exclusive */
  856. if (top.target_tid > 0 && top.cpu_list) {
  857. printf("WARNING: PID switch overriding CPU\n");
  858. sleep(1);
  859. top.cpu_list = NULL;
  860. }
  861. if (top.target_pid != -1)
  862. top.target_tid = top.target_pid;
  863. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  864. top.target_tid, top.cpu_list) < 0)
  865. usage_with_options(top_usage, options);
  866. if (!top.evlist->nr_entries &&
  867. perf_evlist__add_default(top.evlist) < 0) {
  868. pr_err("Not enough memory for event selector list\n");
  869. return -ENOMEM;
  870. }
  871. if (top.delay_secs < 1)
  872. top.delay_secs = 1;
  873. /*
  874. * User specified count overrides default frequency.
  875. */
  876. if (default_interval)
  877. top.freq = 0;
  878. else if (top.freq) {
  879. default_interval = top.freq;
  880. } else {
  881. fprintf(stderr, "frequency and count are zero, aborting\n");
  882. exit(EXIT_FAILURE);
  883. }
  884. list_for_each_entry(pos, &top.evlist->entries, node) {
  885. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  886. top.evlist->threads->nr) < 0)
  887. goto out_free_fd;
  888. /*
  889. * Fill in the ones not specifically initialized via -c:
  890. */
  891. if (pos->attr.sample_period)
  892. continue;
  893. pos->attr.sample_period = default_interval;
  894. }
  895. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  896. perf_evlist__alloc_mmap(top.evlist) < 0)
  897. goto out_free_fd;
  898. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  899. symbol_conf.priv_size = sizeof(struct annotation);
  900. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  901. if (symbol__init() < 0)
  902. return -1;
  903. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  904. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  905. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  906. get_term_dimensions(&winsize);
  907. if (top.print_entries == 0) {
  908. update_print_entries(&winsize);
  909. signal(SIGWINCH, sig_winch_handler);
  910. }
  911. status = __cmd_top();
  912. out_free_fd:
  913. perf_evlist__delete(top.evlist);
  914. return status;
  915. }