builtin-top.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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_evsel *pos;
  461. struct perf_top *top = arg;
  462. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  463. perf_top__sort_new_samples(top);
  464. /*
  465. * Initialize the uid_filter_str, in the future the TUI will allow
  466. * Zooming in/out UIDs. For now juse use whatever the user passed
  467. * via --uid.
  468. */
  469. list_for_each_entry(pos, &top->evlist->entries, node)
  470. pos->hists.uid_filter_str = top->uid_str;
  471. perf_evlist__tui_browse_hists(top->evlist, help,
  472. perf_top__sort_new_samples,
  473. top, top->delay_secs);
  474. exit_browser(0);
  475. exit(0);
  476. return NULL;
  477. }
  478. static void *display_thread(void *arg)
  479. {
  480. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  481. struct termios tc, save;
  482. struct perf_top *top = arg;
  483. int delay_msecs, c;
  484. tcgetattr(0, &save);
  485. tc = save;
  486. tc.c_lflag &= ~(ICANON | ECHO);
  487. tc.c_cc[VMIN] = 0;
  488. tc.c_cc[VTIME] = 0;
  489. pthread__unblock_sigwinch();
  490. repeat:
  491. delay_msecs = top->delay_secs * 1000;
  492. tcsetattr(0, TCSANOW, &tc);
  493. /* trash return*/
  494. getc(stdin);
  495. while (1) {
  496. perf_top__print_sym_table(top);
  497. /*
  498. * Either timeout expired or we got an EINTR due to SIGWINCH,
  499. * refresh screen in both cases.
  500. */
  501. switch (poll(&stdin_poll, 1, delay_msecs)) {
  502. case 0:
  503. continue;
  504. case -1:
  505. if (errno == EINTR)
  506. continue;
  507. /* Fall trhu */
  508. default:
  509. goto process_hotkey;
  510. }
  511. }
  512. process_hotkey:
  513. c = getc(stdin);
  514. tcsetattr(0, TCSAFLUSH, &save);
  515. perf_top__handle_keypress(top, c);
  516. goto repeat;
  517. return NULL;
  518. }
  519. /* Tag samples to be skipped. */
  520. static const char *skip_symbols[] = {
  521. "default_idle",
  522. "native_safe_halt",
  523. "cpu_idle",
  524. "enter_idle",
  525. "exit_idle",
  526. "mwait_idle",
  527. "mwait_idle_with_hints",
  528. "poll_idle",
  529. "ppc64_runlatch_off",
  530. "pseries_dedicated_idle_sleep",
  531. NULL
  532. };
  533. static int symbol_filter(struct map *map __used, struct symbol *sym)
  534. {
  535. const char *name = sym->name;
  536. int i;
  537. /*
  538. * ppc64 uses function descriptors and appends a '.' to the
  539. * start of every instruction address. Remove it.
  540. */
  541. if (name[0] == '.')
  542. name++;
  543. if (!strcmp(name, "_text") ||
  544. !strcmp(name, "_etext") ||
  545. !strcmp(name, "_sinittext") ||
  546. !strncmp("init_module", name, 11) ||
  547. !strncmp("cleanup_module", name, 14) ||
  548. strstr(name, "_text_start") ||
  549. strstr(name, "_text_end"))
  550. return 1;
  551. for (i = 0; skip_symbols[i]; i++) {
  552. if (!strcmp(skip_symbols[i], name)) {
  553. sym->ignore = true;
  554. break;
  555. }
  556. }
  557. return 0;
  558. }
  559. static void perf_event__process_sample(struct perf_tool *tool,
  560. const union perf_event *event,
  561. struct perf_evsel *evsel,
  562. struct perf_sample *sample,
  563. struct machine *machine)
  564. {
  565. struct perf_top *top = container_of(tool, struct perf_top, tool);
  566. struct symbol *parent = NULL;
  567. u64 ip = event->ip.ip;
  568. struct addr_location al;
  569. int err;
  570. if (!machine && perf_guest) {
  571. pr_err("Can't find guest [%d]'s kernel information\n",
  572. event->ip.pid);
  573. return;
  574. }
  575. if (!machine) {
  576. pr_err("%u unprocessable samples recorded.",
  577. top->session->hists.stats.nr_unprocessable_samples++);
  578. return;
  579. }
  580. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  581. top->exact_samples++;
  582. if (perf_event__preprocess_sample(event, machine, &al, sample,
  583. symbol_filter) < 0 ||
  584. al.filtered)
  585. return;
  586. if (!top->kptr_restrict_warned &&
  587. symbol_conf.kptr_restrict &&
  588. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  589. ui__warning(
  590. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  591. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  592. "Kernel%s samples will not be resolved.\n",
  593. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  594. " modules" : "");
  595. if (use_browser <= 0)
  596. sleep(5);
  597. top->kptr_restrict_warned = true;
  598. }
  599. if (al.sym == NULL) {
  600. const char *msg = "Kernel samples will not be resolved.\n";
  601. /*
  602. * As we do lazy loading of symtabs we only will know if the
  603. * specified vmlinux file is invalid when we actually have a
  604. * hit in kernel space and then try to load it. So if we get
  605. * here and there are _no_ symbols in the DSO backing the
  606. * kernel map, bail out.
  607. *
  608. * We may never get here, for instance, if we use -K/
  609. * --hide-kernel-symbols, even if the user specifies an
  610. * invalid --vmlinux ;-)
  611. */
  612. if (!top->kptr_restrict_warned && !top->vmlinux_warned &&
  613. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  614. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  615. if (symbol_conf.vmlinux_name) {
  616. ui__warning("The %s file can't be used.\n%s",
  617. symbol_conf.vmlinux_name, msg);
  618. } else {
  619. ui__warning("A vmlinux file was not found.\n%s",
  620. msg);
  621. }
  622. if (use_browser <= 0)
  623. sleep(5);
  624. top->vmlinux_warned = true;
  625. }
  626. }
  627. if (al.sym == NULL || !al.sym->ignore) {
  628. struct hist_entry *he;
  629. if ((sort__has_parent || symbol_conf.use_callchain) &&
  630. sample->callchain) {
  631. err = machine__resolve_callchain(machine, evsel, al.thread,
  632. sample->callchain, &parent);
  633. if (err)
  634. return;
  635. }
  636. he = perf_evsel__add_hist_entry(evsel, &al, sample);
  637. if (he == NULL) {
  638. pr_err("Problem incrementing symbol period, skipping event\n");
  639. return;
  640. }
  641. if (symbol_conf.use_callchain) {
  642. err = callchain_append(he->callchain, &evsel->hists.callchain_cursor,
  643. sample->period);
  644. if (err)
  645. return;
  646. }
  647. if (top->sort_has_symbols)
  648. perf_top__record_precise_ip(top, he, evsel->idx, ip);
  649. }
  650. return;
  651. }
  652. static void perf_top__mmap_read_idx(struct perf_top *top, int idx)
  653. {
  654. struct perf_sample sample;
  655. struct perf_evsel *evsel;
  656. struct perf_session *session = top->session;
  657. union perf_event *event;
  658. struct machine *machine;
  659. u8 origin;
  660. int ret;
  661. while ((event = perf_evlist__mmap_read(top->evlist, idx)) != NULL) {
  662. ret = perf_session__parse_sample(session, event, &sample);
  663. if (ret) {
  664. pr_err("Can't parse sample, err = %d\n", ret);
  665. continue;
  666. }
  667. evsel = perf_evlist__id2evsel(session->evlist, sample.id);
  668. assert(evsel != NULL);
  669. origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  670. if (event->header.type == PERF_RECORD_SAMPLE)
  671. ++top->samples;
  672. switch (origin) {
  673. case PERF_RECORD_MISC_USER:
  674. ++top->us_samples;
  675. if (top->hide_user_symbols)
  676. continue;
  677. machine = perf_session__find_host_machine(session);
  678. break;
  679. case PERF_RECORD_MISC_KERNEL:
  680. ++top->kernel_samples;
  681. if (top->hide_kernel_symbols)
  682. continue;
  683. machine = perf_session__find_host_machine(session);
  684. break;
  685. case PERF_RECORD_MISC_GUEST_KERNEL:
  686. ++top->guest_kernel_samples;
  687. machine = perf_session__find_machine(session, event->ip.pid);
  688. break;
  689. case PERF_RECORD_MISC_GUEST_USER:
  690. ++top->guest_us_samples;
  691. /*
  692. * TODO: we don't process guest user from host side
  693. * except simple counting.
  694. */
  695. /* Fall thru */
  696. default:
  697. continue;
  698. }
  699. if (event->header.type == PERF_RECORD_SAMPLE) {
  700. perf_event__process_sample(&top->tool, event, evsel,
  701. &sample, machine);
  702. } else if (event->header.type < PERF_RECORD_MAX) {
  703. hists__inc_nr_events(&evsel->hists, event->header.type);
  704. perf_event__process(&top->tool, event, &sample, machine);
  705. } else
  706. ++session->hists.stats.nr_unknown_events;
  707. }
  708. }
  709. static void perf_top__mmap_read(struct perf_top *top)
  710. {
  711. int i;
  712. for (i = 0; i < top->evlist->nr_mmaps; i++)
  713. perf_top__mmap_read_idx(top, i);
  714. }
  715. static void perf_top__start_counters(struct perf_top *top)
  716. {
  717. struct perf_evsel *counter, *first;
  718. struct perf_evlist *evlist = top->evlist;
  719. first = list_entry(evlist->entries.next, struct perf_evsel, node);
  720. list_for_each_entry(counter, &evlist->entries, node) {
  721. struct perf_event_attr *attr = &counter->attr;
  722. struct xyarray *group_fd = NULL;
  723. if (top->group && counter != first)
  724. group_fd = first->fd;
  725. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  726. if (top->freq) {
  727. attr->sample_type |= PERF_SAMPLE_PERIOD;
  728. attr->freq = 1;
  729. attr->sample_freq = top->freq;
  730. }
  731. if (evlist->nr_entries > 1) {
  732. attr->sample_type |= PERF_SAMPLE_ID;
  733. attr->read_format |= PERF_FORMAT_ID;
  734. }
  735. if (symbol_conf.use_callchain)
  736. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  737. attr->mmap = 1;
  738. attr->comm = 1;
  739. attr->inherit = top->inherit;
  740. fallback_missing_features:
  741. if (top->exclude_guest_missing)
  742. attr->exclude_guest = attr->exclude_host = 0;
  743. retry_sample_id:
  744. attr->sample_id_all = top->sample_id_all_missing ? 0 : 1;
  745. try_again:
  746. if (perf_evsel__open(counter, top->evlist->cpus,
  747. top->evlist->threads, top->group,
  748. group_fd) < 0) {
  749. int err = errno;
  750. if (err == EPERM || err == EACCES) {
  751. ui__error_paranoid();
  752. goto out_err;
  753. } else if (err == EINVAL) {
  754. if (!top->exclude_guest_missing &&
  755. (attr->exclude_guest || attr->exclude_host)) {
  756. pr_debug("Old kernel, cannot exclude "
  757. "guest or host samples.\n");
  758. top->exclude_guest_missing = true;
  759. goto fallback_missing_features;
  760. } else if (!top->sample_id_all_missing) {
  761. /*
  762. * Old kernel, no attr->sample_id_type_all field
  763. */
  764. top->sample_id_all_missing = true;
  765. goto retry_sample_id;
  766. }
  767. }
  768. /*
  769. * If it's cycles then fall back to hrtimer
  770. * based cpu-clock-tick sw counter, which
  771. * is always available even if no PMU support:
  772. */
  773. if (attr->type == PERF_TYPE_HARDWARE &&
  774. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  775. if (verbose)
  776. ui__warning("Cycles event not supported,\n"
  777. "trying to fall back to cpu-clock-ticks\n");
  778. attr->type = PERF_TYPE_SOFTWARE;
  779. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  780. goto try_again;
  781. }
  782. if (err == ENOENT) {
  783. ui__warning("The %s event is not supported.\n",
  784. event_name(counter));
  785. goto out_err;
  786. } else if (err == EMFILE) {
  787. ui__warning("Too many events are opened.\n"
  788. "Try again after reducing the number of events\n");
  789. goto out_err;
  790. }
  791. ui__warning("The sys_perf_event_open() syscall "
  792. "returned with %d (%s). /bin/dmesg "
  793. "may provide additional information.\n"
  794. "No CONFIG_PERF_EVENTS=y kernel support "
  795. "configured?\n", err, strerror(err));
  796. goto out_err;
  797. }
  798. }
  799. if (perf_evlist__mmap(evlist, top->mmap_pages, false) < 0) {
  800. ui__warning("Failed to mmap with %d (%s)\n",
  801. errno, strerror(errno));
  802. goto out_err;
  803. }
  804. return;
  805. out_err:
  806. exit_browser(0);
  807. exit(0);
  808. }
  809. static int perf_top__setup_sample_type(struct perf_top *top)
  810. {
  811. if (!top->sort_has_symbols) {
  812. if (symbol_conf.use_callchain) {
  813. ui__warning("Selected -g but \"sym\" not present in --sort/-s.");
  814. return -EINVAL;
  815. }
  816. } else if (!top->dont_use_callchains && callchain_param.mode != CHAIN_NONE) {
  817. if (callchain_register_param(&callchain_param) < 0) {
  818. ui__warning("Can't register callchain params.\n");
  819. return -EINVAL;
  820. }
  821. }
  822. return 0;
  823. }
  824. static int __cmd_top(struct perf_top *top)
  825. {
  826. pthread_t thread;
  827. int ret;
  828. /*
  829. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  830. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  831. */
  832. top->session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  833. if (top->session == NULL)
  834. return -ENOMEM;
  835. ret = perf_top__setup_sample_type(top);
  836. if (ret)
  837. goto out_delete;
  838. if (top->target_tid || top->uid != UINT_MAX)
  839. perf_event__synthesize_thread_map(&top->tool, top->evlist->threads,
  840. perf_event__process,
  841. &top->session->host_machine);
  842. else
  843. perf_event__synthesize_threads(&top->tool, perf_event__process,
  844. &top->session->host_machine);
  845. perf_top__start_counters(top);
  846. top->session->evlist = top->evlist;
  847. perf_session__update_sample_type(top->session);
  848. /* Wait for a minimal set of events before starting the snapshot */
  849. poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  850. perf_top__mmap_read(top);
  851. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  852. display_thread), top)) {
  853. printf("Could not create display thread.\n");
  854. exit(-1);
  855. }
  856. if (top->realtime_prio) {
  857. struct sched_param param;
  858. param.sched_priority = top->realtime_prio;
  859. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  860. printf("Could not set realtime priority.\n");
  861. exit(-1);
  862. }
  863. }
  864. while (1) {
  865. u64 hits = top->samples;
  866. perf_top__mmap_read(top);
  867. if (hits == top->samples)
  868. ret = poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  869. }
  870. out_delete:
  871. perf_session__delete(top->session);
  872. top->session = NULL;
  873. return 0;
  874. }
  875. static int
  876. parse_callchain_opt(const struct option *opt, const char *arg, int unset)
  877. {
  878. struct perf_top *top = (struct perf_top *)opt->value;
  879. char *tok, *tok2;
  880. char *endptr;
  881. /*
  882. * --no-call-graph
  883. */
  884. if (unset) {
  885. top->dont_use_callchains = true;
  886. return 0;
  887. }
  888. symbol_conf.use_callchain = true;
  889. if (!arg)
  890. return 0;
  891. tok = strtok((char *)arg, ",");
  892. if (!tok)
  893. return -1;
  894. /* get the output mode */
  895. if (!strncmp(tok, "graph", strlen(arg)))
  896. callchain_param.mode = CHAIN_GRAPH_ABS;
  897. else if (!strncmp(tok, "flat", strlen(arg)))
  898. callchain_param.mode = CHAIN_FLAT;
  899. else if (!strncmp(tok, "fractal", strlen(arg)))
  900. callchain_param.mode = CHAIN_GRAPH_REL;
  901. else if (!strncmp(tok, "none", strlen(arg))) {
  902. callchain_param.mode = CHAIN_NONE;
  903. symbol_conf.use_callchain = false;
  904. return 0;
  905. } else
  906. return -1;
  907. /* get the min percentage */
  908. tok = strtok(NULL, ",");
  909. if (!tok)
  910. goto setup;
  911. callchain_param.min_percent = strtod(tok, &endptr);
  912. if (tok == endptr)
  913. return -1;
  914. /* get the print limit */
  915. tok2 = strtok(NULL, ",");
  916. if (!tok2)
  917. goto setup;
  918. if (tok2[0] != 'c') {
  919. callchain_param.print_limit = strtod(tok2, &endptr);
  920. tok2 = strtok(NULL, ",");
  921. if (!tok2)
  922. goto setup;
  923. }
  924. /* get the call chain order */
  925. if (!strcmp(tok2, "caller"))
  926. callchain_param.order = ORDER_CALLER;
  927. else if (!strcmp(tok2, "callee"))
  928. callchain_param.order = ORDER_CALLEE;
  929. else
  930. return -1;
  931. setup:
  932. if (callchain_register_param(&callchain_param) < 0) {
  933. fprintf(stderr, "Can't register callchain params\n");
  934. return -1;
  935. }
  936. return 0;
  937. }
  938. static const char * const top_usage[] = {
  939. "perf top [<options>]",
  940. NULL
  941. };
  942. int cmd_top(int argc, const char **argv, const char *prefix __used)
  943. {
  944. struct perf_evsel *pos;
  945. int status = -ENOMEM;
  946. struct perf_top top = {
  947. .count_filter = 5,
  948. .delay_secs = 2,
  949. .uid = UINT_MAX,
  950. .freq = 1000, /* 1 KHz */
  951. .mmap_pages = 128,
  952. .sym_pcnt_filter = 5,
  953. };
  954. char callchain_default_opt[] = "fractal,0.5,callee";
  955. const struct option options[] = {
  956. OPT_CALLBACK('e', "event", &top.evlist, "event",
  957. "event selector. use 'perf list' to list available events",
  958. parse_events_option),
  959. OPT_INTEGER('c', "count", &top.default_interval,
  960. "event period to sample"),
  961. OPT_STRING('p', "pid", &top.target_pid, "pid",
  962. "profile events on existing process id"),
  963. OPT_STRING('t', "tid", &top.target_tid, "tid",
  964. "profile events on existing thread id"),
  965. OPT_BOOLEAN('a', "all-cpus", &top.system_wide,
  966. "system-wide collection from all CPUs"),
  967. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  968. "list of cpus to monitor"),
  969. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  970. "file", "vmlinux pathname"),
  971. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  972. "hide kernel symbols"),
  973. OPT_UINTEGER('m', "mmap-pages", &top.mmap_pages, "number of mmap data pages"),
  974. OPT_INTEGER('r', "realtime", &top.realtime_prio,
  975. "collect data with this RT SCHED_FIFO priority"),
  976. OPT_INTEGER('d', "delay", &top.delay_secs,
  977. "number of seconds to delay between refreshes"),
  978. OPT_BOOLEAN('D', "dump-symtab", &top.dump_symtab,
  979. "dump the symbol table used for profiling"),
  980. OPT_INTEGER('f', "count-filter", &top.count_filter,
  981. "only display functions with more events than this"),
  982. OPT_BOOLEAN('g', "group", &top.group,
  983. "put the counters into a counter group"),
  984. OPT_BOOLEAN('i', "inherit", &top.inherit,
  985. "child tasks inherit counters"),
  986. OPT_STRING(0, "sym-annotate", &top.sym_filter, "symbol name",
  987. "symbol to annotate"),
  988. OPT_BOOLEAN('z', "zero", &top.zero,
  989. "zero history across updates"),
  990. OPT_INTEGER('F', "freq", &top.freq,
  991. "profile at this frequency"),
  992. OPT_INTEGER('E', "entries", &top.print_entries,
  993. "display this many functions"),
  994. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  995. "hide user symbols"),
  996. OPT_BOOLEAN(0, "tui", &top.use_tui, "Use the TUI interface"),
  997. OPT_BOOLEAN(0, "stdio", &top.use_stdio, "Use the stdio interface"),
  998. OPT_INCR('v', "verbose", &verbose,
  999. "be more verbose (show counter open errors, etc)"),
  1000. OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
  1001. "sort by key(s): pid, comm, dso, symbol, parent"),
  1002. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  1003. "Show a column with the number of samples"),
  1004. OPT_CALLBACK_DEFAULT('G', "call-graph", &top, "output_type,min_percent, call_order",
  1005. "Display callchains using output_type (graph, flat, fractal, or none), min percent threshold and callchain order. "
  1006. "Default: fractal,0.5,callee", &parse_callchain_opt,
  1007. callchain_default_opt),
  1008. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  1009. "Show a column with the sum of periods"),
  1010. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  1011. "only consider symbols in these dsos"),
  1012. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  1013. "only consider symbols in these comms"),
  1014. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  1015. "only consider these symbols"),
  1016. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  1017. "Interleave source code with assembly code (default)"),
  1018. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  1019. "Display raw encoding of assembly instructions (default)"),
  1020. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  1021. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  1022. OPT_STRING('u', "uid", &top.uid_str, "user", "user to profile"),
  1023. OPT_END()
  1024. };
  1025. top.evlist = perf_evlist__new(NULL, NULL);
  1026. if (top.evlist == NULL)
  1027. return -ENOMEM;
  1028. symbol_conf.exclude_other = false;
  1029. argc = parse_options(argc, argv, options, top_usage, 0);
  1030. if (argc)
  1031. usage_with_options(top_usage, options);
  1032. if (sort_order == default_sort_order)
  1033. sort_order = "dso,symbol";
  1034. setup_sorting(top_usage, options);
  1035. if (top.use_stdio)
  1036. use_browser = 0;
  1037. else if (top.use_tui)
  1038. use_browser = 1;
  1039. setup_browser(false);
  1040. top.uid = parse_target_uid(top.uid_str, top.target_tid, top.target_pid);
  1041. if (top.uid_str != NULL && top.uid == UINT_MAX - 1)
  1042. goto out_delete_evlist;
  1043. /* CPU and PID are mutually exclusive */
  1044. if (top.target_tid && top.cpu_list) {
  1045. printf("WARNING: PID switch overriding CPU\n");
  1046. sleep(1);
  1047. top.cpu_list = NULL;
  1048. }
  1049. if (top.target_pid)
  1050. top.target_tid = top.target_pid;
  1051. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  1052. top.target_tid, top.uid, top.cpu_list) < 0)
  1053. usage_with_options(top_usage, options);
  1054. if (!top.evlist->nr_entries &&
  1055. perf_evlist__add_default(top.evlist) < 0) {
  1056. pr_err("Not enough memory for event selector list\n");
  1057. return -ENOMEM;
  1058. }
  1059. symbol_conf.nr_events = top.evlist->nr_entries;
  1060. if (top.delay_secs < 1)
  1061. top.delay_secs = 1;
  1062. /*
  1063. * User specified count overrides default frequency.
  1064. */
  1065. if (top.default_interval)
  1066. top.freq = 0;
  1067. else if (top.freq) {
  1068. top.default_interval = top.freq;
  1069. } else {
  1070. fprintf(stderr, "frequency and count are zero, aborting\n");
  1071. exit(EXIT_FAILURE);
  1072. }
  1073. list_for_each_entry(pos, &top.evlist->entries, node) {
  1074. /*
  1075. * Fill in the ones not specifically initialized via -c:
  1076. */
  1077. if (!pos->attr.sample_period)
  1078. pos->attr.sample_period = top.default_interval;
  1079. }
  1080. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  1081. symbol_conf.priv_size = sizeof(struct annotation);
  1082. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1083. if (symbol__init() < 0)
  1084. return -1;
  1085. sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
  1086. sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
  1087. sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
  1088. /*
  1089. * Avoid annotation data structures overhead when symbols aren't on the
  1090. * sort list.
  1091. */
  1092. top.sort_has_symbols = sort_sym.list.next != NULL;
  1093. get_term_dimensions(&top.winsize);
  1094. if (top.print_entries == 0) {
  1095. struct sigaction act = {
  1096. .sa_sigaction = perf_top__sig_winch,
  1097. .sa_flags = SA_SIGINFO,
  1098. };
  1099. perf_top__update_print_entries(&top);
  1100. sigaction(SIGWINCH, &act, NULL);
  1101. }
  1102. status = __cmd_top(&top);
  1103. out_delete_evlist:
  1104. perf_evlist__delete(top.evlist);
  1105. return status;
  1106. }