builtin-top.c 31 KB

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