builtin-top.c 30 KB

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