builtin-top.c 31 KB

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