builtin-top.c 32 KB

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