builtin-top.c 30 KB

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