builtin-top.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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 long exact_samples;
  339. static const char CONSOLE_CLEAR[] = "";
  340. static void __list_insert_active_sym(struct sym_entry *syme)
  341. {
  342. list_add(&syme->node, &active_symbols);
  343. }
  344. static void list_remove_active_sym(struct sym_entry *syme)
  345. {
  346. pthread_mutex_lock(&active_symbols_lock);
  347. list_del_init(&syme->node);
  348. pthread_mutex_unlock(&active_symbols_lock);
  349. }
  350. static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
  351. {
  352. struct rb_node **p = &tree->rb_node;
  353. struct rb_node *parent = NULL;
  354. struct sym_entry *iter;
  355. while (*p != NULL) {
  356. parent = *p;
  357. iter = rb_entry(parent, struct sym_entry, rb_node);
  358. if (se->weight > iter->weight)
  359. p = &(*p)->rb_left;
  360. else
  361. p = &(*p)->rb_right;
  362. }
  363. rb_link_node(&se->rb_node, parent, p);
  364. rb_insert_color(&se->rb_node, tree);
  365. }
  366. static void print_sym_table(void)
  367. {
  368. int printed = 0, j;
  369. int counter, snap = !display_weighted ? sym_counter : 0;
  370. float samples_per_sec = samples/delay_secs;
  371. float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
  372. float esamples_percent = (100.0*exact_samples)/samples;
  373. float sum_ksamples = 0.0;
  374. struct sym_entry *syme, *n;
  375. struct rb_root tmp = RB_ROOT;
  376. struct rb_node *nd;
  377. int sym_width = 0, dso_width = 0, max_dso_width;
  378. const int win_width = winsize.ws_col - 1;
  379. samples = userspace_samples = exact_samples = 0;
  380. /* Sort the active symbols */
  381. pthread_mutex_lock(&active_symbols_lock);
  382. syme = list_entry(active_symbols.next, struct sym_entry, node);
  383. pthread_mutex_unlock(&active_symbols_lock);
  384. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  385. syme->snap_count = syme->count[snap];
  386. if (syme->snap_count != 0) {
  387. if ((hide_user_symbols &&
  388. syme->origin == PERF_RECORD_MISC_USER) ||
  389. (hide_kernel_symbols &&
  390. syme->origin == PERF_RECORD_MISC_KERNEL)) {
  391. list_remove_active_sym(syme);
  392. continue;
  393. }
  394. syme->weight = sym_weight(syme);
  395. rb_insert_active_sym(&tmp, syme);
  396. sum_ksamples += syme->snap_count;
  397. for (j = 0; j < nr_counters; j++)
  398. syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
  399. } else
  400. list_remove_active_sym(syme);
  401. }
  402. puts(CONSOLE_CLEAR);
  403. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  404. printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% exact: %4.1f%% [",
  405. samples_per_sec,
  406. 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)),
  407. esamples_percent);
  408. if (nr_counters == 1 || !display_weighted) {
  409. printf("%Ld", (u64)attrs[0].sample_period);
  410. if (freq)
  411. printf("Hz ");
  412. else
  413. printf(" ");
  414. }
  415. if (!display_weighted)
  416. printf("%s", event_name(sym_counter));
  417. else for (counter = 0; counter < nr_counters; counter++) {
  418. if (counter)
  419. printf("/");
  420. printf("%s", event_name(counter));
  421. }
  422. printf( "], ");
  423. if (target_pid != -1)
  424. printf(" (target_pid: %d", target_pid);
  425. else
  426. printf(" (all");
  427. if (profile_cpu != -1)
  428. printf(", cpu: %d)\n", profile_cpu);
  429. else {
  430. if (target_pid != -1)
  431. printf(")\n");
  432. else
  433. printf(", %d CPUs)\n", nr_cpus);
  434. }
  435. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  436. if (sym_filter_entry) {
  437. show_details(sym_filter_entry);
  438. return;
  439. }
  440. /*
  441. * Find the longest symbol name that will be displayed
  442. */
  443. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  444. syme = rb_entry(nd, struct sym_entry, rb_node);
  445. if (++printed > print_entries ||
  446. (int)syme->snap_count < count_filter)
  447. continue;
  448. if (syme->map->dso->long_name_len > dso_width)
  449. dso_width = syme->map->dso->long_name_len;
  450. if (syme->name_len > sym_width)
  451. sym_width = syme->name_len;
  452. }
  453. printed = 0;
  454. max_dso_width = winsize.ws_col - sym_width - 29;
  455. if (dso_width > max_dso_width)
  456. dso_width = max_dso_width;
  457. putchar('\n');
  458. if (nr_counters == 1)
  459. printf(" samples pcnt");
  460. else
  461. printf(" weight samples pcnt");
  462. if (verbose)
  463. printf(" RIP ");
  464. printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
  465. printf(" %s _______ _____",
  466. nr_counters == 1 ? " " : "______");
  467. if (verbose)
  468. printf(" ________________");
  469. printf(" %-*.*s", sym_width, sym_width, graph_line);
  470. printf(" %-*.*s", dso_width, dso_width, graph_line);
  471. puts("\n");
  472. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  473. struct symbol *sym;
  474. double pcnt;
  475. syme = rb_entry(nd, struct sym_entry, rb_node);
  476. sym = sym_entry__symbol(syme);
  477. if (++printed > print_entries || (int)syme->snap_count < count_filter)
  478. continue;
  479. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  480. sum_ksamples));
  481. if (nr_counters == 1 || !display_weighted)
  482. printf("%20.2f ", syme->weight);
  483. else
  484. printf("%9.1f %10ld ", syme->weight, syme->snap_count);
  485. percent_color_fprintf(stdout, "%4.1f%%", pcnt);
  486. if (verbose)
  487. printf(" %016llx", sym->start);
  488. printf(" %-*.*s", sym_width, sym_width, sym->name);
  489. printf(" %-*.*s\n", dso_width, dso_width,
  490. dso_width >= syme->map->dso->long_name_len ?
  491. syme->map->dso->long_name :
  492. syme->map->dso->short_name);
  493. }
  494. }
  495. static void prompt_integer(int *target, const char *msg)
  496. {
  497. char *buf = malloc(0), *p;
  498. size_t dummy = 0;
  499. int tmp;
  500. fprintf(stdout, "\n%s: ", msg);
  501. if (getline(&buf, &dummy, stdin) < 0)
  502. return;
  503. p = strchr(buf, '\n');
  504. if (p)
  505. *p = 0;
  506. p = buf;
  507. while(*p) {
  508. if (!isdigit(*p))
  509. goto out_free;
  510. p++;
  511. }
  512. tmp = strtoul(buf, NULL, 10);
  513. *target = tmp;
  514. out_free:
  515. free(buf);
  516. }
  517. static void prompt_percent(int *target, const char *msg)
  518. {
  519. int tmp = 0;
  520. prompt_integer(&tmp, msg);
  521. if (tmp >= 0 && tmp <= 100)
  522. *target = tmp;
  523. }
  524. static void prompt_symbol(struct sym_entry **target, const char *msg)
  525. {
  526. char *buf = malloc(0), *p;
  527. struct sym_entry *syme = *target, *n, *found = NULL;
  528. size_t dummy = 0;
  529. /* zero counters of active symbol */
  530. if (syme) {
  531. pthread_mutex_lock(&syme->src->lock);
  532. __zero_source_counters(syme);
  533. *target = NULL;
  534. pthread_mutex_unlock(&syme->src->lock);
  535. }
  536. fprintf(stdout, "\n%s: ", msg);
  537. if (getline(&buf, &dummy, stdin) < 0)
  538. goto out_free;
  539. p = strchr(buf, '\n');
  540. if (p)
  541. *p = 0;
  542. pthread_mutex_lock(&active_symbols_lock);
  543. syme = list_entry(active_symbols.next, struct sym_entry, node);
  544. pthread_mutex_unlock(&active_symbols_lock);
  545. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  546. struct symbol *sym = sym_entry__symbol(syme);
  547. if (!strcmp(buf, sym->name)) {
  548. found = syme;
  549. break;
  550. }
  551. }
  552. if (!found) {
  553. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  554. sleep(1);
  555. return;
  556. } else
  557. parse_source(found);
  558. out_free:
  559. free(buf);
  560. }
  561. static void print_mapped_keys(void)
  562. {
  563. char *name = NULL;
  564. if (sym_filter_entry) {
  565. struct symbol *sym = sym_entry__symbol(sym_filter_entry);
  566. name = sym->name;
  567. }
  568. fprintf(stdout, "\nMapped keys:\n");
  569. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
  570. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
  571. if (nr_counters > 1)
  572. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
  573. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
  574. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  575. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  576. fprintf(stdout, "\t[S] stop annotation.\n");
  577. if (nr_counters > 1)
  578. fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
  579. fprintf(stdout,
  580. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  581. hide_kernel_symbols ? "yes" : "no");
  582. fprintf(stdout,
  583. "\t[U] hide user symbols. \t(%s)\n",
  584. hide_user_symbols ? "yes" : "no");
  585. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
  586. fprintf(stdout, "\t[qQ] quit.\n");
  587. }
  588. static int key_mapped(int c)
  589. {
  590. switch (c) {
  591. case 'd':
  592. case 'e':
  593. case 'f':
  594. case 'z':
  595. case 'q':
  596. case 'Q':
  597. case 'K':
  598. case 'U':
  599. case 'F':
  600. case 's':
  601. case 'S':
  602. return 1;
  603. case 'E':
  604. case 'w':
  605. return nr_counters > 1 ? 1 : 0;
  606. default:
  607. break;
  608. }
  609. return 0;
  610. }
  611. static void handle_keypress(int c)
  612. {
  613. if (!key_mapped(c)) {
  614. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  615. struct termios tc, save;
  616. print_mapped_keys();
  617. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  618. fflush(stdout);
  619. tcgetattr(0, &save);
  620. tc = save;
  621. tc.c_lflag &= ~(ICANON | ECHO);
  622. tc.c_cc[VMIN] = 0;
  623. tc.c_cc[VTIME] = 0;
  624. tcsetattr(0, TCSANOW, &tc);
  625. poll(&stdin_poll, 1, -1);
  626. c = getc(stdin);
  627. tcsetattr(0, TCSAFLUSH, &save);
  628. if (!key_mapped(c))
  629. return;
  630. }
  631. switch (c) {
  632. case 'd':
  633. prompt_integer(&delay_secs, "Enter display delay");
  634. if (delay_secs < 1)
  635. delay_secs = 1;
  636. break;
  637. case 'e':
  638. prompt_integer(&print_entries, "Enter display entries (lines)");
  639. if (print_entries == 0) {
  640. sig_winch_handler(SIGWINCH);
  641. signal(SIGWINCH, sig_winch_handler);
  642. } else
  643. signal(SIGWINCH, SIG_DFL);
  644. break;
  645. case 'E':
  646. if (nr_counters > 1) {
  647. int i;
  648. fprintf(stderr, "\nAvailable events:");
  649. for (i = 0; i < nr_counters; i++)
  650. fprintf(stderr, "\n\t%d %s", i, event_name(i));
  651. prompt_integer(&sym_counter, "Enter details event counter");
  652. if (sym_counter >= nr_counters) {
  653. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
  654. sym_counter = 0;
  655. sleep(1);
  656. }
  657. } else sym_counter = 0;
  658. break;
  659. case 'f':
  660. prompt_integer(&count_filter, "Enter display event count filter");
  661. break;
  662. case 'F':
  663. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  664. break;
  665. case 'K':
  666. hide_kernel_symbols = !hide_kernel_symbols;
  667. break;
  668. case 'q':
  669. case 'Q':
  670. printf("exiting.\n");
  671. if (dump_symtab)
  672. dsos__fprintf(stderr);
  673. exit(0);
  674. case 's':
  675. prompt_symbol(&sym_filter_entry, "Enter details symbol");
  676. break;
  677. case 'S':
  678. if (!sym_filter_entry)
  679. break;
  680. else {
  681. struct sym_entry *syme = sym_filter_entry;
  682. pthread_mutex_lock(&syme->src->lock);
  683. sym_filter_entry = NULL;
  684. __zero_source_counters(syme);
  685. pthread_mutex_unlock(&syme->src->lock);
  686. }
  687. break;
  688. case 'U':
  689. hide_user_symbols = !hide_user_symbols;
  690. break;
  691. case 'w':
  692. display_weighted = ~display_weighted;
  693. break;
  694. case 'z':
  695. zero = ~zero;
  696. break;
  697. default:
  698. break;
  699. }
  700. }
  701. static void *display_thread(void *arg __used)
  702. {
  703. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  704. struct termios tc, save;
  705. int delay_msecs, c;
  706. tcgetattr(0, &save);
  707. tc = save;
  708. tc.c_lflag &= ~(ICANON | ECHO);
  709. tc.c_cc[VMIN] = 0;
  710. tc.c_cc[VTIME] = 0;
  711. repeat:
  712. delay_msecs = delay_secs * 1000;
  713. tcsetattr(0, TCSANOW, &tc);
  714. /* trash return*/
  715. getc(stdin);
  716. do {
  717. print_sym_table();
  718. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  719. c = getc(stdin);
  720. tcsetattr(0, TCSAFLUSH, &save);
  721. handle_keypress(c);
  722. goto repeat;
  723. return NULL;
  724. }
  725. /* Tag samples to be skipped. */
  726. static const char *skip_symbols[] = {
  727. "default_idle",
  728. "cpu_idle",
  729. "enter_idle",
  730. "exit_idle",
  731. "mwait_idle",
  732. "mwait_idle_with_hints",
  733. "poll_idle",
  734. "ppc64_runlatch_off",
  735. "pseries_dedicated_idle_sleep",
  736. NULL
  737. };
  738. static int symbol_filter(struct map *map, struct symbol *sym)
  739. {
  740. struct sym_entry *syme;
  741. const char *name = sym->name;
  742. int i;
  743. /*
  744. * ppc64 uses function descriptors and appends a '.' to the
  745. * start of every instruction address. Remove it.
  746. */
  747. if (name[0] == '.')
  748. name++;
  749. if (!strcmp(name, "_text") ||
  750. !strcmp(name, "_etext") ||
  751. !strcmp(name, "_sinittext") ||
  752. !strncmp("init_module", name, 11) ||
  753. !strncmp("cleanup_module", name, 14) ||
  754. strstr(name, "_text_start") ||
  755. strstr(name, "_text_end"))
  756. return 1;
  757. syme = symbol__priv(sym);
  758. syme->map = map;
  759. syme->src = NULL;
  760. if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
  761. /* schedule initial sym_filter_entry setup */
  762. sym_filter_entry_sched = syme;
  763. sym_filter = NULL;
  764. }
  765. for (i = 0; skip_symbols[i]; i++) {
  766. if (!strcmp(skip_symbols[i], name)) {
  767. syme->skip = 1;
  768. break;
  769. }
  770. }
  771. if (!syme->skip)
  772. syme->name_len = strlen(sym->name);
  773. return 0;
  774. }
  775. static void event__process_sample(const event_t *self,
  776. struct perf_session *session, int counter)
  777. {
  778. u64 ip = self->ip.ip;
  779. struct sym_entry *syme;
  780. struct addr_location al;
  781. u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  782. ++samples;
  783. switch (origin) {
  784. case PERF_RECORD_MISC_USER:
  785. ++userspace_samples;
  786. if (hide_user_symbols)
  787. return;
  788. break;
  789. case PERF_RECORD_MISC_KERNEL:
  790. if (hide_kernel_symbols)
  791. return;
  792. break;
  793. default:
  794. return;
  795. }
  796. if (self->header.misc & PERF_RECORD_MISC_EXACT)
  797. exact_samples++;
  798. if (event__preprocess_sample(self, session, &al, symbol_filter) < 0 ||
  799. al.filtered)
  800. return;
  801. if (al.sym == NULL) {
  802. /*
  803. * As we do lazy loading of symtabs we only will know if the
  804. * specified vmlinux file is invalid when we actually have a
  805. * hit in kernel space and then try to load it. So if we get
  806. * here and there are _no_ symbols in the DSO backing the
  807. * kernel map, bail out.
  808. *
  809. * We may never get here, for instance, if we use -K/
  810. * --hide-kernel-symbols, even if the user specifies an
  811. * invalid --vmlinux ;-)
  812. */
  813. if (al.map == session->vmlinux_maps[MAP__FUNCTION] &&
  814. RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
  815. pr_err("The %s file can't be used\n",
  816. symbol_conf.vmlinux_name);
  817. exit(1);
  818. }
  819. return;
  820. }
  821. /* let's see, whether we need to install initial sym_filter_entry */
  822. if (sym_filter_entry_sched) {
  823. sym_filter_entry = sym_filter_entry_sched;
  824. sym_filter_entry_sched = NULL;
  825. parse_source(sym_filter_entry);
  826. }
  827. syme = symbol__priv(al.sym);
  828. if (!syme->skip) {
  829. syme->count[counter]++;
  830. syme->origin = origin;
  831. record_precise_ip(syme, counter, ip);
  832. pthread_mutex_lock(&active_symbols_lock);
  833. if (list_empty(&syme->node) || !syme->node.next)
  834. __list_insert_active_sym(syme);
  835. pthread_mutex_unlock(&active_symbols_lock);
  836. }
  837. }
  838. static int event__process(event_t *event, struct perf_session *session)
  839. {
  840. switch (event->header.type) {
  841. case PERF_RECORD_COMM:
  842. event__process_comm(event, session);
  843. break;
  844. case PERF_RECORD_MMAP:
  845. event__process_mmap(event, session);
  846. break;
  847. case PERF_RECORD_FORK:
  848. case PERF_RECORD_EXIT:
  849. event__process_task(event, session);
  850. break;
  851. default:
  852. break;
  853. }
  854. return 0;
  855. }
  856. struct mmap_data {
  857. int counter;
  858. void *base;
  859. int mask;
  860. unsigned int prev;
  861. };
  862. static unsigned int mmap_read_head(struct mmap_data *md)
  863. {
  864. struct perf_event_mmap_page *pc = md->base;
  865. int head;
  866. head = pc->data_head;
  867. rmb();
  868. return head;
  869. }
  870. static void perf_session__mmap_read_counter(struct perf_session *self,
  871. struct mmap_data *md)
  872. {
  873. unsigned int head = mmap_read_head(md);
  874. unsigned int old = md->prev;
  875. unsigned char *data = md->base + page_size;
  876. int diff;
  877. /*
  878. * If we're further behind than half the buffer, there's a chance
  879. * the writer will bite our tail and mess up the samples under us.
  880. *
  881. * If we somehow ended up ahead of the head, we got messed up.
  882. *
  883. * In either case, truncate and restart at head.
  884. */
  885. diff = head - old;
  886. if (diff > md->mask / 2 || diff < 0) {
  887. fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
  888. /*
  889. * head points to a known good entry, start there.
  890. */
  891. old = head;
  892. }
  893. for (; old != head;) {
  894. event_t *event = (event_t *)&data[old & md->mask];
  895. event_t event_copy;
  896. size_t size = event->header.size;
  897. /*
  898. * Event straddles the mmap boundary -- header should always
  899. * be inside due to u64 alignment of output.
  900. */
  901. if ((old & md->mask) + size != ((old + size) & md->mask)) {
  902. unsigned int offset = old;
  903. unsigned int len = min(sizeof(*event), size), cpy;
  904. void *dst = &event_copy;
  905. do {
  906. cpy = min(md->mask + 1 - (offset & md->mask), len);
  907. memcpy(dst, &data[offset & md->mask], cpy);
  908. offset += cpy;
  909. dst += cpy;
  910. len -= cpy;
  911. } while (len);
  912. event = &event_copy;
  913. }
  914. if (event->header.type == PERF_RECORD_SAMPLE)
  915. event__process_sample(event, self, md->counter);
  916. else
  917. event__process(event, self);
  918. old += size;
  919. }
  920. md->prev = old;
  921. }
  922. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  923. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  924. static void perf_session__mmap_read(struct perf_session *self)
  925. {
  926. int i, counter;
  927. for (i = 0; i < nr_cpus; i++) {
  928. for (counter = 0; counter < nr_counters; counter++)
  929. perf_session__mmap_read_counter(self, &mmap_array[i][counter]);
  930. }
  931. }
  932. int nr_poll;
  933. int group_fd;
  934. static void start_counter(int i, int counter)
  935. {
  936. struct perf_event_attr *attr;
  937. int cpu;
  938. cpu = profile_cpu;
  939. if (target_pid == -1 && profile_cpu == -1)
  940. cpu = i;
  941. attr = attrs + counter;
  942. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  943. if (freq) {
  944. attr->sample_type |= PERF_SAMPLE_PERIOD;
  945. attr->freq = 1;
  946. attr->sample_freq = freq;
  947. }
  948. attr->inherit = (cpu < 0) && inherit;
  949. attr->mmap = 1;
  950. try_again:
  951. fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
  952. if (fd[i][counter] < 0) {
  953. int err = errno;
  954. if (err == EPERM || err == EACCES)
  955. die("No permission - are you root?\n");
  956. /*
  957. * If it's cycles then fall back to hrtimer
  958. * based cpu-clock-tick sw counter, which
  959. * is always available even if no PMU support:
  960. */
  961. if (attr->type == PERF_TYPE_HARDWARE
  962. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  963. if (verbose)
  964. warning(" ... trying to fall back to cpu-clock-ticks\n");
  965. attr->type = PERF_TYPE_SOFTWARE;
  966. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  967. goto try_again;
  968. }
  969. printf("\n");
  970. error("perfcounter syscall returned with %d (%s)\n",
  971. fd[i][counter], strerror(err));
  972. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  973. exit(-1);
  974. }
  975. assert(fd[i][counter] >= 0);
  976. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  977. /*
  978. * First counter acts as the group leader:
  979. */
  980. if (group && group_fd == -1)
  981. group_fd = fd[i][counter];
  982. event_array[nr_poll].fd = fd[i][counter];
  983. event_array[nr_poll].events = POLLIN;
  984. nr_poll++;
  985. mmap_array[i][counter].counter = counter;
  986. mmap_array[i][counter].prev = 0;
  987. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  988. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  989. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  990. if (mmap_array[i][counter].base == MAP_FAILED)
  991. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  992. }
  993. static int __cmd_top(void)
  994. {
  995. pthread_t thread;
  996. int i, counter;
  997. int ret;
  998. /*
  999. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  1000. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  1001. */
  1002. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false);
  1003. if (session == NULL)
  1004. return -ENOMEM;
  1005. if (target_pid != -1)
  1006. event__synthesize_thread(target_pid, event__process, session);
  1007. else
  1008. event__synthesize_threads(event__process, session);
  1009. for (i = 0; i < nr_cpus; i++) {
  1010. group_fd = -1;
  1011. for (counter = 0; counter < nr_counters; counter++)
  1012. start_counter(i, counter);
  1013. }
  1014. /* Wait for a minimal set of events before starting the snapshot */
  1015. poll(event_array, nr_poll, 100);
  1016. perf_session__mmap_read(session);
  1017. if (pthread_create(&thread, NULL, display_thread, NULL)) {
  1018. printf("Could not create display thread.\n");
  1019. exit(-1);
  1020. }
  1021. if (realtime_prio) {
  1022. struct sched_param param;
  1023. param.sched_priority = realtime_prio;
  1024. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  1025. printf("Could not set realtime priority.\n");
  1026. exit(-1);
  1027. }
  1028. }
  1029. while (1) {
  1030. int hits = samples;
  1031. perf_session__mmap_read(session);
  1032. if (hits == samples)
  1033. ret = poll(event_array, nr_poll, 100);
  1034. }
  1035. return 0;
  1036. }
  1037. static const char * const top_usage[] = {
  1038. "perf top [<options>]",
  1039. NULL
  1040. };
  1041. static const struct option options[] = {
  1042. OPT_CALLBACK('e', "event", NULL, "event",
  1043. "event selector. use 'perf list' to list available events",
  1044. parse_events),
  1045. OPT_INTEGER('c', "count", &default_interval,
  1046. "event period to sample"),
  1047. OPT_INTEGER('p', "pid", &target_pid,
  1048. "profile events on existing pid"),
  1049. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  1050. "system-wide collection from all CPUs"),
  1051. OPT_INTEGER('C', "CPU", &profile_cpu,
  1052. "CPU to profile on"),
  1053. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  1054. "file", "vmlinux pathname"),
  1055. OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
  1056. "hide kernel symbols"),
  1057. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  1058. "number of mmap data pages"),
  1059. OPT_INTEGER('r', "realtime", &realtime_prio,
  1060. "collect data with this RT SCHED_FIFO priority"),
  1061. OPT_INTEGER('d', "delay", &delay_secs,
  1062. "number of seconds to delay between refreshes"),
  1063. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  1064. "dump the symbol table used for profiling"),
  1065. OPT_INTEGER('f', "count-filter", &count_filter,
  1066. "only display functions with more events than this"),
  1067. OPT_BOOLEAN('g', "group", &group,
  1068. "put the counters into a counter group"),
  1069. OPT_BOOLEAN('i', "inherit", &inherit,
  1070. "child tasks inherit counters"),
  1071. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  1072. "symbol to annotate"),
  1073. OPT_BOOLEAN('z', "zero", &zero,
  1074. "zero history across updates"),
  1075. OPT_INTEGER('F', "freq", &freq,
  1076. "profile at this frequency"),
  1077. OPT_INTEGER('E', "entries", &print_entries,
  1078. "display this many functions"),
  1079. OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
  1080. "hide user symbols"),
  1081. OPT_BOOLEAN('v', "verbose", &verbose,
  1082. "be more verbose (show counter open errors, etc)"),
  1083. OPT_END()
  1084. };
  1085. int cmd_top(int argc, const char **argv, const char *prefix __used)
  1086. {
  1087. int counter;
  1088. page_size = sysconf(_SC_PAGE_SIZE);
  1089. argc = parse_options(argc, argv, options, top_usage, 0);
  1090. if (argc)
  1091. usage_with_options(top_usage, options);
  1092. /* CPU and PID are mutually exclusive */
  1093. if (target_pid != -1 && profile_cpu != -1) {
  1094. printf("WARNING: PID switch overriding CPU\n");
  1095. sleep(1);
  1096. profile_cpu = -1;
  1097. }
  1098. if (!nr_counters)
  1099. nr_counters = 1;
  1100. symbol_conf.priv_size = (sizeof(struct sym_entry) +
  1101. (nr_counters + 1) * sizeof(unsigned long));
  1102. symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
  1103. if (symbol__init() < 0)
  1104. return -1;
  1105. if (delay_secs < 1)
  1106. delay_secs = 1;
  1107. /*
  1108. * User specified count overrides default frequency.
  1109. */
  1110. if (default_interval)
  1111. freq = 0;
  1112. else if (freq) {
  1113. default_interval = freq;
  1114. } else {
  1115. fprintf(stderr, "frequency and count are zero, aborting\n");
  1116. exit(EXIT_FAILURE);
  1117. }
  1118. /*
  1119. * Fill in the ones not specifically initialized via -c:
  1120. */
  1121. for (counter = 0; counter < nr_counters; counter++) {
  1122. if (attrs[counter].sample_period)
  1123. continue;
  1124. attrs[counter].sample_period = default_interval;
  1125. }
  1126. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  1127. assert(nr_cpus <= MAX_NR_CPUS);
  1128. assert(nr_cpus >= 0);
  1129. if (target_pid != -1 || profile_cpu != -1)
  1130. nr_cpus = 1;
  1131. get_term_dimensions(&winsize);
  1132. if (print_entries == 0) {
  1133. update_print_entries(&winsize);
  1134. signal(SIGWINCH, sig_winch_handler);
  1135. }
  1136. return __cmd_top();
  1137. }