builtin-top.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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 <sys/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;
  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. if (notes->src == NULL && symbol__alloc_hist(sym) < 0) {
  162. pthread_mutex_unlock(&notes->lock);
  163. pr_err("Not enough memory for annotating '%s' symbol!\n",
  164. sym->name);
  165. sleep(1);
  166. return;
  167. }
  168. ip = he->ms.map->map_ip(he->ms.map, ip);
  169. err = symbol__inc_addr_samples(sym, he->ms.map, counter, ip);
  170. pthread_mutex_unlock(&notes->lock);
  171. if (err == -ERANGE && !he->ms.map->erange_warned)
  172. ui__warn_map_erange(he->ms.map, sym, ip);
  173. }
  174. static void perf_top__show_details(struct perf_top *top)
  175. {
  176. struct hist_entry *he = top->sym_filter_entry;
  177. struct annotation *notes;
  178. struct symbol *symbol;
  179. int more;
  180. if (!he)
  181. return;
  182. symbol = he->ms.sym;
  183. notes = symbol__annotation(symbol);
  184. pthread_mutex_lock(&notes->lock);
  185. if (notes->src == NULL)
  186. goto out_unlock;
  187. printf("Showing %s for %s\n", perf_evsel__name(top->sym_evsel), symbol->name);
  188. printf(" Events Pcnt (>=%d%%)\n", top->sym_pcnt_filter);
  189. more = symbol__annotate_printf(symbol, he->ms.map, top->sym_evsel,
  190. 0, top->sym_pcnt_filter, top->print_entries, 4);
  191. if (top->zero)
  192. symbol__annotate_zero_histogram(symbol, top->sym_evsel->idx);
  193. else
  194. symbol__annotate_decay_histogram(symbol, top->sym_evsel->idx);
  195. if (more != 0)
  196. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  197. out_unlock:
  198. pthread_mutex_unlock(&notes->lock);
  199. }
  200. static struct hist_entry *perf_evsel__add_hist_entry(struct perf_evsel *evsel,
  201. struct addr_location *al,
  202. struct perf_sample *sample)
  203. {
  204. struct hist_entry *he;
  205. pthread_mutex_lock(&evsel->hists.lock);
  206. he = __hists__add_entry(&evsel->hists, al, NULL, NULL, NULL,
  207. sample->period, sample->weight,
  208. sample->transaction);
  209. pthread_mutex_unlock(&evsel->hists.lock);
  210. if (he == NULL)
  211. return NULL;
  212. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  213. return he;
  214. }
  215. static void perf_top__print_sym_table(struct perf_top *top)
  216. {
  217. char bf[160];
  218. int printed = 0;
  219. const int win_width = top->winsize.ws_col - 1;
  220. puts(CONSOLE_CLEAR);
  221. perf_top__header_snprintf(top, bf, sizeof(bf));
  222. printf("%s\n", bf);
  223. perf_top__reset_sample_counters(top);
  224. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  225. if (top->sym_evsel->hists.stats.nr_lost_warned !=
  226. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  227. top->sym_evsel->hists.stats.nr_lost_warned =
  228. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  229. color_fprintf(stdout, PERF_COLOR_RED,
  230. "WARNING: LOST %d chunks, Check IO/CPU overload",
  231. top->sym_evsel->hists.stats.nr_lost_warned);
  232. ++printed;
  233. }
  234. if (top->sym_filter_entry) {
  235. perf_top__show_details(top);
  236. return;
  237. }
  238. hists__collapse_resort(&top->sym_evsel->hists, NULL);
  239. hists__output_resort(&top->sym_evsel->hists);
  240. hists__decay_entries(&top->sym_evsel->hists,
  241. top->hide_user_symbols,
  242. top->hide_kernel_symbols);
  243. hists__output_recalc_col_len(&top->sym_evsel->hists,
  244. top->print_entries - printed);
  245. putchar('\n');
  246. hists__fprintf(&top->sym_evsel->hists, false,
  247. top->print_entries - printed, win_width,
  248. top->min_percent, stdout);
  249. }
  250. static void prompt_integer(int *target, const char *msg)
  251. {
  252. char *buf = malloc(0), *p;
  253. size_t dummy = 0;
  254. int tmp;
  255. fprintf(stdout, "\n%s: ", msg);
  256. if (getline(&buf, &dummy, stdin) < 0)
  257. return;
  258. p = strchr(buf, '\n');
  259. if (p)
  260. *p = 0;
  261. p = buf;
  262. while(*p) {
  263. if (!isdigit(*p))
  264. goto out_free;
  265. p++;
  266. }
  267. tmp = strtoul(buf, NULL, 10);
  268. *target = tmp;
  269. out_free:
  270. free(buf);
  271. }
  272. static void prompt_percent(int *target, const char *msg)
  273. {
  274. int tmp = 0;
  275. prompt_integer(&tmp, msg);
  276. if (tmp >= 0 && tmp <= 100)
  277. *target = tmp;
  278. }
  279. static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
  280. {
  281. char *buf = malloc(0), *p;
  282. struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
  283. struct rb_node *next;
  284. size_t dummy = 0;
  285. /* zero counters of active symbol */
  286. if (syme) {
  287. __zero_source_counters(syme);
  288. top->sym_filter_entry = NULL;
  289. }
  290. fprintf(stdout, "\n%s: ", msg);
  291. if (getline(&buf, &dummy, stdin) < 0)
  292. goto out_free;
  293. p = strchr(buf, '\n');
  294. if (p)
  295. *p = 0;
  296. next = rb_first(&top->sym_evsel->hists.entries);
  297. while (next) {
  298. n = rb_entry(next, struct hist_entry, rb_node);
  299. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  300. found = n;
  301. break;
  302. }
  303. next = rb_next(&n->rb_node);
  304. }
  305. if (!found) {
  306. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  307. sleep(1);
  308. } else
  309. perf_top__parse_source(top, found);
  310. out_free:
  311. free(buf);
  312. }
  313. static void perf_top__print_mapped_keys(struct perf_top *top)
  314. {
  315. char *name = NULL;
  316. if (top->sym_filter_entry) {
  317. struct symbol *sym = top->sym_filter_entry->ms.sym;
  318. name = sym->name;
  319. }
  320. fprintf(stdout, "\nMapped keys:\n");
  321. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
  322. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
  323. if (top->evlist->nr_entries > 1)
  324. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel));
  325. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
  326. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->sym_pcnt_filter);
  327. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  328. fprintf(stdout, "\t[S] stop annotation.\n");
  329. fprintf(stdout,
  330. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  331. top->hide_kernel_symbols ? "yes" : "no");
  332. fprintf(stdout,
  333. "\t[U] hide user symbols. \t(%s)\n",
  334. top->hide_user_symbols ? "yes" : "no");
  335. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
  336. fprintf(stdout, "\t[qQ] quit.\n");
  337. }
  338. static int perf_top__key_mapped(struct perf_top *top, int c)
  339. {
  340. switch (c) {
  341. case 'd':
  342. case 'e':
  343. case 'f':
  344. case 'z':
  345. case 'q':
  346. case 'Q':
  347. case 'K':
  348. case 'U':
  349. case 'F':
  350. case 's':
  351. case 'S':
  352. return 1;
  353. case 'E':
  354. return top->evlist->nr_entries > 1 ? 1 : 0;
  355. default:
  356. break;
  357. }
  358. return 0;
  359. }
  360. static bool perf_top__handle_keypress(struct perf_top *top, int c)
  361. {
  362. bool ret = true;
  363. if (!perf_top__key_mapped(top, c)) {
  364. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  365. struct termios tc, save;
  366. perf_top__print_mapped_keys(top);
  367. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  368. fflush(stdout);
  369. tcgetattr(0, &save);
  370. tc = save;
  371. tc.c_lflag &= ~(ICANON | ECHO);
  372. tc.c_cc[VMIN] = 0;
  373. tc.c_cc[VTIME] = 0;
  374. tcsetattr(0, TCSANOW, &tc);
  375. poll(&stdin_poll, 1, -1);
  376. c = getc(stdin);
  377. tcsetattr(0, TCSAFLUSH, &save);
  378. if (!perf_top__key_mapped(top, c))
  379. return ret;
  380. }
  381. switch (c) {
  382. case 'd':
  383. prompt_integer(&top->delay_secs, "Enter display delay");
  384. if (top->delay_secs < 1)
  385. top->delay_secs = 1;
  386. break;
  387. case 'e':
  388. prompt_integer(&top->print_entries, "Enter display entries (lines)");
  389. if (top->print_entries == 0) {
  390. struct sigaction act = {
  391. .sa_sigaction = perf_top__sig_winch,
  392. .sa_flags = SA_SIGINFO,
  393. };
  394. perf_top__sig_winch(SIGWINCH, NULL, top);
  395. sigaction(SIGWINCH, &act, NULL);
  396. } else {
  397. signal(SIGWINCH, SIG_DFL);
  398. }
  399. break;
  400. case 'E':
  401. if (top->evlist->nr_entries > 1) {
  402. /* Select 0 as the default event: */
  403. int counter = 0;
  404. fprintf(stderr, "\nAvailable events:");
  405. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  406. fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel));
  407. prompt_integer(&counter, "Enter details event counter");
  408. if (counter >= top->evlist->nr_entries) {
  409. top->sym_evsel = perf_evlist__first(top->evlist);
  410. fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel));
  411. sleep(1);
  412. break;
  413. }
  414. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  415. if (top->sym_evsel->idx == counter)
  416. break;
  417. } else
  418. top->sym_evsel = perf_evlist__first(top->evlist);
  419. break;
  420. case 'f':
  421. prompt_integer(&top->count_filter, "Enter display event count filter");
  422. break;
  423. case 'F':
  424. prompt_percent(&top->sym_pcnt_filter,
  425. "Enter details display event filter (percent)");
  426. break;
  427. case 'K':
  428. top->hide_kernel_symbols = !top->hide_kernel_symbols;
  429. break;
  430. case 'q':
  431. case 'Q':
  432. printf("exiting.\n");
  433. if (top->dump_symtab)
  434. perf_session__fprintf_dsos(top->session, stderr);
  435. ret = false;
  436. break;
  437. case 's':
  438. perf_top__prompt_symbol(top, "Enter details symbol");
  439. break;
  440. case 'S':
  441. if (!top->sym_filter_entry)
  442. break;
  443. else {
  444. struct hist_entry *syme = top->sym_filter_entry;
  445. top->sym_filter_entry = NULL;
  446. __zero_source_counters(syme);
  447. }
  448. break;
  449. case 'U':
  450. top->hide_user_symbols = !top->hide_user_symbols;
  451. break;
  452. case 'z':
  453. top->zero = !top->zero;
  454. break;
  455. default:
  456. break;
  457. }
  458. return ret;
  459. }
  460. static void perf_top__sort_new_samples(void *arg)
  461. {
  462. struct perf_top *t = arg;
  463. perf_top__reset_sample_counters(t);
  464. if (t->evlist->selected != NULL)
  465. t->sym_evsel = t->evlist->selected;
  466. hists__collapse_resort(&t->sym_evsel->hists, NULL);
  467. hists__output_resort(&t->sym_evsel->hists);
  468. hists__decay_entries(&t->sym_evsel->hists,
  469. t->hide_user_symbols,
  470. t->hide_kernel_symbols);
  471. }
  472. static void *display_thread_tui(void *arg)
  473. {
  474. struct perf_evsel *pos;
  475. struct perf_top *top = arg;
  476. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  477. struct hist_browser_timer hbt = {
  478. .timer = perf_top__sort_new_samples,
  479. .arg = top,
  480. .refresh = top->delay_secs,
  481. };
  482. perf_top__sort_new_samples(top);
  483. /*
  484. * Initialize the uid_filter_str, in the future the TUI will allow
  485. * Zooming in/out UIDs. For now juse use whatever the user passed
  486. * via --uid.
  487. */
  488. list_for_each_entry(pos, &top->evlist->entries, node)
  489. pos->hists.uid_filter_str = top->record_opts.target.uid_str;
  490. perf_evlist__tui_browse_hists(top->evlist, help, &hbt, top->min_percent,
  491. &top->session->header.env);
  492. done = 1;
  493. return NULL;
  494. }
  495. static void *display_thread(void *arg)
  496. {
  497. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  498. struct termios tc, save;
  499. struct perf_top *top = arg;
  500. int delay_msecs, c;
  501. tcgetattr(0, &save);
  502. tc = save;
  503. tc.c_lflag &= ~(ICANON | ECHO);
  504. tc.c_cc[VMIN] = 0;
  505. tc.c_cc[VTIME] = 0;
  506. pthread__unblock_sigwinch();
  507. repeat:
  508. delay_msecs = top->delay_secs * 1000;
  509. tcsetattr(0, TCSANOW, &tc);
  510. /* trash return*/
  511. getc(stdin);
  512. while (!done) {
  513. perf_top__print_sym_table(top);
  514. /*
  515. * Either timeout expired or we got an EINTR due to SIGWINCH,
  516. * refresh screen in both cases.
  517. */
  518. switch (poll(&stdin_poll, 1, delay_msecs)) {
  519. case 0:
  520. continue;
  521. case -1:
  522. if (errno == EINTR)
  523. continue;
  524. /* Fall trhu */
  525. default:
  526. c = getc(stdin);
  527. tcsetattr(0, TCSAFLUSH, &save);
  528. if (perf_top__handle_keypress(top, c))
  529. goto repeat;
  530. done = 1;
  531. }
  532. }
  533. return NULL;
  534. }
  535. /* Tag samples to be skipped. */
  536. static const char *skip_symbols[] = {
  537. "intel_idle",
  538. "default_idle",
  539. "native_safe_halt",
  540. "cpu_idle",
  541. "enter_idle",
  542. "exit_idle",
  543. "mwait_idle",
  544. "mwait_idle_with_hints",
  545. "poll_idle",
  546. "ppc64_runlatch_off",
  547. "pseries_dedicated_idle_sleep",
  548. NULL
  549. };
  550. static int symbol_filter(struct map *map __maybe_unused, struct symbol *sym)
  551. {
  552. const char *name = sym->name;
  553. int i;
  554. /*
  555. * ppc64 uses function descriptors and appends a '.' to the
  556. * start of every instruction address. Remove it.
  557. */
  558. if (name[0] == '.')
  559. name++;
  560. if (!strcmp(name, "_text") ||
  561. !strcmp(name, "_etext") ||
  562. !strcmp(name, "_sinittext") ||
  563. !strncmp("init_module", name, 11) ||
  564. !strncmp("cleanup_module", name, 14) ||
  565. strstr(name, "_text_start") ||
  566. strstr(name, "_text_end"))
  567. return 1;
  568. for (i = 0; skip_symbols[i]; i++) {
  569. if (!strcmp(skip_symbols[i], name)) {
  570. sym->ignore = true;
  571. break;
  572. }
  573. }
  574. return 0;
  575. }
  576. static void perf_event__process_sample(struct perf_tool *tool,
  577. const union perf_event *event,
  578. struct perf_evsel *evsel,
  579. struct perf_sample *sample,
  580. struct machine *machine)
  581. {
  582. struct perf_top *top = container_of(tool, struct perf_top, tool);
  583. struct symbol *parent = NULL;
  584. u64 ip = sample->ip;
  585. struct addr_location al;
  586. int err;
  587. if (!machine && perf_guest) {
  588. static struct intlist *seen;
  589. if (!seen)
  590. seen = intlist__new(NULL);
  591. if (!intlist__has_entry(seen, sample->pid)) {
  592. pr_err("Can't find guest [%d]'s kernel information\n",
  593. sample->pid);
  594. intlist__add(seen, sample->pid);
  595. }
  596. return;
  597. }
  598. if (!machine) {
  599. pr_err("%u unprocessable samples recorded.\r",
  600. top->session->stats.nr_unprocessable_samples++);
  601. return;
  602. }
  603. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  604. top->exact_samples++;
  605. if (perf_event__preprocess_sample(event, machine, &al, sample) < 0 ||
  606. al.filtered)
  607. return;
  608. if (!top->kptr_restrict_warned &&
  609. symbol_conf.kptr_restrict &&
  610. al.cpumode == PERF_RECORD_MISC_KERNEL) {
  611. ui__warning(
  612. "Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
  613. "Check /proc/sys/kernel/kptr_restrict.\n\n"
  614. "Kernel%s samples will not be resolved.\n",
  615. !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
  616. " modules" : "");
  617. if (use_browser <= 0)
  618. sleep(5);
  619. top->kptr_restrict_warned = true;
  620. }
  621. if (al.sym == NULL) {
  622. const char *msg = "Kernel samples will not be resolved.\n";
  623. /*
  624. * As we do lazy loading of symtabs we only will know if the
  625. * specified vmlinux file is invalid when we actually have a
  626. * hit in kernel space and then try to load it. So if we get
  627. * here and there are _no_ symbols in the DSO backing the
  628. * kernel map, bail out.
  629. *
  630. * We may never get here, for instance, if we use -K/
  631. * --hide-kernel-symbols, even if the user specifies an
  632. * invalid --vmlinux ;-)
  633. */
  634. if (!top->kptr_restrict_warned && !top->vmlinux_warned &&
  635. al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  636. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  637. if (symbol_conf.vmlinux_name) {
  638. ui__warning("The %s file can't be used.\n%s",
  639. symbol_conf.vmlinux_name, msg);
  640. } else {
  641. ui__warning("A vmlinux file was not found.\n%s",
  642. msg);
  643. }
  644. if (use_browser <= 0)
  645. sleep(5);
  646. top->vmlinux_warned = true;
  647. }
  648. }
  649. if (al.sym == NULL || !al.sym->ignore) {
  650. struct hist_entry *he;
  651. if ((sort__has_parent || symbol_conf.use_callchain) &&
  652. sample->callchain) {
  653. err = machine__resolve_callchain(machine, evsel,
  654. al.thread, sample,
  655. &parent, &al,
  656. top->max_stack);
  657. if (err)
  658. return;
  659. }
  660. he = perf_evsel__add_hist_entry(evsel, &al, sample);
  661. if (he == NULL) {
  662. pr_err("Problem incrementing symbol period, skipping event\n");
  663. return;
  664. }
  665. if (symbol_conf.use_callchain) {
  666. err = callchain_append(he->callchain, &callchain_cursor,
  667. sample->period);
  668. if (err)
  669. return;
  670. }
  671. if (sort__has_sym)
  672. perf_top__record_precise_ip(top, he, evsel->idx, ip);
  673. }
  674. return;
  675. }
  676. static void perf_top__mmap_read_idx(struct perf_top *top, int idx)
  677. {
  678. struct perf_sample sample;
  679. struct perf_evsel *evsel;
  680. struct perf_session *session = top->session;
  681. union perf_event *event;
  682. struct machine *machine;
  683. u8 origin;
  684. int ret;
  685. while ((event = perf_evlist__mmap_read(top->evlist, idx)) != NULL) {
  686. ret = perf_evlist__parse_sample(top->evlist, event, &sample);
  687. if (ret) {
  688. pr_err("Can't parse sample, err = %d\n", ret);
  689. goto next_event;
  690. }
  691. evsel = perf_evlist__id2evsel(session->evlist, sample.id);
  692. assert(evsel != NULL);
  693. origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  694. if (event->header.type == PERF_RECORD_SAMPLE)
  695. ++top->samples;
  696. switch (origin) {
  697. case PERF_RECORD_MISC_USER:
  698. ++top->us_samples;
  699. if (top->hide_user_symbols)
  700. goto next_event;
  701. machine = &session->machines.host;
  702. break;
  703. case PERF_RECORD_MISC_KERNEL:
  704. ++top->kernel_samples;
  705. if (top->hide_kernel_symbols)
  706. goto next_event;
  707. machine = &session->machines.host;
  708. break;
  709. case PERF_RECORD_MISC_GUEST_KERNEL:
  710. ++top->guest_kernel_samples;
  711. machine = perf_session__find_machine(session,
  712. sample.pid);
  713. break;
  714. case PERF_RECORD_MISC_GUEST_USER:
  715. ++top->guest_us_samples;
  716. /*
  717. * TODO: we don't process guest user from host side
  718. * except simple counting.
  719. */
  720. /* Fall thru */
  721. default:
  722. goto next_event;
  723. }
  724. if (event->header.type == PERF_RECORD_SAMPLE) {
  725. perf_event__process_sample(&top->tool, event, evsel,
  726. &sample, machine);
  727. } else if (event->header.type < PERF_RECORD_MAX) {
  728. hists__inc_nr_events(&evsel->hists, event->header.type);
  729. machine__process_event(machine, event, &sample);
  730. } else
  731. ++session->stats.nr_unknown_events;
  732. next_event:
  733. perf_evlist__mmap_consume(top->evlist, idx);
  734. }
  735. }
  736. static void perf_top__mmap_read(struct perf_top *top)
  737. {
  738. int i;
  739. for (i = 0; i < top->evlist->nr_mmaps; i++)
  740. perf_top__mmap_read_idx(top, i);
  741. }
  742. static int perf_top__start_counters(struct perf_top *top)
  743. {
  744. char msg[512];
  745. struct perf_evsel *counter;
  746. struct perf_evlist *evlist = top->evlist;
  747. struct perf_record_opts *opts = &top->record_opts;
  748. perf_evlist__config(evlist, opts);
  749. list_for_each_entry(counter, &evlist->entries, node) {
  750. try_again:
  751. if (perf_evsel__open(counter, top->evlist->cpus,
  752. top->evlist->threads) < 0) {
  753. if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  754. if (verbose)
  755. ui__warning("%s\n", msg);
  756. goto try_again;
  757. }
  758. perf_evsel__open_strerror(counter, &opts->target,
  759. errno, msg, sizeof(msg));
  760. ui__error("%s\n", msg);
  761. goto out_err;
  762. }
  763. }
  764. if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
  765. ui__error("Failed to mmap with %d (%s)\n",
  766. errno, strerror(errno));
  767. goto out_err;
  768. }
  769. return 0;
  770. out_err:
  771. return -1;
  772. }
  773. static int perf_top__setup_sample_type(struct perf_top *top __maybe_unused)
  774. {
  775. if (!sort__has_sym) {
  776. if (symbol_conf.use_callchain) {
  777. ui__error("Selected -g but \"sym\" not present in --sort/-s.");
  778. return -EINVAL;
  779. }
  780. } else if (callchain_param.mode != CHAIN_NONE) {
  781. if (callchain_register_param(&callchain_param) < 0) {
  782. ui__error("Can't register callchain params.\n");
  783. return -EINVAL;
  784. }
  785. }
  786. return 0;
  787. }
  788. static int __cmd_top(struct perf_top *top)
  789. {
  790. struct perf_record_opts *opts = &top->record_opts;
  791. pthread_t thread;
  792. int ret;
  793. top->session = perf_session__new(NULL, false, NULL);
  794. if (top->session == NULL)
  795. return -ENOMEM;
  796. machines__set_symbol_filter(&top->session->machines, symbol_filter);
  797. if (!objdump_path) {
  798. ret = perf_session_env__lookup_objdump(&top->session->header.env);
  799. if (ret)
  800. goto out_delete;
  801. }
  802. ret = perf_top__setup_sample_type(top);
  803. if (ret)
  804. goto out_delete;
  805. machine__synthesize_threads(&top->session->machines.host, &opts->target,
  806. top->evlist->threads, false);
  807. ret = perf_top__start_counters(top);
  808. if (ret)
  809. goto out_delete;
  810. top->session->evlist = top->evlist;
  811. perf_session__set_id_hdr_size(top->session);
  812. /*
  813. * When perf is starting the traced process, all the events (apart from
  814. * group members) have enable_on_exec=1 set, so don't spoil it by
  815. * prematurely enabling them.
  816. *
  817. * XXX 'top' still doesn't start workloads like record, trace, but should,
  818. * so leave the check here.
  819. */
  820. if (!target__none(&opts->target))
  821. perf_evlist__enable(top->evlist);
  822. /* Wait for a minimal set of events before starting the snapshot */
  823. poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  824. perf_top__mmap_read(top);
  825. ret = -1;
  826. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  827. display_thread), top)) {
  828. ui__error("Could not create display thread.\n");
  829. goto out_delete;
  830. }
  831. if (top->realtime_prio) {
  832. struct sched_param param;
  833. param.sched_priority = top->realtime_prio;
  834. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  835. ui__error("Could not set realtime priority.\n");
  836. goto out_delete;
  837. }
  838. }
  839. while (!done) {
  840. u64 hits = top->samples;
  841. perf_top__mmap_read(top);
  842. if (hits == top->samples)
  843. ret = poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  844. }
  845. ret = 0;
  846. out_delete:
  847. perf_session__delete(top->session);
  848. top->session = NULL;
  849. return ret;
  850. }
  851. static int
  852. callchain_opt(const struct option *opt, const char *arg, int unset)
  853. {
  854. symbol_conf.use_callchain = true;
  855. return record_callchain_opt(opt, arg, unset);
  856. }
  857. static int
  858. parse_callchain_opt(const struct option *opt, const char *arg, int unset)
  859. {
  860. symbol_conf.use_callchain = true;
  861. return record_parse_callchain_opt(opt, arg, unset);
  862. }
  863. static int
  864. parse_percent_limit(const struct option *opt, const char *arg,
  865. int unset __maybe_unused)
  866. {
  867. struct perf_top *top = opt->value;
  868. top->min_percent = strtof(arg, NULL);
  869. return 0;
  870. }
  871. int cmd_top(int argc, const char **argv, const char *prefix __maybe_unused)
  872. {
  873. int status = -1;
  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 perf_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('g', "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, weight, local_weight,"
  940. " abort, in_tx, transaction"),
  941. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  942. "Show a column with the number of samples"),
  943. OPT_CALLBACK_NOOPT('G', NULL, &top.record_opts,
  944. NULL, "enables call-graph recording",
  945. &callchain_opt),
  946. OPT_CALLBACK(0, "call-graph", &top.record_opts,
  947. "mode[,dump_size]", record_callchain_help,
  948. &parse_callchain_opt),
  949. OPT_INTEGER(0, "max-stack", &top.max_stack,
  950. "Set the maximum stack depth when parsing the callchain. "
  951. "Default: " __stringify(PERF_MAX_STACK_DEPTH)),
  952. OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
  953. "ignore callees of these functions in call graphs",
  954. report_parse_ignore_callees_opt),
  955. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  956. "Show a column with the sum of periods"),
  957. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  958. "only consider symbols in these dsos"),
  959. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  960. "only consider symbols in these comms"),
  961. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  962. "only consider these symbols"),
  963. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  964. "Interleave source code with assembly code (default)"),
  965. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  966. "Display raw encoding of assembly instructions (default)"),
  967. OPT_STRING(0, "objdump", &objdump_path, "path",
  968. "objdump binary to use for disassembly and annotations"),
  969. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  970. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  971. OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
  972. OPT_CALLBACK(0, "percent-limit", &top, "percent",
  973. "Don't show entries under that percent", parse_percent_limit),
  974. OPT_END()
  975. };
  976. const char * const top_usage[] = {
  977. "perf top [<options>]",
  978. NULL
  979. };
  980. top.evlist = perf_evlist__new();
  981. if (top.evlist == NULL)
  982. return -ENOMEM;
  983. argc = parse_options(argc, argv, options, top_usage, 0);
  984. if (argc)
  985. usage_with_options(top_usage, options);
  986. if (sort_order == default_sort_order)
  987. sort_order = "dso,symbol";
  988. if (setup_sorting() < 0) {
  989. parse_options_usage(top_usage, options, "s", 1);
  990. goto out_delete_evlist;
  991. }
  992. /* display thread wants entries to be collapsed in a different tree */
  993. sort__need_collapse = 1;
  994. if (top.use_stdio)
  995. use_browser = 0;
  996. else if (top.use_tui)
  997. use_browser = 1;
  998. setup_browser(false);
  999. status = target__validate(target);
  1000. if (status) {
  1001. target__strerror(target, status, errbuf, BUFSIZ);
  1002. ui__warning("%s\n", errbuf);
  1003. }
  1004. status = target__parse_uid(target);
  1005. if (status) {
  1006. int saved_errno = errno;
  1007. target__strerror(target, status, errbuf, BUFSIZ);
  1008. ui__error("%s\n", errbuf);
  1009. status = -saved_errno;
  1010. goto out_delete_evlist;
  1011. }
  1012. if (target__none(target))
  1013. target->system_wide = true;
  1014. if (perf_evlist__create_maps(top.evlist, target) < 0)
  1015. usage_with_options(top_usage, options);
  1016. if (!top.evlist->nr_entries &&
  1017. perf_evlist__add_default(top.evlist) < 0) {
  1018. ui__error("Not enough memory for event selector list\n");
  1019. goto out_delete_maps;
  1020. }
  1021. symbol_conf.nr_events = top.evlist->nr_entries;
  1022. if (top.delay_secs < 1)
  1023. top.delay_secs = 1;
  1024. if (perf_record_opts__config(opts)) {
  1025. status = -EINVAL;
  1026. goto out_delete_maps;
  1027. }
  1028. top.sym_evsel = perf_evlist__first(top.evlist);
  1029. symbol_conf.priv_size = sizeof(struct annotation);
  1030. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1031. if (symbol__init() < 0)
  1032. return -1;
  1033. sort__setup_elide(stdout);
  1034. get_term_dimensions(&top.winsize);
  1035. if (top.print_entries == 0) {
  1036. struct sigaction act = {
  1037. .sa_sigaction = perf_top__sig_winch,
  1038. .sa_flags = SA_SIGINFO,
  1039. };
  1040. perf_top__update_print_entries(&top);
  1041. sigaction(SIGWINCH, &act, NULL);
  1042. }
  1043. status = __cmd_top(&top);
  1044. out_delete_maps:
  1045. perf_evlist__delete_maps(top.evlist);
  1046. out_delete_evlist:
  1047. perf_evlist__delete(top.evlist);
  1048. return status;
  1049. }