builtin-top.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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/session.h"
  23. #include "util/symbol.h"
  24. #include "util/thread.h"
  25. #include "util/util.h"
  26. #include <linux/rbtree.h>
  27. #include "util/parse-options.h"
  28. #include "util/parse-events.h"
  29. #include "util/debug.h"
  30. #include <assert.h>
  31. #include <fcntl.h>
  32. #include <stdio.h>
  33. #include <termios.h>
  34. #include <unistd.h>
  35. #include <errno.h>
  36. #include <time.h>
  37. #include <sched.h>
  38. #include <pthread.h>
  39. #include <sys/syscall.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/poll.h>
  42. #include <sys/prctl.h>
  43. #include <sys/wait.h>
  44. #include <sys/uio.h>
  45. #include <sys/mman.h>
  46. #include <linux/unistd.h>
  47. #include <linux/types.h>
  48. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  49. static int system_wide = 0;
  50. static int default_interval = 0;
  51. static int count_filter = 5;
  52. static int print_entries;
  53. static int target_pid = -1;
  54. static int inherit = 0;
  55. static int profile_cpu = -1;
  56. static int nr_cpus = 0;
  57. static unsigned int realtime_prio = 0;
  58. static int group = 0;
  59. static unsigned int page_size;
  60. static unsigned int mmap_pages = 16;
  61. static int freq = 1000; /* 1 KHz */
  62. static int delay_secs = 2;
  63. static int zero = 0;
  64. static int dump_symtab = 0;
  65. static bool hide_kernel_symbols = false;
  66. static bool hide_user_symbols = false;
  67. static struct winsize winsize;
  68. /*
  69. * Source
  70. */
  71. struct source_line {
  72. u64 eip;
  73. unsigned long count[MAX_COUNTERS];
  74. char *line;
  75. struct source_line *next;
  76. };
  77. static char *sym_filter = NULL;
  78. struct sym_entry *sym_filter_entry = NULL;
  79. struct sym_entry *sym_filter_entry_sched = NULL;
  80. static int sym_pcnt_filter = 5;
  81. static int sym_counter = 0;
  82. static int display_weighted = -1;
  83. /*
  84. * Symbols
  85. */
  86. struct sym_entry_source {
  87. struct source_line *source;
  88. struct source_line *lines;
  89. struct source_line **lines_tail;
  90. pthread_mutex_t lock;
  91. };
  92. struct sym_entry {
  93. struct rb_node rb_node;
  94. struct list_head node;
  95. unsigned long snap_count;
  96. double weight;
  97. int skip;
  98. u16 name_len;
  99. u8 origin;
  100. struct map *map;
  101. struct sym_entry_source *src;
  102. unsigned long count[0];
  103. };
  104. /*
  105. * Source functions
  106. */
  107. static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
  108. {
  109. return ((void *)self) + symbol_conf.priv_size;
  110. }
  111. static void get_term_dimensions(struct winsize *ws)
  112. {
  113. char *s = getenv("LINES");
  114. if (s != NULL) {
  115. ws->ws_row = atoi(s);
  116. s = getenv("COLUMNS");
  117. if (s != NULL) {
  118. ws->ws_col = atoi(s);
  119. if (ws->ws_row && ws->ws_col)
  120. return;
  121. }
  122. }
  123. #ifdef TIOCGWINSZ
  124. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  125. ws->ws_row && ws->ws_col)
  126. return;
  127. #endif
  128. ws->ws_row = 25;
  129. ws->ws_col = 80;
  130. }
  131. static void update_print_entries(struct winsize *ws)
  132. {
  133. print_entries = ws->ws_row;
  134. if (print_entries > 9)
  135. print_entries -= 9;
  136. }
  137. static void sig_winch_handler(int sig __used)
  138. {
  139. get_term_dimensions(&winsize);
  140. update_print_entries(&winsize);
  141. }
  142. static void parse_source(struct sym_entry *syme)
  143. {
  144. struct symbol *sym;
  145. struct sym_entry_source *source;
  146. struct map *map;
  147. FILE *file;
  148. char command[PATH_MAX*2];
  149. const char *path;
  150. u64 len;
  151. if (!syme)
  152. return;
  153. if (syme->src == NULL) {
  154. syme->src = zalloc(sizeof(*source));
  155. if (syme->src == NULL)
  156. return;
  157. pthread_mutex_init(&syme->src->lock, NULL);
  158. }
  159. source = syme->src;
  160. if (source->lines) {
  161. pthread_mutex_lock(&source->lock);
  162. goto out_assign;
  163. }
  164. sym = sym_entry__symbol(syme);
  165. map = syme->map;
  166. path = map->dso->long_name;
  167. len = sym->end - sym->start;
  168. sprintf(command,
  169. "objdump --start-address=%#0*Lx --stop-address=%#0*Lx -dS %s",
  170. BITS_PER_LONG / 4, map__rip_2objdump(map, sym->start),
  171. BITS_PER_LONG / 4, map__rip_2objdump(map, sym->end), path);
  172. file = popen(command, "r");
  173. if (!file)
  174. return;
  175. pthread_mutex_lock(&source->lock);
  176. source->lines_tail = &source->lines;
  177. while (!feof(file)) {
  178. struct source_line *src;
  179. size_t dummy = 0;
  180. char *c, *sep;
  181. src = malloc(sizeof(struct source_line));
  182. assert(src != NULL);
  183. memset(src, 0, sizeof(struct source_line));
  184. if (getline(&src->line, &dummy, file) < 0)
  185. break;
  186. if (!src->line)
  187. break;
  188. c = strchr(src->line, '\n');
  189. if (c)
  190. *c = 0;
  191. src->next = NULL;
  192. *source->lines_tail = src;
  193. source->lines_tail = &src->next;
  194. src->eip = strtoull(src->line, &sep, 16);
  195. if (*sep == ':')
  196. src->eip = map__objdump_2ip(map, src->eip);
  197. else /* this line has no ip info (e.g. source line) */
  198. src->eip = 0;
  199. }
  200. pclose(file);
  201. out_assign:
  202. sym_filter_entry = syme;
  203. pthread_mutex_unlock(&source->lock);
  204. }
  205. static void __zero_source_counters(struct sym_entry *syme)
  206. {
  207. int i;
  208. struct source_line *line;
  209. line = syme->src->lines;
  210. while (line) {
  211. for (i = 0; i < nr_counters; i++)
  212. line->count[i] = 0;
  213. line = line->next;
  214. }
  215. }
  216. static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
  217. {
  218. struct source_line *line;
  219. if (syme != sym_filter_entry)
  220. return;
  221. if (pthread_mutex_trylock(&syme->src->lock))
  222. return;
  223. if (syme->src == NULL || syme->src->source == NULL)
  224. goto out_unlock;
  225. for (line = syme->src->lines; line; line = line->next) {
  226. /* skip lines without IP info */
  227. if (line->eip == 0)
  228. continue;
  229. if (line->eip == ip) {
  230. line->count[counter]++;
  231. break;
  232. }
  233. if (line->eip > ip)
  234. break;
  235. }
  236. out_unlock:
  237. pthread_mutex_unlock(&syme->src->lock);
  238. }
  239. #define PATTERN_LEN (BITS_PER_LONG / 4 + 2)
  240. static void lookup_sym_source(struct sym_entry *syme)
  241. {
  242. struct symbol *symbol = sym_entry__symbol(syme);
  243. struct source_line *line;
  244. char pattern[PATTERN_LEN + 1];
  245. sprintf(pattern, "%0*Lx <", BITS_PER_LONG / 4,
  246. map__rip_2objdump(syme->map, symbol->start));
  247. pthread_mutex_lock(&syme->src->lock);
  248. for (line = syme->src->lines; line; line = line->next) {
  249. if (memcmp(line->line, pattern, PATTERN_LEN) == 0) {
  250. syme->src->source = line;
  251. break;
  252. }
  253. }
  254. pthread_mutex_unlock(&syme->src->lock);
  255. }
  256. static void show_lines(struct source_line *queue, int count, int total)
  257. {
  258. int i;
  259. struct source_line *line;
  260. line = queue;
  261. for (i = 0; i < count; i++) {
  262. float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
  263. printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
  264. line = line->next;
  265. }
  266. }
  267. #define TRACE_COUNT 3
  268. static void show_details(struct sym_entry *syme)
  269. {
  270. struct symbol *symbol;
  271. struct source_line *line;
  272. struct source_line *line_queue = NULL;
  273. int displayed = 0;
  274. int line_queue_count = 0, total = 0, more = 0;
  275. if (!syme)
  276. return;
  277. if (!syme->src->source)
  278. lookup_sym_source(syme);
  279. if (!syme->src->source)
  280. return;
  281. symbol = sym_entry__symbol(syme);
  282. printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
  283. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  284. pthread_mutex_lock(&syme->src->lock);
  285. line = syme->src->source;
  286. while (line) {
  287. total += line->count[sym_counter];
  288. line = line->next;
  289. }
  290. line = syme->src->source;
  291. while (line) {
  292. float pcnt = 0.0;
  293. if (!line_queue_count)
  294. line_queue = line;
  295. line_queue_count++;
  296. if (line->count[sym_counter])
  297. pcnt = 100.0 * line->count[sym_counter] / (float)total;
  298. if (pcnt >= (float)sym_pcnt_filter) {
  299. if (displayed <= print_entries)
  300. show_lines(line_queue, line_queue_count, total);
  301. else more++;
  302. displayed += line_queue_count;
  303. line_queue_count = 0;
  304. line_queue = NULL;
  305. } else if (line_queue_count > TRACE_COUNT) {
  306. line_queue = line_queue->next;
  307. line_queue_count--;
  308. }
  309. line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
  310. line = line->next;
  311. }
  312. pthread_mutex_unlock(&syme->src->lock);
  313. if (more)
  314. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  315. }
  316. /*
  317. * Symbols will be added here in event__process_sample and will get out
  318. * after decayed.
  319. */
  320. static LIST_HEAD(active_symbols);
  321. static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
  322. /*
  323. * Ordering weight: count-1 * count-2 * ... / count-n
  324. */
  325. static double sym_weight(const struct sym_entry *sym)
  326. {
  327. double weight = sym->snap_count;
  328. int counter;
  329. if (!display_weighted)
  330. return weight;
  331. for (counter = 1; counter < nr_counters-1; counter++)
  332. weight *= sym->count[counter];
  333. weight /= (sym->count[counter] + 1);
  334. return weight;
  335. }
  336. static long samples;
  337. static long userspace_samples;
  338. static const char CONSOLE_CLEAR[] = "";
  339. static void __list_insert_active_sym(struct sym_entry *syme)
  340. {
  341. list_add(&syme->node, &active_symbols);
  342. }
  343. static void list_remove_active_sym(struct sym_entry *syme)
  344. {
  345. pthread_mutex_lock(&active_symbols_lock);
  346. list_del_init(&syme->node);
  347. pthread_mutex_unlock(&active_symbols_lock);
  348. }
  349. static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
  350. {
  351. struct rb_node **p = &tree->rb_node;
  352. struct rb_node *parent = NULL;
  353. struct sym_entry *iter;
  354. while (*p != NULL) {
  355. parent = *p;
  356. iter = rb_entry(parent, struct sym_entry, rb_node);
  357. if (se->weight > iter->weight)
  358. p = &(*p)->rb_left;
  359. else
  360. p = &(*p)->rb_right;
  361. }
  362. rb_link_node(&se->rb_node, parent, p);
  363. rb_insert_color(&se->rb_node, tree);
  364. }
  365. static void print_sym_table(void)
  366. {
  367. int printed = 0, j;
  368. int counter, snap = !display_weighted ? sym_counter : 0;
  369. float samples_per_sec = samples/delay_secs;
  370. float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
  371. float sum_ksamples = 0.0;
  372. struct sym_entry *syme, *n;
  373. struct rb_root tmp = RB_ROOT;
  374. struct rb_node *nd;
  375. int sym_width = 0, dso_width = 0, max_dso_width;
  376. const int win_width = winsize.ws_col - 1;
  377. samples = userspace_samples = 0;
  378. /* Sort the active symbols */
  379. pthread_mutex_lock(&active_symbols_lock);
  380. syme = list_entry(active_symbols.next, struct sym_entry, node);
  381. pthread_mutex_unlock(&active_symbols_lock);
  382. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  383. syme->snap_count = syme->count[snap];
  384. if (syme->snap_count != 0) {
  385. if ((hide_user_symbols &&
  386. syme->origin == PERF_RECORD_MISC_USER) ||
  387. (hide_kernel_symbols &&
  388. syme->origin == PERF_RECORD_MISC_KERNEL)) {
  389. list_remove_active_sym(syme);
  390. continue;
  391. }
  392. syme->weight = sym_weight(syme);
  393. rb_insert_active_sym(&tmp, syme);
  394. sum_ksamples += syme->snap_count;
  395. for (j = 0; j < nr_counters; j++)
  396. syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
  397. } else
  398. list_remove_active_sym(syme);
  399. }
  400. puts(CONSOLE_CLEAR);
  401. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  402. printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% [",
  403. samples_per_sec,
  404. 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)));
  405. if (nr_counters == 1 || !display_weighted) {
  406. printf("%Ld", (u64)attrs[0].sample_period);
  407. if (freq)
  408. printf("Hz ");
  409. else
  410. printf(" ");
  411. }
  412. if (!display_weighted)
  413. printf("%s", event_name(sym_counter));
  414. else for (counter = 0; counter < nr_counters; counter++) {
  415. if (counter)
  416. printf("/");
  417. printf("%s", event_name(counter));
  418. }
  419. printf( "], ");
  420. if (target_pid != -1)
  421. printf(" (target_pid: %d", target_pid);
  422. else
  423. printf(" (all");
  424. if (profile_cpu != -1)
  425. printf(", cpu: %d)\n", profile_cpu);
  426. else {
  427. if (target_pid != -1)
  428. printf(")\n");
  429. else
  430. printf(", %d CPUs)\n", nr_cpus);
  431. }
  432. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  433. if (sym_filter_entry) {
  434. show_details(sym_filter_entry);
  435. return;
  436. }
  437. /*
  438. * Find the longest symbol name that will be displayed
  439. */
  440. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  441. syme = rb_entry(nd, struct sym_entry, rb_node);
  442. if (++printed > print_entries ||
  443. (int)syme->snap_count < count_filter)
  444. continue;
  445. if (syme->map->dso->long_name_len > dso_width)
  446. dso_width = syme->map->dso->long_name_len;
  447. if (syme->name_len > sym_width)
  448. sym_width = syme->name_len;
  449. }
  450. printed = 0;
  451. max_dso_width = winsize.ws_col - sym_width - 29;
  452. if (dso_width > max_dso_width)
  453. dso_width = max_dso_width;
  454. putchar('\n');
  455. if (nr_counters == 1)
  456. printf(" samples pcnt");
  457. else
  458. printf(" weight samples pcnt");
  459. if (verbose)
  460. printf(" RIP ");
  461. printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
  462. printf(" %s _______ _____",
  463. nr_counters == 1 ? " " : "______");
  464. if (verbose)
  465. printf(" ________________");
  466. printf(" %-*.*s", sym_width, sym_width, graph_line);
  467. printf(" %-*.*s", dso_width, dso_width, graph_line);
  468. puts("\n");
  469. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  470. struct symbol *sym;
  471. double pcnt;
  472. syme = rb_entry(nd, struct sym_entry, rb_node);
  473. sym = sym_entry__symbol(syme);
  474. if (++printed > print_entries || (int)syme->snap_count < count_filter)
  475. continue;
  476. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  477. sum_ksamples));
  478. if (nr_counters == 1 || !display_weighted)
  479. printf("%20.2f ", syme->weight);
  480. else
  481. printf("%9.1f %10ld ", syme->weight, syme->snap_count);
  482. percent_color_fprintf(stdout, "%4.1f%%", pcnt);
  483. if (verbose)
  484. printf(" %016llx", sym->start);
  485. printf(" %-*.*s", sym_width, sym_width, sym->name);
  486. printf(" %-*.*s\n", dso_width, dso_width,
  487. dso_width >= syme->map->dso->long_name_len ?
  488. syme->map->dso->long_name :
  489. syme->map->dso->short_name);
  490. }
  491. }
  492. static void prompt_integer(int *target, const char *msg)
  493. {
  494. char *buf = malloc(0), *p;
  495. size_t dummy = 0;
  496. int tmp;
  497. fprintf(stdout, "\n%s: ", msg);
  498. if (getline(&buf, &dummy, stdin) < 0)
  499. return;
  500. p = strchr(buf, '\n');
  501. if (p)
  502. *p = 0;
  503. p = buf;
  504. while(*p) {
  505. if (!isdigit(*p))
  506. goto out_free;
  507. p++;
  508. }
  509. tmp = strtoul(buf, NULL, 10);
  510. *target = tmp;
  511. out_free:
  512. free(buf);
  513. }
  514. static void prompt_percent(int *target, const char *msg)
  515. {
  516. int tmp = 0;
  517. prompt_integer(&tmp, msg);
  518. if (tmp >= 0 && tmp <= 100)
  519. *target = tmp;
  520. }
  521. static void prompt_symbol(struct sym_entry **target, const char *msg)
  522. {
  523. char *buf = malloc(0), *p;
  524. struct sym_entry *syme = *target, *n, *found = NULL;
  525. size_t dummy = 0;
  526. /* zero counters of active symbol */
  527. if (syme) {
  528. pthread_mutex_lock(&syme->src->lock);
  529. __zero_source_counters(syme);
  530. *target = NULL;
  531. pthread_mutex_unlock(&syme->src->lock);
  532. }
  533. fprintf(stdout, "\n%s: ", msg);
  534. if (getline(&buf, &dummy, stdin) < 0)
  535. goto out_free;
  536. p = strchr(buf, '\n');
  537. if (p)
  538. *p = 0;
  539. pthread_mutex_lock(&active_symbols_lock);
  540. syme = list_entry(active_symbols.next, struct sym_entry, node);
  541. pthread_mutex_unlock(&active_symbols_lock);
  542. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  543. struct symbol *sym = sym_entry__symbol(syme);
  544. if (!strcmp(buf, sym->name)) {
  545. found = syme;
  546. break;
  547. }
  548. }
  549. if (!found) {
  550. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  551. sleep(1);
  552. return;
  553. } else
  554. parse_source(found);
  555. out_free:
  556. free(buf);
  557. }
  558. static void print_mapped_keys(void)
  559. {
  560. char *name = NULL;
  561. if (sym_filter_entry) {
  562. struct symbol *sym = sym_entry__symbol(sym_filter_entry);
  563. name = sym->name;
  564. }
  565. fprintf(stdout, "\nMapped keys:\n");
  566. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
  567. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
  568. if (nr_counters > 1)
  569. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
  570. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
  571. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  572. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  573. fprintf(stdout, "\t[S] stop annotation.\n");
  574. if (nr_counters > 1)
  575. fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
  576. fprintf(stdout,
  577. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  578. hide_kernel_symbols ? "yes" : "no");
  579. fprintf(stdout,
  580. "\t[U] hide user symbols. \t(%s)\n",
  581. hide_user_symbols ? "yes" : "no");
  582. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
  583. fprintf(stdout, "\t[qQ] quit.\n");
  584. }
  585. static int key_mapped(int c)
  586. {
  587. switch (c) {
  588. case 'd':
  589. case 'e':
  590. case 'f':
  591. case 'z':
  592. case 'q':
  593. case 'Q':
  594. case 'K':
  595. case 'U':
  596. case 'F':
  597. case 's':
  598. case 'S':
  599. return 1;
  600. case 'E':
  601. case 'w':
  602. return nr_counters > 1 ? 1 : 0;
  603. default:
  604. break;
  605. }
  606. return 0;
  607. }
  608. static void handle_keypress(int c)
  609. {
  610. if (!key_mapped(c)) {
  611. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  612. struct termios tc, save;
  613. print_mapped_keys();
  614. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  615. fflush(stdout);
  616. tcgetattr(0, &save);
  617. tc = save;
  618. tc.c_lflag &= ~(ICANON | ECHO);
  619. tc.c_cc[VMIN] = 0;
  620. tc.c_cc[VTIME] = 0;
  621. tcsetattr(0, TCSANOW, &tc);
  622. poll(&stdin_poll, 1, -1);
  623. c = getc(stdin);
  624. tcsetattr(0, TCSAFLUSH, &save);
  625. if (!key_mapped(c))
  626. return;
  627. }
  628. switch (c) {
  629. case 'd':
  630. prompt_integer(&delay_secs, "Enter display delay");
  631. if (delay_secs < 1)
  632. delay_secs = 1;
  633. break;
  634. case 'e':
  635. prompt_integer(&print_entries, "Enter display entries (lines)");
  636. if (print_entries == 0) {
  637. sig_winch_handler(SIGWINCH);
  638. signal(SIGWINCH, sig_winch_handler);
  639. } else
  640. signal(SIGWINCH, SIG_DFL);
  641. break;
  642. case 'E':
  643. if (nr_counters > 1) {
  644. int i;
  645. fprintf(stderr, "\nAvailable events:");
  646. for (i = 0; i < nr_counters; i++)
  647. fprintf(stderr, "\n\t%d %s", i, event_name(i));
  648. prompt_integer(&sym_counter, "Enter details event counter");
  649. if (sym_counter >= nr_counters) {
  650. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
  651. sym_counter = 0;
  652. sleep(1);
  653. }
  654. } else sym_counter = 0;
  655. break;
  656. case 'f':
  657. prompt_integer(&count_filter, "Enter display event count filter");
  658. break;
  659. case 'F':
  660. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  661. break;
  662. case 'K':
  663. hide_kernel_symbols = !hide_kernel_symbols;
  664. break;
  665. case 'q':
  666. case 'Q':
  667. printf("exiting.\n");
  668. if (dump_symtab)
  669. dsos__fprintf(stderr);
  670. exit(0);
  671. case 's':
  672. prompt_symbol(&sym_filter_entry, "Enter details symbol");
  673. break;
  674. case 'S':
  675. if (!sym_filter_entry)
  676. break;
  677. else {
  678. struct sym_entry *syme = sym_filter_entry;
  679. pthread_mutex_lock(&syme->src->lock);
  680. sym_filter_entry = NULL;
  681. __zero_source_counters(syme);
  682. pthread_mutex_unlock(&syme->src->lock);
  683. }
  684. break;
  685. case 'U':
  686. hide_user_symbols = !hide_user_symbols;
  687. break;
  688. case 'w':
  689. display_weighted = ~display_weighted;
  690. break;
  691. case 'z':
  692. zero = ~zero;
  693. break;
  694. default:
  695. break;
  696. }
  697. }
  698. static void *display_thread(void *arg __used)
  699. {
  700. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  701. struct termios tc, save;
  702. int delay_msecs, c;
  703. tcgetattr(0, &save);
  704. tc = save;
  705. tc.c_lflag &= ~(ICANON | ECHO);
  706. tc.c_cc[VMIN] = 0;
  707. tc.c_cc[VTIME] = 0;
  708. repeat:
  709. delay_msecs = delay_secs * 1000;
  710. tcsetattr(0, TCSANOW, &tc);
  711. /* trash return*/
  712. getc(stdin);
  713. do {
  714. print_sym_table();
  715. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  716. c = getc(stdin);
  717. tcsetattr(0, TCSAFLUSH, &save);
  718. handle_keypress(c);
  719. goto repeat;
  720. return NULL;
  721. }
  722. /* Tag samples to be skipped. */
  723. static const char *skip_symbols[] = {
  724. "default_idle",
  725. "cpu_idle",
  726. "enter_idle",
  727. "exit_idle",
  728. "mwait_idle",
  729. "mwait_idle_with_hints",
  730. "poll_idle",
  731. "ppc64_runlatch_off",
  732. "pseries_dedicated_idle_sleep",
  733. NULL
  734. };
  735. static int symbol_filter(struct map *map, struct symbol *sym)
  736. {
  737. struct sym_entry *syme;
  738. const char *name = sym->name;
  739. int i;
  740. /*
  741. * ppc64 uses function descriptors and appends a '.' to the
  742. * start of every instruction address. Remove it.
  743. */
  744. if (name[0] == '.')
  745. name++;
  746. if (!strcmp(name, "_text") ||
  747. !strcmp(name, "_etext") ||
  748. !strcmp(name, "_sinittext") ||
  749. !strncmp("init_module", name, 11) ||
  750. !strncmp("cleanup_module", name, 14) ||
  751. strstr(name, "_text_start") ||
  752. strstr(name, "_text_end"))
  753. return 1;
  754. syme = symbol__priv(sym);
  755. syme->map = map;
  756. syme->src = NULL;
  757. if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
  758. /* schedule initial sym_filter_entry setup */
  759. sym_filter_entry_sched = syme;
  760. sym_filter = NULL;
  761. }
  762. for (i = 0; skip_symbols[i]; i++) {
  763. if (!strcmp(skip_symbols[i], name)) {
  764. syme->skip = 1;
  765. break;
  766. }
  767. }
  768. if (!syme->skip)
  769. syme->name_len = strlen(sym->name);
  770. return 0;
  771. }
  772. static void event__process_sample(const event_t *self,
  773. struct perf_session *session, int counter)
  774. {
  775. u64 ip = self->ip.ip;
  776. struct sym_entry *syme;
  777. struct addr_location al;
  778. u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  779. ++samples;
  780. switch (origin) {
  781. case PERF_RECORD_MISC_USER:
  782. ++userspace_samples;
  783. if (hide_user_symbols)
  784. return;
  785. break;
  786. case PERF_RECORD_MISC_KERNEL:
  787. if (hide_kernel_symbols)
  788. return;
  789. break;
  790. default:
  791. return;
  792. }
  793. if (event__preprocess_sample(self, session, &al, symbol_filter) < 0 ||
  794. al.filtered)
  795. return;
  796. if (al.sym == NULL) {
  797. /*
  798. * As we do lazy loading of symtabs we only will know if the
  799. * specified vmlinux file is invalid when we actually have a
  800. * hit in kernel space and then try to load it. So if we get
  801. * here and there are _no_ symbols in the DSO backing the
  802. * kernel map, bail out.
  803. *
  804. * We may never get here, for instance, if we use -K/
  805. * --hide-kernel-symbols, even if the user specifies an
  806. * invalid --vmlinux ;-)
  807. */
  808. if (al.map == session->vmlinux_maps[MAP__FUNCTION] &&
  809. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  810. pr_err("The %s file can't be used\n",
  811. symbol_conf.vmlinux_name);
  812. exit(1);
  813. }
  814. return;
  815. }
  816. /* let's see, whether we need to install initial sym_filter_entry */
  817. if (sym_filter_entry_sched) {
  818. sym_filter_entry = sym_filter_entry_sched;
  819. sym_filter_entry_sched = NULL;
  820. parse_source(sym_filter_entry);
  821. }
  822. syme = symbol__priv(al.sym);
  823. if (!syme->skip) {
  824. syme->count[counter]++;
  825. syme->origin = origin;
  826. record_precise_ip(syme, counter, ip);
  827. pthread_mutex_lock(&active_symbols_lock);
  828. if (list_empty(&syme->node) || !syme->node.next)
  829. __list_insert_active_sym(syme);
  830. pthread_mutex_unlock(&active_symbols_lock);
  831. }
  832. }
  833. static int event__process(event_t *event, struct perf_session *session)
  834. {
  835. switch (event->header.type) {
  836. case PERF_RECORD_COMM:
  837. event__process_comm(event, session);
  838. break;
  839. case PERF_RECORD_MMAP:
  840. event__process_mmap(event, session);
  841. break;
  842. case PERF_RECORD_FORK:
  843. case PERF_RECORD_EXIT:
  844. event__process_task(event, session);
  845. break;
  846. default:
  847. break;
  848. }
  849. return 0;
  850. }
  851. struct mmap_data {
  852. int counter;
  853. void *base;
  854. int mask;
  855. unsigned int prev;
  856. };
  857. static unsigned int mmap_read_head(struct mmap_data *md)
  858. {
  859. struct perf_event_mmap_page *pc = md->base;
  860. int head;
  861. head = pc->data_head;
  862. rmb();
  863. return head;
  864. }
  865. static void perf_session__mmap_read_counter(struct perf_session *self,
  866. struct mmap_data *md)
  867. {
  868. unsigned int head = mmap_read_head(md);
  869. unsigned int old = md->prev;
  870. unsigned char *data = md->base + page_size;
  871. int diff;
  872. /*
  873. * If we're further behind than half the buffer, there's a chance
  874. * the writer will bite our tail and mess up the samples under us.
  875. *
  876. * If we somehow ended up ahead of the head, we got messed up.
  877. *
  878. * In either case, truncate and restart at head.
  879. */
  880. diff = head - old;
  881. if (diff > md->mask / 2 || diff < 0) {
  882. fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
  883. /*
  884. * head points to a known good entry, start there.
  885. */
  886. old = head;
  887. }
  888. for (; old != head;) {
  889. event_t *event = (event_t *)&data[old & md->mask];
  890. event_t event_copy;
  891. size_t size = event->header.size;
  892. /*
  893. * Event straddles the mmap boundary -- header should always
  894. * be inside due to u64 alignment of output.
  895. */
  896. if ((old & md->mask) + size != ((old + size) & md->mask)) {
  897. unsigned int offset = old;
  898. unsigned int len = min(sizeof(*event), size), cpy;
  899. void *dst = &event_copy;
  900. do {
  901. cpy = min(md->mask + 1 - (offset & md->mask), len);
  902. memcpy(dst, &data[offset & md->mask], cpy);
  903. offset += cpy;
  904. dst += cpy;
  905. len -= cpy;
  906. } while (len);
  907. event = &event_copy;
  908. }
  909. if (event->header.type == PERF_RECORD_SAMPLE)
  910. event__process_sample(event, self, md->counter);
  911. else
  912. event__process(event, self);
  913. old += size;
  914. }
  915. md->prev = old;
  916. }
  917. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  918. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  919. static void perf_session__mmap_read(struct perf_session *self)
  920. {
  921. int i, counter;
  922. for (i = 0; i < nr_cpus; i++) {
  923. for (counter = 0; counter < nr_counters; counter++)
  924. perf_session__mmap_read_counter(self, &mmap_array[i][counter]);
  925. }
  926. }
  927. int nr_poll;
  928. int group_fd;
  929. static void start_counter(int i, int counter)
  930. {
  931. struct perf_event_attr *attr;
  932. int cpu;
  933. cpu = profile_cpu;
  934. if (target_pid == -1 && profile_cpu == -1)
  935. cpu = i;
  936. attr = attrs + counter;
  937. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  938. if (freq) {
  939. attr->sample_type |= PERF_SAMPLE_PERIOD;
  940. attr->freq = 1;
  941. attr->sample_freq = freq;
  942. }
  943. attr->inherit = (cpu < 0) && inherit;
  944. attr->mmap = 1;
  945. try_again:
  946. fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
  947. if (fd[i][counter] < 0) {
  948. int err = errno;
  949. if (err == EPERM || err == EACCES)
  950. die("No permission - are you root?\n");
  951. /*
  952. * If it's cycles then fall back to hrtimer
  953. * based cpu-clock-tick sw counter, which
  954. * is always available even if no PMU support:
  955. */
  956. if (attr->type == PERF_TYPE_HARDWARE
  957. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  958. if (verbose)
  959. warning(" ... trying to fall back to cpu-clock-ticks\n");
  960. attr->type = PERF_TYPE_SOFTWARE;
  961. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  962. goto try_again;
  963. }
  964. printf("\n");
  965. error("perfcounter syscall returned with %d (%s)\n",
  966. fd[i][counter], strerror(err));
  967. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  968. exit(-1);
  969. }
  970. assert(fd[i][counter] >= 0);
  971. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  972. /*
  973. * First counter acts as the group leader:
  974. */
  975. if (group && group_fd == -1)
  976. group_fd = fd[i][counter];
  977. event_array[nr_poll].fd = fd[i][counter];
  978. event_array[nr_poll].events = POLLIN;
  979. nr_poll++;
  980. mmap_array[i][counter].counter = counter;
  981. mmap_array[i][counter].prev = 0;
  982. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  983. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  984. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  985. if (mmap_array[i][counter].base == MAP_FAILED)
  986. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  987. }
  988. static int __cmd_top(void)
  989. {
  990. pthread_t thread;
  991. int i, counter;
  992. int ret;
  993. /*
  994. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  995. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  996. */
  997. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false);
  998. if (session == NULL)
  999. return -ENOMEM;
  1000. if (target_pid != -1)
  1001. event__synthesize_thread(target_pid, event__process, session);
  1002. else
  1003. event__synthesize_threads(event__process, session);
  1004. for (i = 0; i < nr_cpus; i++) {
  1005. group_fd = -1;
  1006. for (counter = 0; counter < nr_counters; counter++)
  1007. start_counter(i, counter);
  1008. }
  1009. /* Wait for a minimal set of events before starting the snapshot */
  1010. poll(event_array, nr_poll, 100);
  1011. perf_session__mmap_read(session);
  1012. if (pthread_create(&thread, NULL, display_thread, NULL)) {
  1013. printf("Could not create display thread.\n");
  1014. exit(-1);
  1015. }
  1016. if (realtime_prio) {
  1017. struct sched_param param;
  1018. param.sched_priority = realtime_prio;
  1019. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  1020. printf("Could not set realtime priority.\n");
  1021. exit(-1);
  1022. }
  1023. }
  1024. while (1) {
  1025. int hits = samples;
  1026. perf_session__mmap_read(session);
  1027. if (hits == samples)
  1028. ret = poll(event_array, nr_poll, 100);
  1029. }
  1030. return 0;
  1031. }
  1032. static const char * const top_usage[] = {
  1033. "perf top [<options>]",
  1034. NULL
  1035. };
  1036. static const struct option options[] = {
  1037. OPT_CALLBACK('e', "event", NULL, "event",
  1038. "event selector. use 'perf list' to list available events",
  1039. parse_events),
  1040. OPT_INTEGER('c', "count", &default_interval,
  1041. "event period to sample"),
  1042. OPT_INTEGER('p', "pid", &target_pid,
  1043. "profile events on existing pid"),
  1044. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  1045. "system-wide collection from all CPUs"),
  1046. OPT_INTEGER('C', "CPU", &profile_cpu,
  1047. "CPU to profile on"),
  1048. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  1049. "file", "vmlinux pathname"),
  1050. OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
  1051. "hide kernel symbols"),
  1052. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  1053. "number of mmap data pages"),
  1054. OPT_INTEGER('r', "realtime", &realtime_prio,
  1055. "collect data with this RT SCHED_FIFO priority"),
  1056. OPT_INTEGER('d', "delay", &delay_secs,
  1057. "number of seconds to delay between refreshes"),
  1058. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  1059. "dump the symbol table used for profiling"),
  1060. OPT_INTEGER('f', "count-filter", &count_filter,
  1061. "only display functions with more events than this"),
  1062. OPT_BOOLEAN('g', "group", &group,
  1063. "put the counters into a counter group"),
  1064. OPT_BOOLEAN('i', "inherit", &inherit,
  1065. "child tasks inherit counters"),
  1066. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  1067. "symbol to annotate"),
  1068. OPT_BOOLEAN('z', "zero", &zero,
  1069. "zero history across updates"),
  1070. OPT_INTEGER('F', "freq", &freq,
  1071. "profile at this frequency"),
  1072. OPT_INTEGER('E', "entries", &print_entries,
  1073. "display this many functions"),
  1074. OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
  1075. "hide user symbols"),
  1076. OPT_BOOLEAN('v', "verbose", &verbose,
  1077. "be more verbose (show counter open errors, etc)"),
  1078. OPT_END()
  1079. };
  1080. int cmd_top(int argc, const char **argv, const char *prefix __used)
  1081. {
  1082. int counter;
  1083. page_size = sysconf(_SC_PAGE_SIZE);
  1084. argc = parse_options(argc, argv, options, top_usage, 0);
  1085. if (argc)
  1086. usage_with_options(top_usage, options);
  1087. /* CPU and PID are mutually exclusive */
  1088. if (target_pid != -1 && profile_cpu != -1) {
  1089. printf("WARNING: PID switch overriding CPU\n");
  1090. sleep(1);
  1091. profile_cpu = -1;
  1092. }
  1093. if (!nr_counters)
  1094. nr_counters = 1;
  1095. symbol_conf.priv_size = (sizeof(struct sym_entry) +
  1096. (nr_counters + 1) * sizeof(unsigned long));
  1097. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1098. if (symbol__init() < 0)
  1099. return -1;
  1100. if (delay_secs < 1)
  1101. delay_secs = 1;
  1102. /*
  1103. * User specified count overrides default frequency.
  1104. */
  1105. if (default_interval)
  1106. freq = 0;
  1107. else if (freq) {
  1108. default_interval = freq;
  1109. } else {
  1110. fprintf(stderr, "frequency and count are zero, aborting\n");
  1111. exit(EXIT_FAILURE);
  1112. }
  1113. /*
  1114. * Fill in the ones not specifically initialized via -c:
  1115. */
  1116. for (counter = 0; counter < nr_counters; counter++) {
  1117. if (attrs[counter].sample_period)
  1118. continue;
  1119. attrs[counter].sample_period = default_interval;
  1120. }
  1121. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  1122. assert(nr_cpus <= MAX_NR_CPUS);
  1123. assert(nr_cpus >= 0);
  1124. if (target_pid != -1 || profile_cpu != -1)
  1125. nr_cpus = 1;
  1126. get_term_dimensions(&winsize);
  1127. if (print_entries == 0) {
  1128. update_print_entries(&winsize);
  1129. signal(SIGWINCH, sig_winch_handler);
  1130. }
  1131. return __cmd_top();
  1132. }