builtin-top.c 31 KB

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