builtin-top.c 32 KB

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