builtin-top.c 32 KB

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