builtin-top.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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/cpumap.h"
  30. #include "util/debug.h"
  31. #include <assert.h>
  32. #include <fcntl.h>
  33. #include <stdio.h>
  34. #include <termios.h>
  35. #include <unistd.h>
  36. #include <errno.h>
  37. #include <time.h>
  38. #include <sched.h>
  39. #include <pthread.h>
  40. #include <sys/syscall.h>
  41. #include <sys/ioctl.h>
  42. #include <sys/poll.h>
  43. #include <sys/prctl.h>
  44. #include <sys/wait.h>
  45. #include <sys/uio.h>
  46. #include <sys/mman.h>
  47. #include <linux/unistd.h>
  48. #include <linux/types.h>
  49. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  50. static int system_wide = 0;
  51. static int default_interval = 0;
  52. static int count_filter = 5;
  53. static int print_entries;
  54. static int target_pid = -1;
  55. static int inherit = 0;
  56. static int profile_cpu = -1;
  57. static int nr_cpus = 0;
  58. static unsigned int realtime_prio = 0;
  59. static int group = 0;
  60. static unsigned int page_size;
  61. static unsigned int mmap_pages = 16;
  62. static int freq = 1000; /* 1 KHz */
  63. static int delay_secs = 2;
  64. static int zero = 0;
  65. static int dump_symtab = 0;
  66. static bool hide_kernel_symbols = false;
  67. static bool hide_user_symbols = false;
  68. static struct winsize winsize;
  69. /*
  70. * Source
  71. */
  72. struct source_line {
  73. u64 eip;
  74. unsigned long count[MAX_COUNTERS];
  75. char *line;
  76. struct source_line *next;
  77. };
  78. static char *sym_filter = NULL;
  79. struct sym_entry *sym_filter_entry = NULL;
  80. struct sym_entry *sym_filter_entry_sched = NULL;
  81. static int sym_pcnt_filter = 5;
  82. static int sym_counter = 0;
  83. static int display_weighted = -1;
  84. /*
  85. * Symbols
  86. */
  87. struct sym_entry_source {
  88. struct source_line *source;
  89. struct source_line *lines;
  90. struct source_line **lines_tail;
  91. pthread_mutex_t lock;
  92. };
  93. struct sym_entry {
  94. struct rb_node rb_node;
  95. struct list_head node;
  96. unsigned long snap_count;
  97. double weight;
  98. int skip;
  99. u16 name_len;
  100. u8 origin;
  101. struct map *map;
  102. struct sym_entry_source *src;
  103. unsigned long count[0];
  104. };
  105. /*
  106. * Source functions
  107. */
  108. static inline struct symbol *sym_entry__symbol(struct sym_entry *self)
  109. {
  110. return ((void *)self) + symbol_conf.priv_size;
  111. }
  112. static void get_term_dimensions(struct winsize *ws)
  113. {
  114. char *s = getenv("LINES");
  115. if (s != NULL) {
  116. ws->ws_row = atoi(s);
  117. s = getenv("COLUMNS");
  118. if (s != NULL) {
  119. ws->ws_col = atoi(s);
  120. if (ws->ws_row && ws->ws_col)
  121. return;
  122. }
  123. }
  124. #ifdef TIOCGWINSZ
  125. if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
  126. ws->ws_row && ws->ws_col)
  127. return;
  128. #endif
  129. ws->ws_row = 25;
  130. ws->ws_col = 80;
  131. }
  132. static void update_print_entries(struct winsize *ws)
  133. {
  134. print_entries = ws->ws_row;
  135. if (print_entries > 9)
  136. print_entries -= 9;
  137. }
  138. static void sig_winch_handler(int sig __used)
  139. {
  140. get_term_dimensions(&winsize);
  141. update_print_entries(&winsize);
  142. }
  143. static void parse_source(struct sym_entry *syme)
  144. {
  145. struct symbol *sym;
  146. struct sym_entry_source *source;
  147. struct map *map;
  148. FILE *file;
  149. char command[PATH_MAX*2];
  150. const char *path;
  151. u64 len;
  152. if (!syme)
  153. return;
  154. if (syme->src == NULL) {
  155. syme->src = zalloc(sizeof(*source));
  156. if (syme->src == NULL)
  157. return;
  158. pthread_mutex_init(&syme->src->lock, NULL);
  159. }
  160. source = syme->src;
  161. if (source->lines) {
  162. pthread_mutex_lock(&source->lock);
  163. goto out_assign;
  164. }
  165. sym = sym_entry__symbol(syme);
  166. map = syme->map;
  167. path = map->dso->long_name;
  168. len = sym->end - sym->start;
  169. sprintf(command,
  170. "objdump --start-address=%#0*Lx --stop-address=%#0*Lx -dS %s",
  171. BITS_PER_LONG / 4, map__rip_2objdump(map, sym->start),
  172. BITS_PER_LONG / 4, map__rip_2objdump(map, sym->end), path);
  173. file = popen(command, "r");
  174. if (!file)
  175. return;
  176. pthread_mutex_lock(&source->lock);
  177. source->lines_tail = &source->lines;
  178. while (!feof(file)) {
  179. struct source_line *src;
  180. size_t dummy = 0;
  181. char *c, *sep;
  182. src = malloc(sizeof(struct source_line));
  183. assert(src != NULL);
  184. memset(src, 0, sizeof(struct source_line));
  185. if (getline(&src->line, &dummy, file) < 0)
  186. break;
  187. if (!src->line)
  188. break;
  189. c = strchr(src->line, '\n');
  190. if (c)
  191. *c = 0;
  192. src->next = NULL;
  193. *source->lines_tail = src;
  194. source->lines_tail = &src->next;
  195. src->eip = strtoull(src->line, &sep, 16);
  196. if (*sep == ':')
  197. src->eip = map__objdump_2ip(map, src->eip);
  198. else /* this line has no ip info (e.g. source line) */
  199. src->eip = 0;
  200. }
  201. pclose(file);
  202. out_assign:
  203. sym_filter_entry = syme;
  204. pthread_mutex_unlock(&source->lock);
  205. }
  206. static void __zero_source_counters(struct sym_entry *syme)
  207. {
  208. int i;
  209. struct source_line *line;
  210. line = syme->src->lines;
  211. while (line) {
  212. for (i = 0; i < nr_counters; i++)
  213. line->count[i] = 0;
  214. line = line->next;
  215. }
  216. }
  217. static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
  218. {
  219. struct source_line *line;
  220. if (syme != sym_filter_entry)
  221. return;
  222. if (pthread_mutex_trylock(&syme->src->lock))
  223. return;
  224. if (syme->src == NULL || syme->src->source == NULL)
  225. goto out_unlock;
  226. for (line = syme->src->lines; line; line = line->next) {
  227. /* skip lines without IP info */
  228. if (line->eip == 0)
  229. continue;
  230. if (line->eip == ip) {
  231. line->count[counter]++;
  232. break;
  233. }
  234. if (line->eip > ip)
  235. break;
  236. }
  237. out_unlock:
  238. pthread_mutex_unlock(&syme->src->lock);
  239. }
  240. #define PATTERN_LEN (BITS_PER_LONG / 4 + 2)
  241. static void lookup_sym_source(struct sym_entry *syme)
  242. {
  243. struct symbol *symbol = sym_entry__symbol(syme);
  244. struct source_line *line;
  245. char pattern[PATTERN_LEN + 1];
  246. sprintf(pattern, "%0*Lx <", BITS_PER_LONG / 4,
  247. map__rip_2objdump(syme->map, symbol->start));
  248. pthread_mutex_lock(&syme->src->lock);
  249. for (line = syme->src->lines; line; line = line->next) {
  250. if (memcmp(line->line, pattern, PATTERN_LEN) == 0) {
  251. syme->src->source = line;
  252. break;
  253. }
  254. }
  255. pthread_mutex_unlock(&syme->src->lock);
  256. }
  257. static void show_lines(struct source_line *queue, int count, int total)
  258. {
  259. int i;
  260. struct source_line *line;
  261. line = queue;
  262. for (i = 0; i < count; i++) {
  263. float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
  264. printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
  265. line = line->next;
  266. }
  267. }
  268. #define TRACE_COUNT 3
  269. static void show_details(struct sym_entry *syme)
  270. {
  271. struct symbol *symbol;
  272. struct source_line *line;
  273. struct source_line *line_queue = NULL;
  274. int displayed = 0;
  275. int line_queue_count = 0, total = 0, more = 0;
  276. if (!syme)
  277. return;
  278. if (!syme->src->source)
  279. lookup_sym_source(syme);
  280. if (!syme->src->source)
  281. return;
  282. symbol = sym_entry__symbol(syme);
  283. printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
  284. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  285. pthread_mutex_lock(&syme->src->lock);
  286. line = syme->src->source;
  287. while (line) {
  288. total += line->count[sym_counter];
  289. line = line->next;
  290. }
  291. line = syme->src->source;
  292. while (line) {
  293. float pcnt = 0.0;
  294. if (!line_queue_count)
  295. line_queue = line;
  296. line_queue_count++;
  297. if (line->count[sym_counter])
  298. pcnt = 100.0 * line->count[sym_counter] / (float)total;
  299. if (pcnt >= (float)sym_pcnt_filter) {
  300. if (displayed <= print_entries)
  301. show_lines(line_queue, line_queue_count, total);
  302. else more++;
  303. displayed += line_queue_count;
  304. line_queue_count = 0;
  305. line_queue = NULL;
  306. } else if (line_queue_count > TRACE_COUNT) {
  307. line_queue = line_queue->next;
  308. line_queue_count--;
  309. }
  310. line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
  311. line = line->next;
  312. }
  313. pthread_mutex_unlock(&syme->src->lock);
  314. if (more)
  315. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  316. }
  317. /*
  318. * Symbols will be added here in event__process_sample and will get out
  319. * after decayed.
  320. */
  321. static LIST_HEAD(active_symbols);
  322. static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
  323. /*
  324. * Ordering weight: count-1 * count-2 * ... / count-n
  325. */
  326. static double sym_weight(const struct sym_entry *sym)
  327. {
  328. double weight = sym->snap_count;
  329. int counter;
  330. if (!display_weighted)
  331. return weight;
  332. for (counter = 1; counter < nr_counters-1; counter++)
  333. weight *= sym->count[counter];
  334. weight /= (sym->count[counter] + 1);
  335. return weight;
  336. }
  337. static long samples;
  338. static long userspace_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 sum_ksamples = 0.0;
  373. struct sym_entry *syme, *n;
  374. struct rb_root tmp = RB_ROOT;
  375. struct rb_node *nd;
  376. int sym_width = 0, dso_width = 0, dso_short_width = 0;
  377. const int win_width = winsize.ws_col - 1;
  378. samples = userspace_samples = 0;
  379. /* Sort the active symbols */
  380. pthread_mutex_lock(&active_symbols_lock);
  381. syme = list_entry(active_symbols.next, struct sym_entry, node);
  382. pthread_mutex_unlock(&active_symbols_lock);
  383. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  384. syme->snap_count = syme->count[snap];
  385. if (syme->snap_count != 0) {
  386. if ((hide_user_symbols &&
  387. syme->origin == PERF_RECORD_MISC_USER) ||
  388. (hide_kernel_symbols &&
  389. syme->origin == PERF_RECORD_MISC_KERNEL)) {
  390. list_remove_active_sym(syme);
  391. continue;
  392. }
  393. syme->weight = sym_weight(syme);
  394. rb_insert_active_sym(&tmp, syme);
  395. sum_ksamples += syme->snap_count;
  396. for (j = 0; j < nr_counters; j++)
  397. syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
  398. } else
  399. list_remove_active_sym(syme);
  400. }
  401. puts(CONSOLE_CLEAR);
  402. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  403. printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% [",
  404. samples_per_sec,
  405. 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)));
  406. if (nr_counters == 1 || !display_weighted) {
  407. printf("%Ld", (u64)attrs[0].sample_period);
  408. if (freq)
  409. printf("Hz ");
  410. else
  411. printf(" ");
  412. }
  413. if (!display_weighted)
  414. printf("%s", event_name(sym_counter));
  415. else for (counter = 0; counter < nr_counters; counter++) {
  416. if (counter)
  417. printf("/");
  418. printf("%s", event_name(counter));
  419. }
  420. printf( "], ");
  421. if (target_pid != -1)
  422. printf(" (target_pid: %d", target_pid);
  423. else
  424. printf(" (all");
  425. if (profile_cpu != -1)
  426. printf(", cpu: %d)\n", profile_cpu);
  427. else {
  428. if (target_pid != -1)
  429. printf(")\n");
  430. else
  431. printf(", %d CPUs)\n", nr_cpus);
  432. }
  433. printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
  434. if (sym_filter_entry) {
  435. show_details(sym_filter_entry);
  436. return;
  437. }
  438. /*
  439. * Find the longest symbol name that will be displayed
  440. */
  441. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  442. syme = rb_entry(nd, struct sym_entry, rb_node);
  443. if (++printed > print_entries ||
  444. (int)syme->snap_count < count_filter)
  445. continue;
  446. if (syme->map->dso->long_name_len > dso_width)
  447. dso_width = syme->map->dso->long_name_len;
  448. if (syme->map->dso->short_name_len > dso_short_width)
  449. dso_short_width = syme->map->dso->short_name_len;
  450. if (syme->name_len > sym_width)
  451. sym_width = syme->name_len;
  452. }
  453. printed = 0;
  454. if (sym_width + dso_width > winsize.ws_col - 29) {
  455. dso_width = dso_short_width;
  456. if (sym_width + dso_width > winsize.ws_col - 29)
  457. sym_width = winsize.ws_col - dso_width - 29;
  458. }
  459. putchar('\n');
  460. if (nr_counters == 1)
  461. printf(" samples pcnt");
  462. else
  463. printf(" weight samples pcnt");
  464. if (verbose)
  465. printf(" RIP ");
  466. printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
  467. printf(" %s _______ _____",
  468. nr_counters == 1 ? " " : "______");
  469. if (verbose)
  470. printf(" ________________");
  471. printf(" %-*.*s", sym_width, sym_width, graph_line);
  472. printf(" %-*.*s", dso_width, dso_width, graph_line);
  473. puts("\n");
  474. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  475. struct symbol *sym;
  476. double pcnt;
  477. syme = rb_entry(nd, struct sym_entry, rb_node);
  478. sym = sym_entry__symbol(syme);
  479. if (++printed > print_entries || (int)syme->snap_count < count_filter)
  480. continue;
  481. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  482. sum_ksamples));
  483. if (nr_counters == 1 || !display_weighted)
  484. printf("%20.2f ", syme->weight);
  485. else
  486. printf("%9.1f %10ld ", syme->weight, syme->snap_count);
  487. percent_color_fprintf(stdout, "%4.1f%%", pcnt);
  488. if (verbose)
  489. printf(" %016llx", sym->start);
  490. printf(" %-*.*s", sym_width, sym_width, sym->name);
  491. printf(" %-*.*s\n", dso_width, dso_width,
  492. dso_width >= syme->map->dso->long_name_len ?
  493. syme->map->dso->long_name :
  494. syme->map->dso->short_name);
  495. }
  496. }
  497. static void prompt_integer(int *target, const char *msg)
  498. {
  499. char *buf = malloc(0), *p;
  500. size_t dummy = 0;
  501. int tmp;
  502. fprintf(stdout, "\n%s: ", msg);
  503. if (getline(&buf, &dummy, stdin) < 0)
  504. return;
  505. p = strchr(buf, '\n');
  506. if (p)
  507. *p = 0;
  508. p = buf;
  509. while(*p) {
  510. if (!isdigit(*p))
  511. goto out_free;
  512. p++;
  513. }
  514. tmp = strtoul(buf, NULL, 10);
  515. *target = tmp;
  516. out_free:
  517. free(buf);
  518. }
  519. static void prompt_percent(int *target, const char *msg)
  520. {
  521. int tmp = 0;
  522. prompt_integer(&tmp, msg);
  523. if (tmp >= 0 && tmp <= 100)
  524. *target = tmp;
  525. }
  526. static void prompt_symbol(struct sym_entry **target, const char *msg)
  527. {
  528. char *buf = malloc(0), *p;
  529. struct sym_entry *syme = *target, *n, *found = NULL;
  530. size_t dummy = 0;
  531. /* zero counters of active symbol */
  532. if (syme) {
  533. pthread_mutex_lock(&syme->src->lock);
  534. __zero_source_counters(syme);
  535. *target = NULL;
  536. pthread_mutex_unlock(&syme->src->lock);
  537. }
  538. fprintf(stdout, "\n%s: ", msg);
  539. if (getline(&buf, &dummy, stdin) < 0)
  540. goto out_free;
  541. p = strchr(buf, '\n');
  542. if (p)
  543. *p = 0;
  544. pthread_mutex_lock(&active_symbols_lock);
  545. syme = list_entry(active_symbols.next, struct sym_entry, node);
  546. pthread_mutex_unlock(&active_symbols_lock);
  547. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  548. struct symbol *sym = sym_entry__symbol(syme);
  549. if (!strcmp(buf, sym->name)) {
  550. found = syme;
  551. break;
  552. }
  553. }
  554. if (!found) {
  555. fprintf(stderr, "Sorry, %s is not active.\n", buf);
  556. sleep(1);
  557. return;
  558. } else
  559. parse_source(found);
  560. out_free:
  561. free(buf);
  562. }
  563. static void print_mapped_keys(void)
  564. {
  565. char *name = NULL;
  566. if (sym_filter_entry) {
  567. struct symbol *sym = sym_entry__symbol(sym_filter_entry);
  568. name = sym->name;
  569. }
  570. fprintf(stdout, "\nMapped keys:\n");
  571. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
  572. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
  573. if (nr_counters > 1)
  574. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
  575. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
  576. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  577. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  578. fprintf(stdout, "\t[S] stop annotation.\n");
  579. if (nr_counters > 1)
  580. fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
  581. fprintf(stdout,
  582. "\t[K] hide kernel_symbols symbols. \t(%s)\n",
  583. hide_kernel_symbols ? "yes" : "no");
  584. fprintf(stdout,
  585. "\t[U] hide user symbols. \t(%s)\n",
  586. hide_user_symbols ? "yes" : "no");
  587. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
  588. fprintf(stdout, "\t[qQ] quit.\n");
  589. }
  590. static int key_mapped(int c)
  591. {
  592. switch (c) {
  593. case 'd':
  594. case 'e':
  595. case 'f':
  596. case 'z':
  597. case 'q':
  598. case 'Q':
  599. case 'K':
  600. case 'U':
  601. case 'F':
  602. case 's':
  603. case 'S':
  604. return 1;
  605. case 'E':
  606. case 'w':
  607. return nr_counters > 1 ? 1 : 0;
  608. default:
  609. break;
  610. }
  611. return 0;
  612. }
  613. static void handle_keypress(int c)
  614. {
  615. if (!key_mapped(c)) {
  616. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  617. struct termios tc, save;
  618. print_mapped_keys();
  619. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  620. fflush(stdout);
  621. tcgetattr(0, &save);
  622. tc = save;
  623. tc.c_lflag &= ~(ICANON | ECHO);
  624. tc.c_cc[VMIN] = 0;
  625. tc.c_cc[VTIME] = 0;
  626. tcsetattr(0, TCSANOW, &tc);
  627. poll(&stdin_poll, 1, -1);
  628. c = getc(stdin);
  629. tcsetattr(0, TCSAFLUSH, &save);
  630. if (!key_mapped(c))
  631. return;
  632. }
  633. switch (c) {
  634. case 'd':
  635. prompt_integer(&delay_secs, "Enter display delay");
  636. if (delay_secs < 1)
  637. delay_secs = 1;
  638. break;
  639. case 'e':
  640. prompt_integer(&print_entries, "Enter display entries (lines)");
  641. if (print_entries == 0) {
  642. sig_winch_handler(SIGWINCH);
  643. signal(SIGWINCH, sig_winch_handler);
  644. } else
  645. signal(SIGWINCH, SIG_DFL);
  646. break;
  647. case 'E':
  648. if (nr_counters > 1) {
  649. int i;
  650. fprintf(stderr, "\nAvailable events:");
  651. for (i = 0; i < nr_counters; i++)
  652. fprintf(stderr, "\n\t%d %s", i, event_name(i));
  653. prompt_integer(&sym_counter, "Enter details event counter");
  654. if (sym_counter >= nr_counters) {
  655. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
  656. sym_counter = 0;
  657. sleep(1);
  658. }
  659. } else sym_counter = 0;
  660. break;
  661. case 'f':
  662. prompt_integer(&count_filter, "Enter display event count filter");
  663. break;
  664. case 'F':
  665. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  666. break;
  667. case 'K':
  668. hide_kernel_symbols = !hide_kernel_symbols;
  669. break;
  670. case 'q':
  671. case 'Q':
  672. printf("exiting.\n");
  673. if (dump_symtab)
  674. dsos__fprintf(stderr);
  675. exit(0);
  676. case 's':
  677. prompt_symbol(&sym_filter_entry, "Enter details symbol");
  678. break;
  679. case 'S':
  680. if (!sym_filter_entry)
  681. break;
  682. else {
  683. struct sym_entry *syme = sym_filter_entry;
  684. pthread_mutex_lock(&syme->src->lock);
  685. sym_filter_entry = NULL;
  686. __zero_source_counters(syme);
  687. pthread_mutex_unlock(&syme->src->lock);
  688. }
  689. break;
  690. case 'U':
  691. hide_user_symbols = !hide_user_symbols;
  692. break;
  693. case 'w':
  694. display_weighted = ~display_weighted;
  695. break;
  696. case 'z':
  697. zero = ~zero;
  698. break;
  699. default:
  700. break;
  701. }
  702. }
  703. static void *display_thread(void *arg __used)
  704. {
  705. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  706. struct termios tc, save;
  707. int delay_msecs, c;
  708. tcgetattr(0, &save);
  709. tc = save;
  710. tc.c_lflag &= ~(ICANON | ECHO);
  711. tc.c_cc[VMIN] = 0;
  712. tc.c_cc[VTIME] = 0;
  713. repeat:
  714. delay_msecs = delay_secs * 1000;
  715. tcsetattr(0, TCSANOW, &tc);
  716. /* trash return*/
  717. getc(stdin);
  718. do {
  719. print_sym_table();
  720. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  721. c = getc(stdin);
  722. tcsetattr(0, TCSAFLUSH, &save);
  723. handle_keypress(c);
  724. goto repeat;
  725. return NULL;
  726. }
  727. /* Tag samples to be skipped. */
  728. static const char *skip_symbols[] = {
  729. "default_idle",
  730. "cpu_idle",
  731. "enter_idle",
  732. "exit_idle",
  733. "mwait_idle",
  734. "mwait_idle_with_hints",
  735. "poll_idle",
  736. "ppc64_runlatch_off",
  737. "pseries_dedicated_idle_sleep",
  738. NULL
  739. };
  740. static int symbol_filter(struct map *map, struct symbol *sym)
  741. {
  742. struct sym_entry *syme;
  743. const char *name = sym->name;
  744. int i;
  745. /*
  746. * ppc64 uses function descriptors and appends a '.' to the
  747. * start of every instruction address. Remove it.
  748. */
  749. if (name[0] == '.')
  750. name++;
  751. if (!strcmp(name, "_text") ||
  752. !strcmp(name, "_etext") ||
  753. !strcmp(name, "_sinittext") ||
  754. !strncmp("init_module", name, 11) ||
  755. !strncmp("cleanup_module", name, 14) ||
  756. strstr(name, "_text_start") ||
  757. strstr(name, "_text_end"))
  758. return 1;
  759. syme = symbol__priv(sym);
  760. syme->map = map;
  761. syme->src = NULL;
  762. if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
  763. /* schedule initial sym_filter_entry setup */
  764. sym_filter_entry_sched = syme;
  765. sym_filter = NULL;
  766. }
  767. for (i = 0; skip_symbols[i]; i++) {
  768. if (!strcmp(skip_symbols[i], name)) {
  769. syme->skip = 1;
  770. break;
  771. }
  772. }
  773. if (!syme->skip)
  774. syme->name_len = strlen(sym->name);
  775. return 0;
  776. }
  777. static void event__process_sample(const event_t *self,
  778. struct perf_session *session, int counter)
  779. {
  780. u64 ip = self->ip.ip;
  781. struct sym_entry *syme;
  782. struct addr_location al;
  783. u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  784. ++samples;
  785. switch (origin) {
  786. case PERF_RECORD_MISC_USER:
  787. ++userspace_samples;
  788. if (hide_user_symbols)
  789. return;
  790. break;
  791. case PERF_RECORD_MISC_KERNEL:
  792. if (hide_kernel_symbols)
  793. return;
  794. break;
  795. default:
  796. return;
  797. }
  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 = cpumap[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. if (target_pid != -1 || profile_cpu != -1)
  1127. nr_cpus = 1;
  1128. else
  1129. nr_cpus = read_cpu_map();
  1130. get_term_dimensions(&winsize);
  1131. if (print_entries == 0) {
  1132. update_print_entries(&winsize);
  1133. signal(SIGWINCH, sig_winch_handler);
  1134. }
  1135. return __cmd_top();
  1136. }