builtin-top.c 31 KB

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