builtin-top.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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, sample->period,
  207. sample->weight);
  208. pthread_mutex_unlock(&evsel->hists.lock);
  209. if (he == NULL)
  210. return NULL;
  211. hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
  212. return he;
  213. }
  214. static void perf_top__print_sym_table(struct perf_top *top)
  215. {
  216. char bf[160];
  217. int printed = 0;
  218. const int win_width = top->winsize.ws_col - 1;
  219. puts(CONSOLE_CLEAR);
  220. perf_top__header_snprintf(top, bf, sizeof(bf));
  221. printf("%s\n", bf);
  222. perf_top__reset_sample_counters(top);
  223. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  224. if (top->sym_evsel->hists.stats.nr_lost_warned !=
  225. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST]) {
  226. top->sym_evsel->hists.stats.nr_lost_warned =
  227. top->sym_evsel->hists.stats.nr_events[PERF_RECORD_LOST];
  228. color_fprintf(stdout, PERF_COLOR_RED,
  229. "WARNING: LOST %d chunks, Check IO/CPU overload",
  230. top->sym_evsel->hists.stats.nr_lost_warned);
  231. ++printed;
  232. }
  233. if (top->sym_filter_entry) {
  234. perf_top__show_details(top);
  235. return;
  236. }
  237. hists__collapse_resort(&top->sym_evsel->hists);
  238. hists__output_resort(&top->sym_evsel->hists);
  239. hists__decay_entries(&top->sym_evsel->hists,
  240. top->hide_user_symbols,
  241. top->hide_kernel_symbols);
  242. hists__output_recalc_col_len(&top->sym_evsel->hists,
  243. top->print_entries - printed);
  244. putchar('\n');
  245. hists__fprintf(&top->sym_evsel->hists, false,
  246. top->print_entries - printed, win_width,
  247. top->min_percent, stdout);
  248. }
  249. static void prompt_integer(int *target, const char *msg)
  250. {
  251. char *buf = malloc(0), *p;
  252. size_t dummy = 0;
  253. int tmp;
  254. fprintf(stdout, "\n%s: ", msg);
  255. if (getline(&buf, &dummy, stdin) < 0)
  256. return;
  257. p = strchr(buf, '\n');
  258. if (p)
  259. *p = 0;
  260. p = buf;
  261. while(*p) {
  262. if (!isdigit(*p))
  263. goto out_free;
  264. p++;
  265. }
  266. tmp = strtoul(buf, NULL, 10);
  267. *target = tmp;
  268. out_free:
  269. free(buf);
  270. }
  271. static void prompt_percent(int *target, const char *msg)
  272. {
  273. int tmp = 0;
  274. prompt_integer(&tmp, msg);
  275. if (tmp >= 0 && tmp <= 100)
  276. *target = tmp;
  277. }
  278. static void perf_top__prompt_symbol(struct perf_top *top, const char *msg)
  279. {
  280. char *buf = malloc(0), *p;
  281. struct hist_entry *syme = top->sym_filter_entry, *n, *found = NULL;
  282. struct rb_node *next;
  283. size_t dummy = 0;
  284. /* zero counters of active symbol */
  285. if (syme) {
  286. __zero_source_counters(syme);
  287. top->sym_filter_entry = NULL;
  288. }
  289. fprintf(stdout, "\n%s: ", msg);
  290. if (getline(&buf, &dummy, stdin) < 0)
  291. goto out_free;
  292. p = strchr(buf, '\n');
  293. if (p)
  294. *p = 0;
  295. next = rb_first(&top->sym_evsel->hists.entries);
  296. while (next) {
  297. n = rb_entry(next, struct hist_entry, rb_node);
  298. if (n->ms.sym && !strcmp(buf, n->ms.sym->name)) {
  299. found = n;
  300. break;
  301. }
  302. next = rb_next(&n->rb_node);
  303. }
  304. if (!found) {
  305. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  306. sleep(1);
  307. } else
  308. perf_top__parse_source(top, found);
  309. out_free:
  310. free(buf);
  311. }
  312. static void perf_top__print_mapped_keys(struct perf_top *top)
  313. {
  314. char *name = NULL;
  315. if (top->sym_filter_entry) {
  316. struct symbol *sym = top->sym_filter_entry->ms.sym;
  317. name = sym->name;
  318. }
  319. fprintf(stdout, "\nMapped keys:\n");
  320. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top->delay_secs);
  321. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top->print_entries);
  322. if (top->evlist->nr_entries > 1)
  323. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", perf_evsel__name(top->sym_evsel));
  324. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top->count_filter);
  325. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", top->sym_pcnt_filter);
  326. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  327. fprintf(stdout, "\t[S] stop annotation.\n");
  328. fprintf(stdout,
  329. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  330. top->hide_kernel_symbols ? "yes" : "no");
  331. fprintf(stdout,
  332. "\t[U] hide user symbols. \t(%s)\n",
  333. top->hide_user_symbols ? "yes" : "no");
  334. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top->zero ? 1 : 0);
  335. fprintf(stdout, "\t[qQ] quit.\n");
  336. }
  337. static int perf_top__key_mapped(struct perf_top *top, int c)
  338. {
  339. switch (c) {
  340. case 'd':
  341. case 'e':
  342. case 'f':
  343. case 'z':
  344. case 'q':
  345. case 'Q':
  346. case 'K':
  347. case 'U':
  348. case 'F':
  349. case 's':
  350. case 'S':
  351. return 1;
  352. case 'E':
  353. return top->evlist->nr_entries > 1 ? 1 : 0;
  354. default:
  355. break;
  356. }
  357. return 0;
  358. }
  359. static bool perf_top__handle_keypress(struct perf_top *top, int c)
  360. {
  361. bool ret = true;
  362. if (!perf_top__key_mapped(top, c)) {
  363. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  364. struct termios tc, save;
  365. perf_top__print_mapped_keys(top);
  366. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  367. fflush(stdout);
  368. tcgetattr(0, &save);
  369. tc = save;
  370. tc.c_lflag &= ~(ICANON | ECHO);
  371. tc.c_cc[VMIN] = 0;
  372. tc.c_cc[VTIME] = 0;
  373. tcsetattr(0, TCSANOW, &tc);
  374. poll(&stdin_poll, 1, -1);
  375. c = getc(stdin);
  376. tcsetattr(0, TCSAFLUSH, &save);
  377. if (!perf_top__key_mapped(top, c))
  378. return ret;
  379. }
  380. switch (c) {
  381. case 'd':
  382. prompt_integer(&top->delay_secs, "Enter display delay");
  383. if (top->delay_secs < 1)
  384. top->delay_secs = 1;
  385. break;
  386. case 'e':
  387. prompt_integer(&top->print_entries, "Enter display entries (lines)");
  388. if (top->print_entries == 0) {
  389. struct sigaction act = {
  390. .sa_sigaction = perf_top__sig_winch,
  391. .sa_flags = SA_SIGINFO,
  392. };
  393. perf_top__sig_winch(SIGWINCH, NULL, top);
  394. sigaction(SIGWINCH, &act, NULL);
  395. } else {
  396. signal(SIGWINCH, SIG_DFL);
  397. }
  398. break;
  399. case 'E':
  400. if (top->evlist->nr_entries > 1) {
  401. /* Select 0 as the default event: */
  402. int counter = 0;
  403. fprintf(stderr, "\nAvailable events:");
  404. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  405. fprintf(stderr, "\n\t%d %s", top->sym_evsel->idx, perf_evsel__name(top->sym_evsel));
  406. prompt_integer(&counter, "Enter details event counter");
  407. if (counter >= top->evlist->nr_entries) {
  408. top->sym_evsel = perf_evlist__first(top->evlist);
  409. fprintf(stderr, "Sorry, no such event, using %s.\n", perf_evsel__name(top->sym_evsel));
  410. sleep(1);
  411. break;
  412. }
  413. list_for_each_entry(top->sym_evsel, &top->evlist->entries, node)
  414. if (top->sym_evsel->idx == counter)
  415. break;
  416. } else
  417. top->sym_evsel = perf_evlist__first(top->evlist);
  418. break;
  419. case 'f':
  420. prompt_integer(&top->count_filter, "Enter display event count filter");
  421. break;
  422. case 'F':
  423. prompt_percent(&top->sym_pcnt_filter,
  424. "Enter details display event filter (percent)");
  425. break;
  426. case 'K':
  427. top->hide_kernel_symbols = !top->hide_kernel_symbols;
  428. break;
  429. case 'q':
  430. case 'Q':
  431. printf("exiting.\n");
  432. if (top->dump_symtab)
  433. perf_session__fprintf_dsos(top->session, stderr);
  434. ret = false;
  435. break;
  436. case 's':
  437. perf_top__prompt_symbol(top, "Enter details symbol");
  438. break;
  439. case 'S':
  440. if (!top->sym_filter_entry)
  441. break;
  442. else {
  443. struct hist_entry *syme = top->sym_filter_entry;
  444. top->sym_filter_entry = NULL;
  445. __zero_source_counters(syme);
  446. }
  447. break;
  448. case 'U':
  449. top->hide_user_symbols = !top->hide_user_symbols;
  450. break;
  451. case 'z':
  452. top->zero = !top->zero;
  453. break;
  454. default:
  455. break;
  456. }
  457. return ret;
  458. }
  459. static void perf_top__sort_new_samples(void *arg)
  460. {
  461. struct perf_top *t = arg;
  462. perf_top__reset_sample_counters(t);
  463. if (t->evlist->selected != NULL)
  464. t->sym_evsel = t->evlist->selected;
  465. hists__collapse_resort(&t->sym_evsel->hists);
  466. hists__output_resort(&t->sym_evsel->hists);
  467. hists__decay_entries(&t->sym_evsel->hists,
  468. t->hide_user_symbols,
  469. t->hide_kernel_symbols);
  470. }
  471. static void *display_thread_tui(void *arg)
  472. {
  473. struct perf_evsel *pos;
  474. struct perf_top *top = arg;
  475. const char *help = "For a higher level overview, try: perf top --sort comm,dso";
  476. struct hist_browser_timer hbt = {
  477. .timer = perf_top__sort_new_samples,
  478. .arg = top,
  479. .refresh = top->delay_secs,
  480. };
  481. perf_top__sort_new_samples(top);
  482. /*
  483. * Initialize the uid_filter_str, in the future the TUI will allow
  484. * Zooming in/out UIDs. For now juse use whatever the user passed
  485. * via --uid.
  486. */
  487. list_for_each_entry(pos, &top->evlist->entries, node)
  488. pos->hists.uid_filter_str = top->record_opts.target.uid_str;
  489. perf_evlist__tui_browse_hists(top->evlist, help, &hbt, top->min_percent,
  490. &top->session->header.env);
  491. done = 1;
  492. return NULL;
  493. }
  494. static void *display_thread(void *arg)
  495. {
  496. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  497. struct termios tc, save;
  498. struct perf_top *top = arg;
  499. int delay_msecs, c;
  500. tcgetattr(0, &save);
  501. tc = save;
  502. tc.c_lflag &= ~(ICANON | ECHO);
  503. tc.c_cc[VMIN] = 0;
  504. tc.c_cc[VTIME] = 0;
  505. pthread__unblock_sigwinch();
  506. repeat:
  507. delay_msecs = top->delay_secs * 1000;
  508. tcsetattr(0, TCSANOW, &tc);
  509. /* trash return*/
  510. getc(stdin);
  511. while (!done) {
  512. perf_top__print_sym_table(top);
  513. /*
  514. * Either timeout expired or we got an EINTR due to SIGWINCH,
  515. * refresh screen in both cases.
  516. */
  517. switch (poll(&stdin_poll, 1, delay_msecs)) {
  518. case 0:
  519. continue;
  520. case -1:
  521. if (errno == EINTR)
  522. continue;
  523. /* Fall trhu */
  524. default:
  525. c = getc(stdin);
  526. tcsetattr(0, TCSAFLUSH, &save);
  527. if (perf_top__handle_keypress(top, c))
  528. goto repeat;
  529. done = 1;
  530. }
  531. }
  532. return NULL;
  533. }
  534. /* Tag samples to be skipped. */
  535. static const char *skip_symbols[] = {
  536. "intel_idle",
  537. "default_idle",
  538. "native_safe_halt",
  539. "cpu_idle",
  540. "enter_idle",
  541. "exit_idle",
  542. "mwait_idle",
  543. "mwait_idle_with_hints",
  544. "poll_idle",
  545. "ppc64_runlatch_off",
  546. "pseries_dedicated_idle_sleep",
  547. NULL
  548. };
  549. static int symbol_filter(struct map *map __maybe_unused, struct symbol *sym)
  550. {
  551. const char *name = sym->name;
  552. int i;
  553. /*
  554. * ppc64 uses function descriptors and appends a '.' to the
  555. * start of every instruction address. Remove it.
  556. */
  557. if (name[0] == '.')
  558. name++;
  559. if (!strcmp(name, "_text") ||
  560. !strcmp(name, "_etext") ||
  561. !strcmp(name, "_sinittext") ||
  562. !strncmp("init_module", name, 11) ||
  563. !strncmp("cleanup_module", name, 14) ||
  564. strstr(name, "_text_start") ||
  565. strstr(name, "_text_end"))
  566. return 1;
  567. for (i = 0; skip_symbols[i]; i++) {
  568. if (!strcmp(skip_symbols[i], name)) {
  569. sym->ignore = true;
  570. break;
  571. }
  572. }
  573. return 0;
  574. }
  575. static void perf_event__process_sample(struct perf_tool *tool,
  576. const union perf_event *event,
  577. struct perf_evsel *evsel,
  578. struct perf_sample *sample,
  579. struct machine *machine)
  580. {
  581. struct perf_top *top = container_of(tool, struct perf_top, tool);
  582. struct symbol *parent = NULL;
  583. u64 ip = sample->ip;
  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. 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, &al);
  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,
  710. sample.pid);
  711. break;
  712. case PERF_RECORD_MISC_GUEST_USER:
  713. ++top->guest_us_samples;
  714. /*
  715. * TODO: we don't process guest user from host side
  716. * except simple counting.
  717. */
  718. /* Fall thru */
  719. default:
  720. continue;
  721. }
  722. if (event->header.type == PERF_RECORD_SAMPLE) {
  723. perf_event__process_sample(&top->tool, event, evsel,
  724. &sample, machine);
  725. } else if (event->header.type < PERF_RECORD_MAX) {
  726. hists__inc_nr_events(&evsel->hists, event->header.type);
  727. machine__process_event(machine, event);
  728. } else
  729. ++session->stats.nr_unknown_events;
  730. }
  731. }
  732. static void perf_top__mmap_read(struct perf_top *top)
  733. {
  734. int i;
  735. for (i = 0; i < top->evlist->nr_mmaps; i++)
  736. perf_top__mmap_read_idx(top, i);
  737. }
  738. static int perf_top__start_counters(struct perf_top *top)
  739. {
  740. char msg[512];
  741. struct perf_evsel *counter;
  742. struct perf_evlist *evlist = top->evlist;
  743. struct perf_record_opts *opts = &top->record_opts;
  744. perf_evlist__config(evlist, opts);
  745. list_for_each_entry(counter, &evlist->entries, node) {
  746. try_again:
  747. if (perf_evsel__open(counter, top->evlist->cpus,
  748. top->evlist->threads) < 0) {
  749. if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) {
  750. if (verbose)
  751. ui__warning("%s\n", msg);
  752. goto try_again;
  753. }
  754. perf_evsel__open_strerror(counter, &opts->target,
  755. errno, msg, sizeof(msg));
  756. ui__error("%s\n", msg);
  757. goto out_err;
  758. }
  759. }
  760. if (perf_evlist__mmap(evlist, opts->mmap_pages, false) < 0) {
  761. ui__error("Failed to mmap with %d (%s)\n",
  762. errno, strerror(errno));
  763. goto out_err;
  764. }
  765. return 0;
  766. out_err:
  767. return -1;
  768. }
  769. static int perf_top__setup_sample_type(struct perf_top *top __maybe_unused)
  770. {
  771. if (!sort__has_sym) {
  772. if (symbol_conf.use_callchain) {
  773. ui__error("Selected -g but \"sym\" not present in --sort/-s.");
  774. return -EINVAL;
  775. }
  776. } else if (callchain_param.mode != CHAIN_NONE) {
  777. if (callchain_register_param(&callchain_param) < 0) {
  778. ui__error("Can't register callchain params.\n");
  779. return -EINVAL;
  780. }
  781. }
  782. return 0;
  783. }
  784. static int __cmd_top(struct perf_top *top)
  785. {
  786. struct perf_record_opts *opts = &top->record_opts;
  787. pthread_t thread;
  788. int ret;
  789. /*
  790. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  791. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  792. */
  793. top->session = perf_session__new(NULL, O_WRONLY, false, 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. if (perf_target__has_task(&opts->target))
  806. perf_event__synthesize_thread_map(&top->tool, top->evlist->threads,
  807. perf_event__process,
  808. &top->session->machines.host);
  809. else
  810. perf_event__synthesize_threads(&top->tool, perf_event__process,
  811. &top->session->machines.host);
  812. ret = perf_top__start_counters(top);
  813. if (ret)
  814. goto out_delete;
  815. top->session->evlist = top->evlist;
  816. perf_session__set_id_hdr_size(top->session);
  817. /*
  818. * When perf is starting the traced process, all the events (apart from
  819. * group members) have enable_on_exec=1 set, so don't spoil it by
  820. * prematurely enabling them.
  821. *
  822. * XXX 'top' still doesn't start workloads like record, trace, but should,
  823. * so leave the check here.
  824. */
  825. if (!perf_target__none(&opts->target))
  826. perf_evlist__enable(top->evlist);
  827. /* Wait for a minimal set of events before starting the snapshot */
  828. poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  829. perf_top__mmap_read(top);
  830. ret = -1;
  831. if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
  832. display_thread), top)) {
  833. ui__error("Could not create display thread.\n");
  834. goto out_delete;
  835. }
  836. if (top->realtime_prio) {
  837. struct sched_param param;
  838. param.sched_priority = top->realtime_prio;
  839. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  840. ui__error("Could not set realtime priority.\n");
  841. goto out_delete;
  842. }
  843. }
  844. while (!done) {
  845. u64 hits = top->samples;
  846. perf_top__mmap_read(top);
  847. if (hits == top->samples)
  848. ret = poll(top->evlist->pollfd, top->evlist->nr_fds, 100);
  849. }
  850. ret = 0;
  851. out_delete:
  852. perf_session__delete(top->session);
  853. top->session = NULL;
  854. return ret;
  855. }
  856. static int
  857. parse_callchain_opt(const struct option *opt, const char *arg, int unset)
  858. {
  859. /*
  860. * --no-call-graph
  861. */
  862. if (unset)
  863. return 0;
  864. symbol_conf.use_callchain = true;
  865. return record_parse_callchain_opt(opt, arg, unset);
  866. }
  867. static int
  868. parse_percent_limit(const struct option *opt, const char *arg,
  869. int unset __maybe_unused)
  870. {
  871. struct perf_top *top = opt->value;
  872. top->min_percent = strtof(arg, NULL);
  873. return 0;
  874. }
  875. int cmd_top(int argc, const char **argv, const char *prefix __maybe_unused)
  876. {
  877. int status;
  878. char errbuf[BUFSIZ];
  879. struct perf_top top = {
  880. .count_filter = 5,
  881. .delay_secs = 2,
  882. .record_opts = {
  883. .mmap_pages = UINT_MAX,
  884. .user_freq = UINT_MAX,
  885. .user_interval = ULLONG_MAX,
  886. .freq = 4000, /* 4 KHz */
  887. .target = {
  888. .uses_mmap = true,
  889. },
  890. },
  891. .sym_pcnt_filter = 5,
  892. };
  893. struct perf_record_opts *opts = &top.record_opts;
  894. struct perf_target *target = &opts->target;
  895. const struct option options[] = {
  896. OPT_CALLBACK('e', "event", &top.evlist, "event",
  897. "event selector. use 'perf list' to list available events",
  898. parse_events_option),
  899. OPT_U64('c', "count", &opts->user_interval, "event period to sample"),
  900. OPT_STRING('p', "pid", &target->pid, "pid",
  901. "profile events on existing process id"),
  902. OPT_STRING('t', "tid", &target->tid, "tid",
  903. "profile events on existing thread id"),
  904. OPT_BOOLEAN('a', "all-cpus", &target->system_wide,
  905. "system-wide collection from all CPUs"),
  906. OPT_STRING('C', "cpu", &target->cpu_list, "cpu",
  907. "list of cpus to monitor"),
  908. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  909. "file", "vmlinux pathname"),
  910. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  911. "hide kernel symbols"),
  912. OPT_UINTEGER('m', "mmap-pages", &opts->mmap_pages,
  913. "number of mmap data 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. OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
  941. "Show a column with the number of samples"),
  942. OPT_CALLBACK_DEFAULT('G', "call-graph", &top.record_opts,
  943. "mode[,dump_size]", record_callchain_help,
  944. &parse_callchain_opt, "fp"),
  945. OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
  946. "ignore callees of these functions in call graphs",
  947. report_parse_ignore_callees_opt),
  948. OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
  949. "Show a column with the sum of periods"),
  950. OPT_STRING(0, "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
  951. "only consider symbols in these dsos"),
  952. OPT_STRING(0, "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
  953. "only consider symbols in these comms"),
  954. OPT_STRING(0, "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
  955. "only consider these symbols"),
  956. OPT_BOOLEAN(0, "source", &symbol_conf.annotate_src,
  957. "Interleave source code with assembly code (default)"),
  958. OPT_BOOLEAN(0, "asm-raw", &symbol_conf.annotate_asm_raw,
  959. "Display raw encoding of assembly instructions (default)"),
  960. OPT_STRING(0, "objdump", &objdump_path, "path",
  961. "objdump binary to use for disassembly and annotations"),
  962. OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
  963. "Specify disassembler style (e.g. -M intel for intel syntax)"),
  964. OPT_STRING('u', "uid", &target->uid_str, "user", "user to profile"),
  965. OPT_CALLBACK(0, "percent-limit", &top, "percent",
  966. "Don't show entries under that percent", parse_percent_limit),
  967. OPT_END()
  968. };
  969. const char * const top_usage[] = {
  970. "perf top [<options>]",
  971. NULL
  972. };
  973. top.evlist = perf_evlist__new();
  974. if (top.evlist == NULL)
  975. return -ENOMEM;
  976. argc = parse_options(argc, argv, options, top_usage, 0);
  977. if (argc)
  978. usage_with_options(top_usage, options);
  979. if (sort_order == default_sort_order)
  980. sort_order = "dso,symbol";
  981. if (setup_sorting() < 0)
  982. usage_with_options(top_usage, options);
  983. /* display thread wants entries to be collapsed in a different tree */
  984. sort__need_collapse = 1;
  985. if (top.use_stdio)
  986. use_browser = 0;
  987. else if (top.use_tui)
  988. use_browser = 1;
  989. setup_browser(false);
  990. status = perf_target__validate(target);
  991. if (status) {
  992. perf_target__strerror(target, status, errbuf, BUFSIZ);
  993. ui__warning("%s", errbuf);
  994. }
  995. status = perf_target__parse_uid(target);
  996. if (status) {
  997. int saved_errno = errno;
  998. perf_target__strerror(target, status, errbuf, BUFSIZ);
  999. ui__error("%s", errbuf);
  1000. status = -saved_errno;
  1001. goto out_delete_evlist;
  1002. }
  1003. if (perf_target__none(target))
  1004. target->system_wide = true;
  1005. if (perf_evlist__create_maps(top.evlist, target) < 0)
  1006. usage_with_options(top_usage, options);
  1007. if (!top.evlist->nr_entries &&
  1008. perf_evlist__add_default(top.evlist) < 0) {
  1009. ui__error("Not enough memory for event selector list\n");
  1010. goto out_delete_maps;
  1011. }
  1012. symbol_conf.nr_events = top.evlist->nr_entries;
  1013. if (top.delay_secs < 1)
  1014. top.delay_secs = 1;
  1015. if (opts->user_interval != ULLONG_MAX)
  1016. opts->default_interval = opts->user_interval;
  1017. if (opts->user_freq != UINT_MAX)
  1018. opts->freq = opts->user_freq;
  1019. /*
  1020. * User specified count overrides default frequency.
  1021. */
  1022. if (opts->default_interval)
  1023. opts->freq = 0;
  1024. else if (opts->freq) {
  1025. opts->default_interval = opts->freq;
  1026. } else {
  1027. ui__error("frequency and count are zero, aborting\n");
  1028. status = -EINVAL;
  1029. goto out_delete_maps;
  1030. }
  1031. top.sym_evsel = perf_evlist__first(top.evlist);
  1032. symbol_conf.priv_size = sizeof(struct annotation);
  1033. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1034. if (symbol__init() < 0)
  1035. return -1;
  1036. sort__setup_elide(stdout);
  1037. get_term_dimensions(&top.winsize);
  1038. if (top.print_entries == 0) {
  1039. struct sigaction act = {
  1040. .sa_sigaction = perf_top__sig_winch,
  1041. .sa_flags = SA_SIGINFO,
  1042. };
  1043. perf_top__update_print_entries(&top);
  1044. sigaction(SIGWINCH, &act, NULL);
  1045. }
  1046. status = __cmd_top(&top);
  1047. out_delete_maps:
  1048. perf_evlist__delete_maps(top.evlist);
  1049. out_delete_evlist:
  1050. perf_evlist__delete(top.evlist);
  1051. return status;
  1052. }