builtin-top.c 29 KB

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