builtin-top.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  196. return he;
  197. }
  198. static void perf_top__print_sym_table(struct perf_top *top)
  199. {
  200. char bf[160];
  201. int printed = 0;
  202. const int win_width = top->winsize.ws_col - 1;
  203. puts(CONSOLE_CLEAR);
  204. perf_top__header_snprintf(top, bf, sizeof(bf));
  205. printf("%s\n", bf);
  206. perf_top__reset_sample_counters(top);
  207. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  208. if (top->sym_evsel->hists.stats.nr_lost_warned !=
  209. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  210. top->sym_evsel->hists.stats.nr_lost_warned =
  211. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  212. color_fprintf(stdout, PERF_COLOR_RED,
  213. "WARNING: LOST %d chunks, Check IO/CPU overload",
  214. top->sym_evsel->hists.stats.nr_lost_warned);
  215. ++printed;
  216. }
  217. if (top->sym_filter_entry) {
  218. perf_top__show_details(top);
  219. return;
  220. }
  221. hists__collapse_resort_threaded(&top->sym_evsel->hists);
  222. hists__output_resort_threaded(&top->sym_evsel->hists);
  223. hists__decay_entries_threaded(&top->sym_evsel->hists,
  224. top->hide_user_symbols,
  225. top->hide_kernel_symbols);
  226. hists__output_recalc_col_len(&top->sym_evsel->hists,
  227. top->winsize.ws_row - 3);
  228. putchar('\n');
  229. hists__fprintf(&top->sym_evsel->hists, NULL, false, false,
  230. top->winsize.ws_row - 4 - printed, win_width, stdout);
  231. }
  232. static void prompt_integer(int *target, const char *msg)
  233. {
  234. char *buf = malloc(0), *p;
  235. size_t dummy = 0;
  236. int tmp;
  237. fprintf(stdout, "\n%s: ", msg);
  238. if (getline(&buf, &dummy, stdin) < 0)
  239. return;
  240. p = strchr(buf, '\n');
  241. if (p)
  242. *p = 0;
  243. p = buf;
  244. while(*p) {
  245. if (!isdigit(*p))
  246. goto out_free;
  247. p++;
  248. }
  249. tmp = strtoul(buf, NULL, 10);
  250. *target = tmp;
  251. out_free:
  252. free(buf);
  253. }
  254. static void prompt_percent(int *target, const char *msg)
  255. {
  256. int tmp = 0;
  257. prompt_integer(&tmp, msg);
  258. if (tmp >= 0 && tmp <= 100)
  259. *target = tmp;
  260. }
  261. static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
  262. {
  263. char *buf = malloc(0), *p;
  264. struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
  265. struct rb_node *next;
  266. size_t dummy = 0;
  267. /* zero counters of active symbol */
  268. if (syme) {
  269. __zero_source_counters(syme);
  270. top->sym_filter_entry = NULL;
  271. }
  272. fprintf(stdout, "\n%s: ", msg);
  273. if (getline(&buf, &dummy, stdin) < 0)
  274. goto out_free;
  275. p = strchr(buf, '\n');
  276. if (p)
  277. *p = 0;
  278. next = rb_first(&top->sym_evsel->hists.entries);
  279. while (next) {
  280. n = rb_entry(next, struct hist_entry, rb_node);
  281. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  282. found = n;
  283. break;
  284. }
  285. next = rb_next(&n->rb_node);
  286. }
  287. if (!found) {
  288. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  289. sleep(1);
  290. } else
  291. perf_top__parse_source(top, found);
  292. out_free:
  293. free(buf);
  294. }
  295. static void perf_top__print_mapped_keys(struct perf_top *top)
  296. {
  297. char *name = NULL;
  298. if (top->sym_filter_entry) {
  299. struct symbol *sym = top->sym_filter_entry->ms.sym;
  300. name = sym->name;
  301. }
  302. fprintf(stdout, "\nMapped keys:\n");
  303. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
  304. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
  305. if (top->evlist->nr_entries > 1)
  306. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top->sym_evsel));
  307. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
  308. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->sym_pcnt_filter);
  309. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  310. fprintf(stdout, "\t[S] stop annotation.\n");
  311. fprintf(stdout,
  312. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  313. top->hide_kernel_symbols ? "yes" : "no");
  314. fprintf(stdout,
  315. "\t[U] hide user symbols. \t(%s)\n",
  316. top->hide_user_symbols ? "yes" : "no");
  317. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
  318. fprintf(stdout, "\t[qQ] quit.\n");
  319. }
  320. static int perf_top__key_mapped(struct perf_top *top, int c)
  321. {
  322. switch (c) {
  323. case 'd':
  324. case 'e':
  325. case 'f':
  326. case 'z':
  327. case 'q':
  328. case 'Q':
  329. case 'K':
  330. case 'U':
  331. case 'F':
  332. case 's':
  333. case 'S':
  334. return 1;
  335. case 'E':
  336. return top->evlist->nr_entries > 1 ? 1 : 0;
  337. default:
  338. break;
  339. }
  340. return 0;
  341. }
  342. static void perf_top__handle_keypress(struct perf_top *top, int c)
  343. {
  344. if (!perf_top__key_mapped(top, c)) {
  345. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  346. struct termios tc, save;
  347. perf_top__print_mapped_keys(top);
  348. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  349. fflush(stdout);
  350. tcgetattr(0, &save);
  351. tc = save;
  352. tc.c_lflag &= ~(ICANON | ECHO);
  353. tc.c_cc[VMIN] = 0;
  354. tc.c_cc[VTIME] = 0;
  355. tcsetattr(0, TCSANOW, &tc);
  356. poll(&stdin_poll, 1, -1);
  357. c = getc(stdin);
  358. tcsetattr(0, TCSAFLUSH, &save);
  359. if (!perf_top__key_mapped(top, c))
  360. return;
  361. }
  362. switch (c) {
  363. case 'd':
  364. prompt_integer(&top->delay_secs, "Enter display delay");
  365. if (top->delay_secs < 1)
  366. top->delay_secs = 1;
  367. break;
  368. case 'e':
  369. prompt_integer(&top->print_entries, "Enter display entries (lines)");
  370. if (top->print_entries == 0) {
  371. struct sigaction act = {
  372. .sa_sigaction = perf_top__sig_winch,
  373. .sa_flags = SA_SIGINFO,
  374. };
  375. perf_top__sig_winch(SIGWINCH, NULL, top);
  376. sigaction(SIGWINCH, &act, NULL);
  377. } else
  378. signal(SIGWINCH, SIG_DFL);
  379. break;
  380. case 'E':
  381. if (top->evlist->nr_entries > 1) {
  382. /* Select 0 as the default event: */
  383. int counter = 0;
  384. fprintf(stderr, "\nAvailable events:");
  385. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  386. fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, event_name(top->sym_evsel));
  387. prompt_integer(&counter, "Enter details event counter");
  388. if (counter >= top->evlist->nr_entries) {
  389. top->sym_evsel = list_entry(top->evlist->entries.next, struct perf_evsel, node);
  390. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top->sym_evsel));
  391. sleep(1);
  392. break;
  393. }
  394. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  395. if (top->sym_evsel->idx == counter)
  396. break;
  397. } else
  398. top->sym_evsel = list_entry(top->evlist->entries.next, struct perf_evsel, node);
  399. break;
  400. case 'f':
  401. prompt_integer(&top->count_filter, "Enter display event count filter");
  402. break;
  403. case 'F':
  404. prompt_percent(&top->sym_pcnt_filter,
  405. "Enter details display event filter (percent)");
  406. break;
  407. case 'K':
  408. top->hide_kernel_symbols = !top->hide_kernel_symbols;
  409. break;
  410. case 'q':
  411. case 'Q':
  412. printf("exiting.\n");
  413. if (top->dump_symtab)
  414. perf_session__fprintf_dsos(top->session, stderr);
  415. exit(0);
  416. case 's':
  417. perf_top__prompt_symbol(top, "Enter details symbol");
  418. break;
  419. case 'S':
  420. if (!top->sym_filter_entry)
  421. break;
  422. else {
  423. struct hist_entry *syme = top->sym_filter_entry;
  424. top->sym_filter_entry = NULL;
  425. __zero_source_counters(syme);
  426. }
  427. break;
  428. case 'U':
  429. top->hide_user_symbols = !top->hide_user_symbols;
  430. break;
  431. case 'z':
  432. top->zero = !top->zero;
  433. break;
  434. default:
  435. break;
  436. }
  437. }
  438. static void perf_top__sort_new_samples(void *arg)
  439. {
  440. struct perf_top *t = arg;
  441. perf_top__reset_sample_counters(t);
  442. if (t->evlist->selected != NULL)
  443. t->sym_evsel = t->evlist->selected;
  444. hists__collapse_resort_threaded(&t->sym_evsel->hists);
  445. hists__output_resort_threaded(&t->sym_evsel->hists);
  446. hists__decay_entries_threaded(&t->sym_evsel->hists,
  447. t->hide_user_symbols,
  448. t->hide_kernel_symbols);
  449. }
  450. static void *display_thread_tui(void *arg)
  451. {
  452. struct perf_evsel *pos;
  453. struct perf_top *top = arg;
  454. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  455. perf_top__sort_new_samples(top);
  456. /*
  457. * Initialize the uid_filter_str, in the future the TUI will allow
  458. * Zooming in/out UIDs. For now juse use whatever the user passed
  459. * via --uid.
  460. */
  461. list_for_each_entry(pos, &top->evlist->entries, node)
  462. pos->hists.uid_filter_str = top->uid_str;
  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 || top->uid != UINT_MAX)
  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. .uid = UINT_MAX,
  928. .freq = 1000, /* 1 KHz */
  929. .sample_id_all_avail = true,
  930. .mmap_pages = 128,
  931. .sym_pcnt_filter = 5,
  932. };
  933. char callchain_default_opt[] = "fractal,0.5,callee";
  934. const struct option options[] = {
  935. OPT_CALLBACK('e', "event", &top.evlist, "event",
  936. "event selector. use 'perf list' to list available events",
  937. parse_events_option),
  938. OPT_INTEGER('c', "count", &top.default_interval,
  939. "event period to sample"),
  940. OPT_INTEGER('p', "pid", &top.target_pid,
  941. "profile events on existing process id"),
  942. OPT_INTEGER('t', "tid", &top.target_tid,
  943. "profile events on existing thread id"),
  944. OPT_BOOLEAN('a', "all-cpus", &top.system_wide,
  945. "system-wide collection from all CPUs"),
  946. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  947. "list of cpus to monitor"),
  948. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  949. "file", "vmlinux pathname"),
  950. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  951. "hide kernel symbols"),
  952. OPT_UINTEGER('m', "mmap-pages", &top.mmap_pages, "number of mmap data pages"),
  953. OPT_INTEGER('r', "realtime", &top.realtime_prio,
  954. "collect data with this RT SCHED_FIFO priority"),
  955. OPT_INTEGER('d', "delay", &top.delay_secs,
  956. "number of seconds to delay between refreshes"),
  957. OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
  958. "dump the symbol table used for profiling"),
  959. OPT_INTEGER('f', "count-filter", &top.count_filter,
  960. "only display functions with more events than this"),
  961. OPT_BOOLEAN('g', "group", &top.group,
  962. "put the counters into a counter group"),
  963. OPT_BOOLEAN('i', "inherit", &top.inherit,
  964. "child tasks inherit counters"),
  965. OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
  966. "symbol to annotate"),
  967. OPT_BOOLEAN('z', "zero", &top.zero,
  968. "zero history across updates"),
  969. OPT_INTEGER('F', "freq", &top.freq,
  970. "profile at this frequency"),
  971. OPT_INTEGER('E', "entries", &top.print_entries,
  972. "display this many functions"),
  973. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  974. "hide user symbols"),
  975. OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
  976. OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
  977. OPT_INCR('v', "verbose", &verbose,
  978. "be more verbose (show counter open errors, etc)"),
  979. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  980. "sort by key(s): pid, comm, dso, symbol, parent"),
  981. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  982. "Show a column with the number of samples"),
  983. OPT_CALLBACK_DEFAULT('G', "call-graph", &top, "output_type,min_percent, call_order",
  984. "Display callchains using output_type (graph, flat, fractal, or none), min percent threshold and callchain order. "
  985. "Default: fractal,0.5,callee", &parse_callchain_opt,
  986. callchain_default_opt),
  987. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  988. "Show a column with the sum of periods"),
  989. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  990. "only consider symbols in these dsos"),
  991. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  992. "only consider symbols in these comms"),
  993. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  994. "only consider these symbols"),
  995. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  996. "Interleave source code with assembly code (default)"),
  997. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  998. "Display raw encoding of assembly instructions (default)"),
  999. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  1000. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  1001. OPT_STRING('u', "uid", &top.uid_str, "user", "user to profile"),
  1002. OPT_END()
  1003. };
  1004. top.evlist = perf_evlist__new(NULL, NULL);
  1005. if (top.evlist == NULL)
  1006. return -ENOMEM;
  1007. symbol_conf.exclude_other = false;
  1008. argc = parse_options(argc, argv, options, top_usage, 0);
  1009. if (argc)
  1010. usage_with_options(top_usage, options);
  1011. if (sort_order == default_sort_order)
  1012. sort_order = "dso,symbol";
  1013. setup_sorting(top_usage, options);
  1014. if (top.use_stdio)
  1015. use_browser = 0;
  1016. else if (top.use_tui)
  1017. use_browser = 1;
  1018. setup_browser(false);
  1019. top.uid = parse_target_uid(top.uid_str, top.target_tid, top.target_pid);
  1020. if (top.uid_str != NULL && top.uid == UINT_MAX - 1)
  1021. goto out_delete_evlist;
  1022. /* CPU and PID are mutually exclusive */
  1023. if (top.target_tid > 0 && top.cpu_list) {
  1024. printf("WARNING: PID switch overriding CPU\n");
  1025. sleep(1);
  1026. top.cpu_list = NULL;
  1027. }
  1028. if (top.target_pid != -1)
  1029. top.target_tid = top.target_pid;
  1030. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  1031. top.target_tid, top.uid, top.cpu_list) < 0)
  1032. usage_with_options(top_usage, options);
  1033. if (!top.evlist->nr_entries &&
  1034. perf_evlist__add_default(top.evlist) < 0) {
  1035. pr_err("Not enough memory for event selector list\n");
  1036. return -ENOMEM;
  1037. }
  1038. symbol_conf.nr_events = top.evlist->nr_entries;
  1039. if (top.delay_secs < 1)
  1040. top.delay_secs = 1;
  1041. /*
  1042. * User specified count overrides default frequency.
  1043. */
  1044. if (top.default_interval)
  1045. top.freq = 0;
  1046. else if (top.freq) {
  1047. top.default_interval = top.freq;
  1048. } else {
  1049. fprintf(stderr, "frequency and count are zero, aborting\n");
  1050. exit(EXIT_FAILURE);
  1051. }
  1052. list_for_each_entry(pos, &top.evlist->entries, node) {
  1053. /*
  1054. * Fill in the ones not specifically initialized via -c:
  1055. */
  1056. if (!pos->attr.sample_period)
  1057. pos->attr.sample_period = top.default_interval;
  1058. }
  1059. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  1060. symbol_conf.priv_size = sizeof(struct annotation);
  1061. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1062. if (symbol__init() < 0)
  1063. return -1;
  1064. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  1065. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  1066. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  1067. /*
  1068. * Avoid annotation data structures overhead when symbols aren't on the
  1069. * sort list.
  1070. */
  1071. top.sort_has_symbols = sort_sym.list.next != NULL;
  1072. get_term_dimensions(&top.winsize);
  1073. if (top.print_entries == 0) {
  1074. struct sigaction act = {
  1075. .sa_sigaction = perf_top__sig_winch,
  1076. .sa_flags = SA_SIGINFO,
  1077. };
  1078. perf_top__update_print_entries(&top);
  1079. sigaction(SIGWINCH, &act, NULL);
  1080. }
  1081. status = __cmd_top(&top);
  1082. out_delete_evlist:
  1083. perf_evlist__delete(top.evlist);
  1084. return status;
  1085. }