builtin-top.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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. *
  9. * Improvements and fixes by:
  10. *
  11. * Arjan van de Ven <arjan@linux.intel.com>
  12. * Yanmin Zhang <yanmin.zhang@intel.com>
  13. * Wu Fengguang <fengguang.wu@intel.com>
  14. * Mike Galbraith <efault@gmx.de>
  15. * Paul Mackerras <paulus@samba.org>
  16. *
  17. * Released under the GPL v2. (and only v2, not any later version)
  18. */
  19. #include "builtin.h"
  20. #include "perf.h"
  21. #include "util/color.h"
  22. #include "util/evlist.h"
  23. #include "util/evsel.h"
  24. #include "util/session.h"
  25. #include "util/symbol.h"
  26. #include "util/thread.h"
  27. #include "util/thread_map.h"
  28. #include "util/top.h"
  29. #include "util/util.h"
  30. #include <linux/rbtree.h>
  31. #include "util/parse-options.h"
  32. #include "util/parse-events.h"
  33. #include "util/cpumap.h"
  34. #include "util/xyarray.h"
  35. #include "util/debug.h"
  36. #include <assert.h>
  37. #include <fcntl.h>
  38. #include <stdio.h>
  39. #include <termios.h>
  40. #include <unistd.h>
  41. #include <inttypes.h>
  42. #include <errno.h>
  43. #include <time.h>
  44. #include <sched.h>
  45. #include <sys/syscall.h>
  46. #include <sys/ioctl.h>
  47. #include <sys/poll.h>
  48. #include <sys/prctl.h>
  49. #include <sys/wait.h>
  50. #include <sys/uio.h>
  51. #include <sys/mman.h>
  52. #include <linux/unistd.h>
  53. #include <linux/types.h>
  54. #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
  55. static struct perf_top top = {
  56. .count_filter = 5,
  57. .delay_secs = 2,
  58. .display_weighted = -1,
  59. .target_pid = -1,
  60. .target_tid = -1,
  61. .active_symbols = LIST_HEAD_INIT(top.active_symbols),
  62. .active_symbols_lock = PTHREAD_MUTEX_INITIALIZER,
  63. .freq = 1000, /* 1 KHz */
  64. };
  65. static bool system_wide = false;
  66. static int default_interval = 0;
  67. static bool inherit = false;
  68. static int realtime_prio = 0;
  69. static bool group = false;
  70. static unsigned int page_size;
  71. static unsigned int mmap_pages = 128;
  72. static bool dump_symtab = false;
  73. static struct winsize winsize;
  74. static const char *sym_filter = NULL;
  75. struct sym_entry *sym_filter_entry = NULL;
  76. struct sym_entry *sym_filter_entry_sched = NULL;
  77. static int sym_pcnt_filter = 5;
  78. /*
  79. * Source functions
  80. */
  81. static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
  82. {
  83. return ((void *)self) + symbol_conf.priv_size;
  84. }
  85. void get_term_dimensions(struct winsize *ws)
  86. {
  87. char *s = getenv("LINES");
  88. if (s != NULL) {
  89. ws->ws_row = atoi(s);
  90. s = getenv("COLUMNS");
  91. if (s != NULL) {
  92. ws->ws_col = atoi(s);
  93. if (ws->ws_row && ws->ws_col)
  94. return;
  95. }
  96. }
  97. #ifdef TIOCGWINSZ
  98. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  99. ws->ws_row && ws->ws_col)
  100. return;
  101. #endif
  102. ws->ws_row = 25;
  103. ws->ws_col = 80;
  104. }
  105. static void update_print_entries(struct winsize *ws)
  106. {
  107. top.print_entries = ws->ws_row;
  108. if (top.print_entries > 9)
  109. top.print_entries -= 9;
  110. }
  111. static void sig_winch_handler(int sig __used)
  112. {
  113. get_term_dimensions(&winsize);
  114. update_print_entries(&winsize);
  115. }
  116. static int parse_source(struct sym_entry *syme)
  117. {
  118. struct symbol *sym;
  119. struct sym_entry_source *source;
  120. struct map *map;
  121. FILE *file;
  122. char command[PATH_MAX*2];
  123. const char *path;
  124. u64 len;
  125. if (!syme)
  126. return -1;
  127. sym = sym_entry__symbol(syme);
  128. map = syme->map;
  129. /*
  130. * We can't annotate with just /proc/kallsyms
  131. */
  132. if (map->dso->origin == DSO__ORIG_KERNEL)
  133. return -1;
  134. if (syme->src == NULL) {
  135. syme->src = zalloc(sizeof(*source));
  136. if (syme->src == NULL)
  137. return -1;
  138. pthread_mutex_init(&syme->src->lock, NULL);
  139. }
  140. source = syme->src;
  141. if (source->lines) {
  142. pthread_mutex_lock(&source->lock);
  143. goto out_assign;
  144. }
  145. path = map->dso->long_name;
  146. len = sym->end - sym->start;
  147. sprintf(command,
  148. "objdump --start-address=%#0*" PRIx64 " --stop-address=%#0*" PRIx64 " -dS %s",
  149. BITS_PER_LONG / 4, map__rip_2objdump(map, sym->start),
  150. BITS_PER_LONG / 4, map__rip_2objdump(map, sym->end), path);
  151. file = popen(command, "r");
  152. if (!file)
  153. return -1;
  154. pthread_mutex_lock(&source->lock);
  155. source->lines_tail = &source->lines;
  156. while (!feof(file)) {
  157. struct source_line *src;
  158. size_t dummy = 0;
  159. char *c, *sep;
  160. src = malloc(sizeof(struct source_line));
  161. assert(src != NULL);
  162. memset(src, 0, sizeof(struct source_line));
  163. if (getline(&src->line, &dummy, file) < 0)
  164. break;
  165. if (!src->line)
  166. break;
  167. c = strchr(src->line, '\n');
  168. if (c)
  169. *c = 0;
  170. src->next = NULL;
  171. *source->lines_tail = src;
  172. source->lines_tail = &src->next;
  173. src->eip = strtoull(src->line, &sep, 16);
  174. if (*sep == ':')
  175. src->eip = map__objdump_2ip(map, src->eip);
  176. else /* this line has no ip info (e.g. source line) */
  177. src->eip = 0;
  178. }
  179. pclose(file);
  180. out_assign:
  181. sym_filter_entry = syme;
  182. pthread_mutex_unlock(&source->lock);
  183. return 0;
  184. }
  185. static void __zero_source_counters(struct sym_entry *syme)
  186. {
  187. int i;
  188. struct source_line *line;
  189. line = syme->src->lines;
  190. while (line) {
  191. for (i = 0; i < top.evlist->nr_entries; i++)
  192. line->count[i] = 0;
  193. line = line->next;
  194. }
  195. }
  196. static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
  197. {
  198. struct source_line *line;
  199. if (syme != sym_filter_entry)
  200. return;
  201. if (pthread_mutex_trylock(&syme->src->lock))
  202. return;
  203. if (syme->src == NULL || syme->src->source == NULL)
  204. goto out_unlock;
  205. for (line = syme->src->lines; line; line = line->next) {
  206. /* skip lines without IP info */
  207. if (line->eip == 0)
  208. continue;
  209. if (line->eip == ip) {
  210. line->count[counter]++;
  211. break;
  212. }
  213. if (line->eip > ip)
  214. break;
  215. }
  216. out_unlock:
  217. pthread_mutex_unlock(&syme->src->lock);
  218. }
  219. #define PATTERN_LEN (BITS_PER_LONG / 4 + 2)
  220. static void lookup_sym_source(struct sym_entry *syme)
  221. {
  222. struct symbol *symbol = sym_entry__symbol(syme);
  223. struct source_line *line;
  224. char pattern[PATTERN_LEN + 1];
  225. sprintf(pattern, "%0*" PRIx64 " <", BITS_PER_LONG / 4,
  226. map__rip_2objdump(syme->map, symbol->start));
  227. pthread_mutex_lock(&syme->src->lock);
  228. for (line = syme->src->lines; line; line = line->next) {
  229. if (memcmp(line->line, pattern, PATTERN_LEN) == 0) {
  230. syme->src->source = line;
  231. break;
  232. }
  233. }
  234. pthread_mutex_unlock(&syme->src->lock);
  235. }
  236. static void show_lines(struct source_line *queue, int count, int total)
  237. {
  238. int i;
  239. struct source_line *line;
  240. line = queue;
  241. for (i = 0; i < count; i++) {
  242. float pcnt = 100.0*(float)line->count[top.sym_counter]/(float)total;
  243. printf("%8li %4.1f%%\t%s\n", line->count[top.sym_counter], pcnt, line->line);
  244. line = line->next;
  245. }
  246. }
  247. #define TRACE_COUNT 3
  248. static void show_details(struct sym_entry *syme)
  249. {
  250. struct symbol *symbol;
  251. struct source_line *line;
  252. struct source_line *line_queue = NULL;
  253. int displayed = 0;
  254. int line_queue_count = 0, total = 0, more = 0;
  255. if (!syme)
  256. return;
  257. if (!syme->src->source)
  258. lookup_sym_source(syme);
  259. if (!syme->src->source)
  260. return;
  261. symbol = sym_entry__symbol(syme);
  262. printf("Showing %s for %s\n", event_name(top.sym_evsel), symbol->name);
  263. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  264. pthread_mutex_lock(&syme->src->lock);
  265. line = syme->src->source;
  266. while (line) {
  267. total += line->count[top.sym_counter];
  268. line = line->next;
  269. }
  270. line = syme->src->source;
  271. while (line) {
  272. float pcnt = 0.0;
  273. if (!line_queue_count)
  274. line_queue = line;
  275. line_queue_count++;
  276. if (line->count[top.sym_counter])
  277. pcnt = 100.0 * line->count[top.sym_counter] / (float)total;
  278. if (pcnt >= (float)sym_pcnt_filter) {
  279. if (displayed <= top.print_entries)
  280. show_lines(line_queue, line_queue_count, total);
  281. else more++;
  282. displayed += line_queue_count;
  283. line_queue_count = 0;
  284. line_queue = NULL;
  285. } else if (line_queue_count > TRACE_COUNT) {
  286. line_queue = line_queue->next;
  287. line_queue_count--;
  288. }
  289. line->count[top.sym_counter] = top.zero ? 0 : line->count[top.sym_counter] * 7 / 8;
  290. line = line->next;
  291. }
  292. pthread_mutex_unlock(&syme->src->lock);
  293. if (more)
  294. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  295. }
  296. static const char CONSOLE_CLEAR[] = "";
  297. static void __list_insert_active_sym(struct sym_entry *syme)
  298. {
  299. list_add(&syme->node, &top.active_symbols);
  300. }
  301. static void print_sym_table(struct perf_session *session)
  302. {
  303. char bf[160];
  304. int printed = 0;
  305. struct rb_node *nd;
  306. struct sym_entry *syme;
  307. struct rb_root tmp = RB_ROOT;
  308. const int win_width = winsize.ws_col - 1;
  309. int sym_width, dso_width, dso_short_width;
  310. float sum_ksamples = perf_top__decay_samples(&top, &tmp);
  311. puts(CONSOLE_CLEAR);
  312. perf_top__header_snprintf(&top, bf, sizeof(bf));
  313. printf("%s\n", bf);
  314. perf_top__reset_sample_counters(&top);
  315. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  316. if (session->hists.stats.total_lost != 0) {
  317. color_fprintf(stdout, PERF_COLOR_RED, "WARNING:");
  318. printf(" LOST %" PRIu64 " events, Check IO/CPU overload\n",
  319. session->hists.stats.total_lost);
  320. }
  321. if (sym_filter_entry) {
  322. show_details(sym_filter_entry);
  323. return;
  324. }
  325. perf_top__find_widths(&top, &tmp, &dso_width, &dso_short_width,
  326. &sym_width);
  327. if (sym_width + dso_width > winsize.ws_col - 29) {
  328. dso_width = dso_short_width;
  329. if (sym_width + dso_width > winsize.ws_col - 29)
  330. sym_width = winsize.ws_col - dso_width - 29;
  331. }
  332. putchar('\n');
  333. if (top.evlist->nr_entries == 1)
  334. printf(" samples pcnt");
  335. else
  336. printf(" weight samples pcnt");
  337. if (verbose)
  338. printf(" RIP ");
  339. printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
  340. printf(" %s _______ _____",
  341. top.evlist->nr_entries == 1 ? " " : "______");
  342. if (verbose)
  343. printf(" ________________");
  344. printf(" %-*.*s", sym_width, sym_width, graph_line);
  345. printf(" %-*.*s", dso_width, dso_width, graph_line);
  346. puts("\n");
  347. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  348. struct symbol *sym;
  349. double pcnt;
  350. syme = rb_entry(nd, struct sym_entry, rb_node);
  351. sym = sym_entry__symbol(syme);
  352. if (++printed > top.print_entries ||
  353. (int)syme->snap_count < top.count_filter)
  354. continue;
  355. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  356. sum_ksamples));
  357. if (top.evlist->nr_entries == 1 || !top.display_weighted)
  358. printf("%20.2f ", syme->weight);
  359. else
  360. printf("%9.1f %10ld ", syme->weight, syme->snap_count);
  361. percent_color_fprintf(stdout, "%4.1f%%", pcnt);
  362. if (verbose)
  363. printf(" %016" PRIx64, sym->start);
  364. printf(" %-*.*s", sym_width, sym_width, sym->name);
  365. printf(" %-*.*s\n", dso_width, dso_width,
  366. dso_width >= syme->map->dso->long_name_len ?
  367. syme->map->dso->long_name :
  368. syme->map->dso->short_name);
  369. }
  370. }
  371. static void prompt_integer(int *target, const char *msg)
  372. {
  373. char *buf = malloc(0), *p;
  374. size_t dummy = 0;
  375. int tmp;
  376. fprintf(stdout, "\n%s: ", msg);
  377. if (getline(&buf, &dummy, stdin) < 0)
  378. return;
  379. p = strchr(buf, '\n');
  380. if (p)
  381. *p = 0;
  382. p = buf;
  383. while(*p) {
  384. if (!isdigit(*p))
  385. goto out_free;
  386. p++;
  387. }
  388. tmp = strtoul(buf, NULL, 10);
  389. *target = tmp;
  390. out_free:
  391. free(buf);
  392. }
  393. static void prompt_percent(int *target, const char *msg)
  394. {
  395. int tmp = 0;
  396. prompt_integer(&tmp, msg);
  397. if (tmp >= 0 && tmp <= 100)
  398. *target = tmp;
  399. }
  400. static void prompt_symbol(struct sym_entry **target, const char *msg)
  401. {
  402. char *buf = malloc(0), *p;
  403. struct sym_entry *syme = *target, *n, *found = NULL;
  404. size_t dummy = 0;
  405. /* zero counters of active symbol */
  406. if (syme) {
  407. pthread_mutex_lock(&syme->src->lock);
  408. __zero_source_counters(syme);
  409. *target = NULL;
  410. pthread_mutex_unlock(&syme->src->lock);
  411. }
  412. fprintf(stdout, "\n%s: ", msg);
  413. if (getline(&buf, &dummy, stdin) < 0)
  414. goto out_free;
  415. p = strchr(buf, '\n');
  416. if (p)
  417. *p = 0;
  418. pthread_mutex_lock(&top.active_symbols_lock);
  419. syme = list_entry(top.active_symbols.next, struct sym_entry, node);
  420. pthread_mutex_unlock(&top.active_symbols_lock);
  421. list_for_each_entry_safe_from(syme, n, &top.active_symbols, node) {
  422. struct symbol *sym = sym_entry__symbol(syme);
  423. if (!strcmp(buf, sym->name)) {
  424. found = syme;
  425. break;
  426. }
  427. }
  428. if (!found) {
  429. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  430. sleep(1);
  431. return;
  432. } else
  433. parse_source(found);
  434. out_free:
  435. free(buf);
  436. }
  437. static void print_mapped_keys(void)
  438. {
  439. char *name = NULL;
  440. if (sym_filter_entry) {
  441. struct symbol *sym = sym_entry__symbol(sym_filter_entry);
  442. name = sym->name;
  443. }
  444. fprintf(stdout, "\nMapped keys:\n");
  445. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", top.delay_secs);
  446. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", top.print_entries);
  447. if (top.evlist->nr_entries > 1)
  448. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(top.sym_evsel));
  449. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", top.count_filter);
  450. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  451. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  452. fprintf(stdout, "\t[S] stop annotation.\n");
  453. if (top.evlist->nr_entries > 1)
  454. fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", top.display_weighted ? 1 : 0);
  455. fprintf(stdout,
  456. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  457. top.hide_kernel_symbols ? "yes" : "no");
  458. fprintf(stdout,
  459. "\t[U] hide user symbols. \t(%s)\n",
  460. top.hide_user_symbols ? "yes" : "no");
  461. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", top.zero ? 1 : 0);
  462. fprintf(stdout, "\t[qQ] quit.\n");
  463. }
  464. static int key_mapped(int c)
  465. {
  466. switch (c) {
  467. case 'd':
  468. case 'e':
  469. case 'f':
  470. case 'z':
  471. case 'q':
  472. case 'Q':
  473. case 'K':
  474. case 'U':
  475. case 'F':
  476. case 's':
  477. case 'S':
  478. return 1;
  479. case 'E':
  480. case 'w':
  481. return top.evlist->nr_entries > 1 ? 1 : 0;
  482. default:
  483. break;
  484. }
  485. return 0;
  486. }
  487. static void handle_keypress(struct perf_session *session, int c)
  488. {
  489. if (!key_mapped(c)) {
  490. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  491. struct termios tc, save;
  492. print_mapped_keys();
  493. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  494. fflush(stdout);
  495. tcgetattr(0, &save);
  496. tc = save;
  497. tc.c_lflag &= ~(ICANON | ECHO);
  498. tc.c_cc[VMIN] = 0;
  499. tc.c_cc[VTIME] = 0;
  500. tcsetattr(0, TCSANOW, &tc);
  501. poll(&stdin_poll, 1, -1);
  502. c = getc(stdin);
  503. tcsetattr(0, TCSAFLUSH, &save);
  504. if (!key_mapped(c))
  505. return;
  506. }
  507. switch (c) {
  508. case 'd':
  509. prompt_integer(&top.delay_secs, "Enter display delay");
  510. if (top.delay_secs < 1)
  511. top.delay_secs = 1;
  512. break;
  513. case 'e':
  514. prompt_integer(&top.print_entries, "Enter display entries (lines)");
  515. if (top.print_entries == 0) {
  516. sig_winch_handler(SIGWINCH);
  517. signal(SIGWINCH, sig_winch_handler);
  518. } else
  519. signal(SIGWINCH, SIG_DFL);
  520. break;
  521. case 'E':
  522. if (top.evlist->nr_entries > 1) {
  523. fprintf(stderr, "\nAvailable events:");
  524. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  525. fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
  526. prompt_integer(&top.sym_counter, "Enter details event counter");
  527. if (top.sym_counter >= top.evlist->nr_entries) {
  528. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  529. top.sym_counter = 0;
  530. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
  531. sleep(1);
  532. break;
  533. }
  534. list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
  535. if (top.sym_evsel->idx == top.sym_counter)
  536. break;
  537. } else top.sym_counter = 0;
  538. break;
  539. case 'f':
  540. prompt_integer(&top.count_filter, "Enter display event count filter");
  541. break;
  542. case 'F':
  543. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  544. break;
  545. case 'K':
  546. top.hide_kernel_symbols = !top.hide_kernel_symbols;
  547. break;
  548. case 'q':
  549. case 'Q':
  550. printf("exiting.\n");
  551. if (dump_symtab)
  552. perf_session__fprintf_dsos(session, stderr);
  553. exit(0);
  554. case 's':
  555. prompt_symbol(&sym_filter_entry, "Enter details symbol");
  556. break;
  557. case 'S':
  558. if (!sym_filter_entry)
  559. break;
  560. else {
  561. struct sym_entry *syme = sym_filter_entry;
  562. pthread_mutex_lock(&syme->src->lock);
  563. sym_filter_entry = NULL;
  564. __zero_source_counters(syme);
  565. pthread_mutex_unlock(&syme->src->lock);
  566. }
  567. break;
  568. case 'U':
  569. top.hide_user_symbols = !top.hide_user_symbols;
  570. break;
  571. case 'w':
  572. top.display_weighted = ~top.display_weighted;
  573. break;
  574. case 'z':
  575. top.zero = !top.zero;
  576. break;
  577. default:
  578. break;
  579. }
  580. }
  581. static void *display_thread(void *arg __used)
  582. {
  583. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  584. struct termios tc, save;
  585. int delay_msecs, c;
  586. struct perf_session *session = (struct perf_session *) arg;
  587. tcgetattr(0, &save);
  588. tc = save;
  589. tc.c_lflag &= ~(ICANON | ECHO);
  590. tc.c_cc[VMIN] = 0;
  591. tc.c_cc[VTIME] = 0;
  592. repeat:
  593. delay_msecs = top.delay_secs * 1000;
  594. tcsetattr(0, TCSANOW, &tc);
  595. /* trash return*/
  596. getc(stdin);
  597. do {
  598. print_sym_table(session);
  599. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  600. c = getc(stdin);
  601. tcsetattr(0, TCSAFLUSH, &save);
  602. handle_keypress(session, c);
  603. goto repeat;
  604. return NULL;
  605. }
  606. /* Tag samples to be skipped. */
  607. static const char *skip_symbols[] = {
  608. "default_idle",
  609. "native_safe_halt",
  610. "cpu_idle",
  611. "enter_idle",
  612. "exit_idle",
  613. "mwait_idle",
  614. "mwait_idle_with_hints",
  615. "poll_idle",
  616. "ppc64_runlatch_off",
  617. "pseries_dedicated_idle_sleep",
  618. NULL
  619. };
  620. static int symbol_filter(struct map *map, struct symbol *sym)
  621. {
  622. struct sym_entry *syme;
  623. const char *name = sym->name;
  624. int i;
  625. /*
  626. * ppc64 uses function descriptors and appends a '.' to the
  627. * start of every instruction address. Remove it.
  628. */
  629. if (name[0] == '.')
  630. name++;
  631. if (!strcmp(name, "_text") ||
  632. !strcmp(name, "_etext") ||
  633. !strcmp(name, "_sinittext") ||
  634. !strncmp("init_module", name, 11) ||
  635. !strncmp("cleanup_module", name, 14) ||
  636. strstr(name, "_text_start") ||
  637. strstr(name, "_text_end"))
  638. return 1;
  639. syme = symbol__priv(sym);
  640. syme->map = map;
  641. syme->src = NULL;
  642. if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
  643. /* schedule initial sym_filter_entry setup */
  644. sym_filter_entry_sched = syme;
  645. sym_filter = NULL;
  646. }
  647. for (i = 0; skip_symbols[i]; i++) {
  648. if (!strcmp(skip_symbols[i], name)) {
  649. syme->skip = 1;
  650. break;
  651. }
  652. }
  653. if (!syme->skip)
  654. syme->name_len = strlen(sym->name);
  655. return 0;
  656. }
  657. static void perf_event__process_sample(const union perf_event *event,
  658. struct perf_sample *sample,
  659. struct perf_session *session)
  660. {
  661. u64 ip = event->ip.ip;
  662. struct sym_entry *syme;
  663. struct addr_location al;
  664. struct machine *machine;
  665. u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  666. ++top.samples;
  667. switch (origin) {
  668. case PERF_RECORD_MISC_USER:
  669. ++top.us_samples;
  670. if (top.hide_user_symbols)
  671. return;
  672. machine = perf_session__find_host_machine(session);
  673. break;
  674. case PERF_RECORD_MISC_KERNEL:
  675. ++top.kernel_samples;
  676. if (top.hide_kernel_symbols)
  677. return;
  678. machine = perf_session__find_host_machine(session);
  679. break;
  680. case PERF_RECORD_MISC_GUEST_KERNEL:
  681. ++top.guest_kernel_samples;
  682. machine = perf_session__find_machine(session, event->ip.pid);
  683. break;
  684. case PERF_RECORD_MISC_GUEST_USER:
  685. ++top.guest_us_samples;
  686. /*
  687. * TODO: we don't process guest user from host side
  688. * except simple counting.
  689. */
  690. return;
  691. default:
  692. return;
  693. }
  694. if (!machine && perf_guest) {
  695. pr_err("Can't find guest [%d]'s kernel information\n",
  696. event->ip.pid);
  697. return;
  698. }
  699. if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
  700. top.exact_samples++;
  701. if (perf_event__preprocess_sample(event, session, &al, sample,
  702. symbol_filter) < 0 ||
  703. al.filtered)
  704. return;
  705. if (al.sym == NULL) {
  706. /*
  707. * As we do lazy loading of symtabs we only will know if the
  708. * specified vmlinux file is invalid when we actually have a
  709. * hit in kernel space and then try to load it. So if we get
  710. * here and there are _no_ symbols in the DSO backing the
  711. * kernel map, bail out.
  712. *
  713. * We may never get here, for instance, if we use -K/
  714. * --hide-kernel-symbols, even if the user specifies an
  715. * invalid --vmlinux ;-)
  716. */
  717. if (al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
  718. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  719. pr_err("The %s file can't be used\n",
  720. symbol_conf.vmlinux_name);
  721. exit(1);
  722. }
  723. return;
  724. }
  725. /* let's see, whether we need to install initial sym_filter_entry */
  726. if (sym_filter_entry_sched) {
  727. sym_filter_entry = sym_filter_entry_sched;
  728. sym_filter_entry_sched = NULL;
  729. if (parse_source(sym_filter_entry) < 0) {
  730. struct symbol *sym = sym_entry__symbol(sym_filter_entry);
  731. pr_err("Can't annotate %s", sym->name);
  732. if (sym_filter_entry->map->dso->origin == DSO__ORIG_KERNEL) {
  733. pr_err(": No vmlinux file was found in the path:\n");
  734. machine__fprintf_vmlinux_path(machine, stderr);
  735. } else
  736. pr_err(".\n");
  737. exit(1);
  738. }
  739. }
  740. syme = symbol__priv(al.sym);
  741. if (!syme->skip) {
  742. struct perf_evsel *evsel;
  743. syme->origin = origin;
  744. evsel = perf_evlist__id2evsel(top.evlist, sample->id);
  745. assert(evsel != NULL);
  746. syme->count[evsel->idx]++;
  747. record_precise_ip(syme, evsel->idx, ip);
  748. pthread_mutex_lock(&top.active_symbols_lock);
  749. if (list_empty(&syme->node) || !syme->node.next)
  750. __list_insert_active_sym(syme);
  751. pthread_mutex_unlock(&top.active_symbols_lock);
  752. }
  753. }
  754. static void perf_session__mmap_read_cpu(struct perf_session *self, int cpu)
  755. {
  756. struct perf_sample sample;
  757. union perf_event *event;
  758. while ((event = perf_evlist__read_on_cpu(top.evlist, cpu)) != NULL) {
  759. perf_session__parse_sample(self, event, &sample);
  760. if (event->header.type == PERF_RECORD_SAMPLE)
  761. perf_event__process_sample(event, &sample, self);
  762. else
  763. perf_event__process(event, &sample, self);
  764. }
  765. }
  766. static void perf_session__mmap_read(struct perf_session *self)
  767. {
  768. int i;
  769. for (i = 0; i < top.evlist->cpus->nr; i++)
  770. perf_session__mmap_read_cpu(self, i);
  771. }
  772. static void start_counters(struct perf_evlist *evlist)
  773. {
  774. struct perf_evsel *counter;
  775. list_for_each_entry(counter, &evlist->entries, node) {
  776. struct perf_event_attr *attr = &counter->attr;
  777. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  778. if (top.freq) {
  779. attr->sample_type |= PERF_SAMPLE_PERIOD;
  780. attr->freq = 1;
  781. attr->sample_freq = top.freq;
  782. }
  783. if (evlist->nr_entries > 1) {
  784. attr->sample_type |= PERF_SAMPLE_ID;
  785. attr->read_format |= PERF_FORMAT_ID;
  786. }
  787. attr->mmap = 1;
  788. try_again:
  789. if (perf_evsel__open(counter, top.evlist->cpus,
  790. top.evlist->threads, group, inherit) < 0) {
  791. int err = errno;
  792. if (err == EPERM || err == EACCES)
  793. die("Permission error - are you root?\n"
  794. "\t Consider tweaking"
  795. " /proc/sys/kernel/perf_event_paranoid.\n");
  796. /*
  797. * If it's cycles then fall back to hrtimer
  798. * based cpu-clock-tick sw counter, which
  799. * is always available even if no PMU support:
  800. */
  801. if (attr->type == PERF_TYPE_HARDWARE &&
  802. attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  803. if (verbose)
  804. warning(" ... trying to fall back to cpu-clock-ticks\n");
  805. attr->type = PERF_TYPE_SOFTWARE;
  806. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  807. goto try_again;
  808. }
  809. printf("\n");
  810. error("sys_perf_event_open() syscall returned with %d "
  811. "(%s). /bin/dmesg may provide additional information.\n",
  812. err, strerror(err));
  813. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  814. exit(-1);
  815. }
  816. }
  817. if (perf_evlist__mmap(evlist, mmap_pages, false) < 0)
  818. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  819. }
  820. static int __cmd_top(void)
  821. {
  822. pthread_t thread;
  823. struct perf_evsel *first;
  824. int ret;
  825. /*
  826. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  827. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  828. */
  829. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
  830. if (session == NULL)
  831. return -ENOMEM;
  832. if (top.target_tid != -1)
  833. perf_event__synthesize_thread(top.target_tid, perf_event__process,
  834. session);
  835. else
  836. perf_event__synthesize_threads(perf_event__process, session);
  837. start_counters(top.evlist);
  838. first = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  839. perf_session__set_sample_type(session, first->attr.sample_type);
  840. /* Wait for a minimal set of events before starting the snapshot */
  841. poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  842. perf_session__mmap_read(session);
  843. if (pthread_create(&thread, NULL, display_thread, session)) {
  844. printf("Could not create display thread.\n");
  845. exit(-1);
  846. }
  847. if (realtime_prio) {
  848. struct sched_param param;
  849. param.sched_priority = realtime_prio;
  850. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  851. printf("Could not set realtime priority.\n");
  852. exit(-1);
  853. }
  854. }
  855. while (1) {
  856. u64 hits = top.samples;
  857. perf_session__mmap_read(session);
  858. if (hits == top.samples)
  859. ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
  860. }
  861. return 0;
  862. }
  863. static const char * const top_usage[] = {
  864. "perf top [<options>]",
  865. NULL
  866. };
  867. static const struct option options[] = {
  868. OPT_CALLBACK('e', "event", &top.evlist, "event",
  869. "event selector. use 'perf list' to list available events",
  870. parse_events),
  871. OPT_INTEGER('c', "count", &default_interval,
  872. "event period to sample"),
  873. OPT_INTEGER('p', "pid", &top.target_pid,
  874. "profile events on existing process id"),
  875. OPT_INTEGER('t', "tid", &top.target_tid,
  876. "profile events on existing thread id"),
  877. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  878. "system-wide collection from all CPUs"),
  879. OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
  880. "list of cpus to monitor"),
  881. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  882. "file", "vmlinux pathname"),
  883. OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
  884. "hide kernel symbols"),
  885. OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
  886. OPT_INTEGER('r', "realtime", &realtime_prio,
  887. "collect data with this RT SCHED_FIFO priority"),
  888. OPT_INTEGER('d', "delay", &top.delay_secs,
  889. "number of seconds to delay between refreshes"),
  890. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  891. "dump the symbol table used for profiling"),
  892. OPT_INTEGER('f', "count-filter", &top.count_filter,
  893. "only display functions with more events than this"),
  894. OPT_BOOLEAN('g', "group", &group,
  895. "put the counters into a counter group"),
  896. OPT_BOOLEAN('i', "inherit", &inherit,
  897. "child tasks inherit counters"),
  898. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  899. "symbol to annotate"),
  900. OPT_BOOLEAN('z', "zero", &top.zero,
  901. "zero history across updates"),
  902. OPT_INTEGER('F', "freq", &top.freq,
  903. "profile at this frequency"),
  904. OPT_INTEGER('E', "entries", &top.print_entries,
  905. "display this many functions"),
  906. OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
  907. "hide user symbols"),
  908. OPT_INCR('v', "verbose", &verbose,
  909. "be more verbose (show counter open errors, etc)"),
  910. OPT_END()
  911. };
  912. int cmd_top(int argc, const char **argv, const char *prefix __used)
  913. {
  914. struct perf_evsel *pos;
  915. int status = -ENOMEM;
  916. top.evlist = perf_evlist__new(NULL, NULL);
  917. if (top.evlist == NULL)
  918. return -ENOMEM;
  919. page_size = sysconf(_SC_PAGE_SIZE);
  920. argc = parse_options(argc, argv, options, top_usage, 0);
  921. if (argc)
  922. usage_with_options(top_usage, options);
  923. /* CPU and PID are mutually exclusive */
  924. if (top.target_tid > 0 && top.cpu_list) {
  925. printf("WARNING: PID switch overriding CPU\n");
  926. sleep(1);
  927. top.cpu_list = NULL;
  928. }
  929. if (top.target_pid != -1)
  930. top.target_tid = top.target_pid;
  931. if (perf_evlist__create_maps(top.evlist, top.target_pid,
  932. top.target_tid, top.cpu_list) < 0)
  933. usage_with_options(top_usage, options);
  934. if (!top.evlist->nr_entries &&
  935. perf_evlist__add_default(top.evlist) < 0) {
  936. pr_err("Not enough memory for event selector list\n");
  937. return -ENOMEM;
  938. }
  939. if (top.delay_secs < 1)
  940. top.delay_secs = 1;
  941. /*
  942. * User specified count overrides default frequency.
  943. */
  944. if (default_interval)
  945. top.freq = 0;
  946. else if (top.freq) {
  947. default_interval = top.freq;
  948. } else {
  949. fprintf(stderr, "frequency and count are zero, aborting\n");
  950. exit(EXIT_FAILURE);
  951. }
  952. list_for_each_entry(pos, &top.evlist->entries, node) {
  953. if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
  954. top.evlist->threads->nr) < 0)
  955. goto out_free_fd;
  956. /*
  957. * Fill in the ones not specifically initialized via -c:
  958. */
  959. if (pos->attr.sample_period)
  960. continue;
  961. pos->attr.sample_period = default_interval;
  962. }
  963. if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
  964. perf_evlist__alloc_mmap(top.evlist) < 0)
  965. goto out_free_fd;
  966. top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
  967. symbol_conf.priv_size = (sizeof(struct sym_entry) +
  968. (top.evlist->nr_entries + 1) * sizeof(unsigned long));
  969. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  970. if (symbol__init() < 0)
  971. return -1;
  972. get_term_dimensions(&winsize);
  973. if (top.print_entries == 0) {
  974. update_print_entries(&winsize);
  975. signal(SIGWINCH, sig_winch_handler);
  976. }
  977. status = __cmd_top();
  978. out_free_fd:
  979. perf_evlist__delete(top.evlist);
  980. return status;
  981. }