builtin-top.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  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. 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,
  771. struct perf_session *session, int counter)
  772. {
  773. u64 ip = self->ip.ip;
  774. struct sym_entry *syme;
  775. struct addr_location al;
  776. u8 origin = self->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  777. switch (origin) {
  778. case PERF_RECORD_MISC_USER:
  779. if (hide_user_symbols)
  780. return;
  781. break;
  782. case PERF_RECORD_MISC_KERNEL:
  783. if (hide_kernel_symbols)
  784. return;
  785. break;
  786. default:
  787. return;
  788. }
  789. if (event__preprocess_sample(self, session, &al, symbol_filter) < 0 ||
  790. al.sym == NULL || al.filtered)
  791. return;
  792. syme = symbol__priv(al.sym);
  793. if (!syme->skip) {
  794. syme->count[counter]++;
  795. syme->origin = origin;
  796. record_precise_ip(syme, counter, ip);
  797. pthread_mutex_lock(&active_symbols_lock);
  798. if (list_empty(&syme->node) || !syme->node.next)
  799. __list_insert_active_sym(syme);
  800. pthread_mutex_unlock(&active_symbols_lock);
  801. if (origin == PERF_RECORD_MISC_USER)
  802. ++userspace_samples;
  803. ++samples;
  804. }
  805. }
  806. static int event__process(event_t *event, struct perf_session *session)
  807. {
  808. switch (event->header.type) {
  809. case PERF_RECORD_COMM:
  810. event__process_comm(event, session);
  811. break;
  812. case PERF_RECORD_MMAP:
  813. event__process_mmap(event, session);
  814. break;
  815. default:
  816. break;
  817. }
  818. return 0;
  819. }
  820. struct mmap_data {
  821. int counter;
  822. void *base;
  823. int mask;
  824. unsigned int prev;
  825. };
  826. static unsigned int mmap_read_head(struct mmap_data *md)
  827. {
  828. struct perf_event_mmap_page *pc = md->base;
  829. int head;
  830. head = pc->data_head;
  831. rmb();
  832. return head;
  833. }
  834. static void perf_session__mmap_read_counter(struct perf_session *self,
  835. struct mmap_data *md)
  836. {
  837. unsigned int head = mmap_read_head(md);
  838. unsigned int old = md->prev;
  839. unsigned char *data = md->base + page_size;
  840. int diff;
  841. /*
  842. * If we're further behind than half the buffer, there's a chance
  843. * the writer will bite our tail and mess up the samples under us.
  844. *
  845. * If we somehow ended up ahead of the head, we got messed up.
  846. *
  847. * In either case, truncate and restart at head.
  848. */
  849. diff = head - old;
  850. if (diff > md->mask / 2 || diff < 0) {
  851. fprintf(stderr, "WARNING: failed to keep up with mmap data.\n");
  852. /*
  853. * head points to a known good entry, start there.
  854. */
  855. old = head;
  856. }
  857. for (; old != head;) {
  858. event_t *event = (event_t *)&data[old & md->mask];
  859. event_t event_copy;
  860. size_t size = event->header.size;
  861. /*
  862. * Event straddles the mmap boundary -- header should always
  863. * be inside due to u64 alignment of output.
  864. */
  865. if ((old & md->mask) + size != ((old + size) & md->mask)) {
  866. unsigned int offset = old;
  867. unsigned int len = min(sizeof(*event), size), cpy;
  868. void *dst = &event_copy;
  869. do {
  870. cpy = min(md->mask + 1 - (offset & md->mask), len);
  871. memcpy(dst, &data[offset & md->mask], cpy);
  872. offset += cpy;
  873. dst += cpy;
  874. len -= cpy;
  875. } while (len);
  876. event = &event_copy;
  877. }
  878. if (event->header.type == PERF_RECORD_SAMPLE)
  879. event__process_sample(event, self, md->counter);
  880. else
  881. event__process(event, self);
  882. old += size;
  883. }
  884. md->prev = old;
  885. }
  886. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  887. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  888. static void perf_session__mmap_read(struct perf_session *self)
  889. {
  890. int i, counter;
  891. for (i = 0; i < nr_cpus; i++) {
  892. for (counter = 0; counter < nr_counters; counter++)
  893. perf_session__mmap_read_counter(self, &mmap_array[i][counter]);
  894. }
  895. }
  896. int nr_poll;
  897. int group_fd;
  898. static void start_counter(int i, int counter)
  899. {
  900. struct perf_event_attr *attr;
  901. int cpu;
  902. cpu = profile_cpu;
  903. if (target_pid == -1 && profile_cpu == -1)
  904. cpu = i;
  905. attr = attrs + counter;
  906. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  907. if (freq) {
  908. attr->sample_type |= PERF_SAMPLE_PERIOD;
  909. attr->freq = 1;
  910. attr->sample_freq = freq;
  911. }
  912. attr->inherit = (cpu < 0) && inherit;
  913. attr->mmap = 1;
  914. try_again:
  915. fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
  916. if (fd[i][counter] < 0) {
  917. int err = errno;
  918. if (err == EPERM || err == EACCES)
  919. die("No permission - are you root?\n");
  920. /*
  921. * If it's cycles then fall back to hrtimer
  922. * based cpu-clock-tick sw counter, which
  923. * is always available even if no PMU support:
  924. */
  925. if (attr->type == PERF_TYPE_HARDWARE
  926. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  927. if (verbose)
  928. warning(" ... trying to fall back to cpu-clock-ticks\n");
  929. attr->type = PERF_TYPE_SOFTWARE;
  930. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  931. goto try_again;
  932. }
  933. printf("\n");
  934. error("perfcounter syscall returned with %d (%s)\n",
  935. fd[i][counter], strerror(err));
  936. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  937. exit(-1);
  938. }
  939. assert(fd[i][counter] >= 0);
  940. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  941. /*
  942. * First counter acts as the group leader:
  943. */
  944. if (group && group_fd == -1)
  945. group_fd = fd[i][counter];
  946. event_array[nr_poll].fd = fd[i][counter];
  947. event_array[nr_poll].events = POLLIN;
  948. nr_poll++;
  949. mmap_array[i][counter].counter = counter;
  950. mmap_array[i][counter].prev = 0;
  951. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  952. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  953. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  954. if (mmap_array[i][counter].base == MAP_FAILED)
  955. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  956. }
  957. static int __cmd_top(void)
  958. {
  959. pthread_t thread;
  960. int i, counter;
  961. int ret;
  962. /*
  963. * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
  964. * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
  965. */
  966. struct perf_session *session = perf_session__new(NULL, O_WRONLY, false);
  967. if (session == NULL)
  968. return -ENOMEM;
  969. if (target_pid != -1)
  970. event__synthesize_thread(target_pid, event__process, session);
  971. else
  972. event__synthesize_threads(event__process, session);
  973. for (i = 0; i < nr_cpus; i++) {
  974. group_fd = -1;
  975. for (counter = 0; counter < nr_counters; counter++)
  976. start_counter(i, counter);
  977. }
  978. /* Wait for a minimal set of events before starting the snapshot */
  979. poll(event_array, nr_poll, 100);
  980. perf_session__mmap_read(session);
  981. if (pthread_create(&thread, NULL, display_thread, NULL)) {
  982. printf("Could not create display thread.\n");
  983. exit(-1);
  984. }
  985. if (realtime_prio) {
  986. struct sched_param param;
  987. param.sched_priority = realtime_prio;
  988. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  989. printf("Could not set realtime priority.\n");
  990. exit(-1);
  991. }
  992. }
  993. while (1) {
  994. int hits = samples;
  995. perf_session__mmap_read(session);
  996. if (hits == samples)
  997. ret = poll(event_array, nr_poll, 100);
  998. }
  999. return 0;
  1000. }
  1001. static const char * const top_usage[] = {
  1002. "perf top [<options>]",
  1003. NULL
  1004. };
  1005. static const struct option options[] = {
  1006. OPT_CALLBACK('e', "event", NULL, "event",
  1007. "event selector. use 'perf list' to list available events",
  1008. parse_events),
  1009. OPT_INTEGER('c', "count", &default_interval,
  1010. "event period to sample"),
  1011. OPT_INTEGER('p', "pid", &target_pid,
  1012. "profile events on existing pid"),
  1013. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  1014. "system-wide collection from all CPUs"),
  1015. OPT_INTEGER('C', "CPU", &profile_cpu,
  1016. "CPU to profile on"),
  1017. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  1018. "file", "vmlinux pathname"),
  1019. OPT_BOOLEAN('K', "hide_kernel_symbols", &hide_kernel_symbols,
  1020. "hide kernel symbols"),
  1021. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  1022. "number of mmap data pages"),
  1023. OPT_INTEGER('r', "realtime", &realtime_prio,
  1024. "collect data with this RT SCHED_FIFO priority"),
  1025. OPT_INTEGER('d', "delay", &delay_secs,
  1026. "number of seconds to delay between refreshes"),
  1027. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  1028. "dump the symbol table used for profiling"),
  1029. OPT_INTEGER('f', "count-filter", &count_filter,
  1030. "only display functions with more events than this"),
  1031. OPT_BOOLEAN('g', "group", &group,
  1032. "put the counters into a counter group"),
  1033. OPT_BOOLEAN('i', "inherit", &inherit,
  1034. "child tasks inherit counters"),
  1035. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  1036. "symbol to annotate - requires -k option"),
  1037. OPT_BOOLEAN('z', "zero", &zero,
  1038. "zero history across updates"),
  1039. OPT_INTEGER('F', "freq", &freq,
  1040. "profile at this frequency"),
  1041. OPT_INTEGER('E', "entries", &print_entries,
  1042. "display this many functions"),
  1043. OPT_BOOLEAN('U', "hide_user_symbols", &hide_user_symbols,
  1044. "hide user symbols"),
  1045. OPT_BOOLEAN('v', "verbose", &verbose,
  1046. "be more verbose (show counter open errors, etc)"),
  1047. OPT_END()
  1048. };
  1049. int cmd_top(int argc, const char **argv, const char *prefix __used)
  1050. {
  1051. int counter;
  1052. page_size = sysconf(_SC_PAGE_SIZE);
  1053. argc = parse_options(argc, argv, options, top_usage, 0);
  1054. if (argc)
  1055. usage_with_options(top_usage, options);
  1056. /* CPU and PID are mutually exclusive */
  1057. if (target_pid != -1 && profile_cpu != -1) {
  1058. printf("WARNING: PID switch overriding CPU\n");
  1059. sleep(1);
  1060. profile_cpu = -1;
  1061. }
  1062. if (!nr_counters)
  1063. nr_counters = 1;
  1064. symbol_conf.priv_size = (sizeof(struct sym_entry) +
  1065. (nr_counters + 1) * sizeof(unsigned long));
  1066. if (symbol_conf.vmlinux_name == NULL)
  1067. symbol_conf.try_vmlinux_path = true;
  1068. if (symbol__init() < 0)
  1069. return -1;
  1070. if (delay_secs < 1)
  1071. delay_secs = 1;
  1072. parse_source(sym_filter_entry);
  1073. /*
  1074. * User specified count overrides default frequency.
  1075. */
  1076. if (default_interval)
  1077. freq = 0;
  1078. else if (freq) {
  1079. default_interval = freq;
  1080. } else {
  1081. fprintf(stderr, "frequency and count are zero, aborting\n");
  1082. exit(EXIT_FAILURE);
  1083. }
  1084. /*
  1085. * Fill in the ones not specifically initialized via -c:
  1086. */
  1087. for (counter = 0; counter < nr_counters; counter++) {
  1088. if (attrs[counter].sample_period)
  1089. continue;
  1090. attrs[counter].sample_period = default_interval;
  1091. }
  1092. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  1093. assert(nr_cpus <= MAX_NR_CPUS);
  1094. assert(nr_cpus >= 0);
  1095. if (target_pid != -1 || profile_cpu != -1)
  1096. nr_cpus = 1;
  1097. get_term_dimensions(&winsize);
  1098. if (print_entries == 0) {
  1099. update_print_entries(&winsize);
  1100. signal(SIGWINCH, sig_winch_handler);
  1101. }
  1102. return __cmd_top();
  1103. }