builtin-top.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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. static void lookup_sym_source(struct sym_entry *syme)
  240. {
  241. struct symbol *symbol = sym_entry__symbol(syme);
  242. struct source_line *line;
  243. const size_t pattern_len = BITS_PER_LONG / 4 + 2;
  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. }