builtin-top.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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 = 100000;
  50. static int count_filter = 5;
  51. static int print_entries = 15;
  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 = 0;
  61. static int delay_secs = 2;
  62. static int zero;
  63. static int dump_symtab;
  64. /*
  65. * Source
  66. */
  67. struct source_line {
  68. u64 eip;
  69. unsigned long count[MAX_COUNTERS];
  70. char *line;
  71. struct source_line *next;
  72. };
  73. static char *sym_filter = NULL;
  74. struct sym_entry *sym_filter_entry = NULL;
  75. static int sym_pcnt_filter = 5;
  76. static int sym_counter = 0;
  77. static int display_weighted = -1;
  78. /*
  79. * Symbols
  80. */
  81. struct sym_entry {
  82. struct rb_node rb_node;
  83. struct list_head node;
  84. unsigned long count[MAX_COUNTERS];
  85. unsigned long snap_count;
  86. double weight;
  87. int skip;
  88. struct map *map;
  89. struct source_line *source;
  90. struct source_line *lines;
  91. struct source_line **lines_tail;
  92. pthread_mutex_t source_lock;
  93. };
  94. /*
  95. * Source functions
  96. */
  97. static void parse_source(struct sym_entry *syme)
  98. {
  99. struct symbol *sym;
  100. struct map *map;
  101. FILE *file;
  102. char command[PATH_MAX*2];
  103. const char *path;
  104. u64 len;
  105. if (!syme)
  106. return;
  107. if (syme->lines) {
  108. pthread_mutex_lock(&syme->source_lock);
  109. goto out_assign;
  110. }
  111. sym = (struct symbol *)(syme + 1);
  112. map = syme->map;
  113. path = map->dso->long_name;
  114. len = sym->end - sym->start;
  115. sprintf(command,
  116. "objdump --start-address=0x%016Lx "
  117. "--stop-address=0x%016Lx -dS %s",
  118. sym->start, sym->end, path);
  119. file = popen(command, "r");
  120. if (!file)
  121. return;
  122. pthread_mutex_lock(&syme->source_lock);
  123. syme->lines_tail = &syme->lines;
  124. while (!feof(file)) {
  125. struct source_line *src;
  126. size_t dummy = 0;
  127. char *c;
  128. src = malloc(sizeof(struct source_line));
  129. assert(src != NULL);
  130. memset(src, 0, sizeof(struct source_line));
  131. if (getline(&src->line, &dummy, file) < 0)
  132. break;
  133. if (!src->line)
  134. break;
  135. c = strchr(src->line, '\n');
  136. if (c)
  137. *c = 0;
  138. src->next = NULL;
  139. *syme->lines_tail = src;
  140. syme->lines_tail = &src->next;
  141. if (strlen(src->line)>8 && src->line[8] == ':') {
  142. src->eip = strtoull(src->line, NULL, 16);
  143. src->eip += map->start;
  144. }
  145. if (strlen(src->line)>8 && src->line[16] == ':') {
  146. src->eip = strtoull(src->line, NULL, 16);
  147. src->eip += map->start;
  148. }
  149. }
  150. pclose(file);
  151. out_assign:
  152. sym_filter_entry = syme;
  153. pthread_mutex_unlock(&syme->source_lock);
  154. }
  155. static void __zero_source_counters(struct sym_entry *syme)
  156. {
  157. int i;
  158. struct source_line *line;
  159. line = syme->lines;
  160. while (line) {
  161. for (i = 0; i < nr_counters; i++)
  162. line->count[i] = 0;
  163. line = line->next;
  164. }
  165. }
  166. static void record_precise_ip(struct sym_entry *syme, int counter, u64 ip)
  167. {
  168. struct source_line *line;
  169. if (syme != sym_filter_entry)
  170. return;
  171. if (pthread_mutex_trylock(&syme->source_lock))
  172. return;
  173. if (!syme->source)
  174. goto out_unlock;
  175. for (line = syme->lines; line; line = line->next) {
  176. if (line->eip == ip) {
  177. line->count[counter]++;
  178. break;
  179. }
  180. if (line->eip > ip)
  181. break;
  182. }
  183. out_unlock:
  184. pthread_mutex_unlock(&syme->source_lock);
  185. }
  186. static void lookup_sym_source(struct sym_entry *syme)
  187. {
  188. struct symbol *symbol = (struct symbol *)(syme + 1);
  189. struct source_line *line;
  190. char pattern[PATH_MAX];
  191. sprintf(pattern, "<%s>:", symbol->name);
  192. pthread_mutex_lock(&syme->source_lock);
  193. for (line = syme->lines; line; line = line->next) {
  194. if (strstr(line->line, pattern)) {
  195. syme->source = line;
  196. break;
  197. }
  198. }
  199. pthread_mutex_unlock(&syme->source_lock);
  200. }
  201. static void show_lines(struct source_line *queue, int count, int total)
  202. {
  203. int i;
  204. struct source_line *line;
  205. line = queue;
  206. for (i = 0; i < count; i++) {
  207. float pcnt = 100.0*(float)line->count[sym_counter]/(float)total;
  208. printf("%8li %4.1f%%\t%s\n", line->count[sym_counter], pcnt, line->line);
  209. line = line->next;
  210. }
  211. }
  212. #define TRACE_COUNT 3
  213. static void show_details(struct sym_entry *syme)
  214. {
  215. struct symbol *symbol;
  216. struct source_line *line;
  217. struct source_line *line_queue = NULL;
  218. int displayed = 0;
  219. int line_queue_count = 0, total = 0, more = 0;
  220. if (!syme)
  221. return;
  222. if (!syme->source)
  223. lookup_sym_source(syme);
  224. if (!syme->source)
  225. return;
  226. symbol = (struct symbol *)(syme + 1);
  227. printf("Showing %s for %s\n", event_name(sym_counter), symbol->name);
  228. printf(" Events Pcnt (>=%d%%)\n", sym_pcnt_filter);
  229. pthread_mutex_lock(&syme->source_lock);
  230. line = syme->source;
  231. while (line) {
  232. total += line->count[sym_counter];
  233. line = line->next;
  234. }
  235. line = syme->source;
  236. while (line) {
  237. float pcnt = 0.0;
  238. if (!line_queue_count)
  239. line_queue = line;
  240. line_queue_count++;
  241. if (line->count[sym_counter])
  242. pcnt = 100.0 * line->count[sym_counter] / (float)total;
  243. if (pcnt >= (float)sym_pcnt_filter) {
  244. if (displayed <= print_entries)
  245. show_lines(line_queue, line_queue_count, total);
  246. else more++;
  247. displayed += line_queue_count;
  248. line_queue_count = 0;
  249. line_queue = NULL;
  250. } else if (line_queue_count > TRACE_COUNT) {
  251. line_queue = line_queue->next;
  252. line_queue_count--;
  253. }
  254. line->count[sym_counter] = zero ? 0 : line->count[sym_counter] * 7 / 8;
  255. line = line->next;
  256. }
  257. pthread_mutex_unlock(&syme->source_lock);
  258. if (more)
  259. printf("%d lines not displayed, maybe increase display entries [e]\n", more);
  260. }
  261. /*
  262. * Symbols will be added here in record_ip and will get out
  263. * after decayed.
  264. */
  265. static LIST_HEAD(active_symbols);
  266. static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
  267. /*
  268. * Ordering weight: count-1 * count-2 * ... / count-n
  269. */
  270. static double sym_weight(const struct sym_entry *sym)
  271. {
  272. double weight = sym->snap_count;
  273. int counter;
  274. if (!display_weighted)
  275. return weight;
  276. for (counter = 1; counter < nr_counters-1; counter++)
  277. weight *= sym->count[counter];
  278. weight /= (sym->count[counter] + 1);
  279. return weight;
  280. }
  281. static long samples;
  282. static long userspace_samples;
  283. static const char CONSOLE_CLEAR[] = "";
  284. static void __list_insert_active_sym(struct sym_entry *syme)
  285. {
  286. list_add(&syme->node, &active_symbols);
  287. }
  288. static void list_remove_active_sym(struct sym_entry *syme)
  289. {
  290. pthread_mutex_lock(&active_symbols_lock);
  291. list_del_init(&syme->node);
  292. pthread_mutex_unlock(&active_symbols_lock);
  293. }
  294. static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
  295. {
  296. struct rb_node **p = &tree->rb_node;
  297. struct rb_node *parent = NULL;
  298. struct sym_entry *iter;
  299. while (*p != NULL) {
  300. parent = *p;
  301. iter = rb_entry(parent, struct sym_entry, rb_node);
  302. if (se->weight > iter->weight)
  303. p = &(*p)->rb_left;
  304. else
  305. p = &(*p)->rb_right;
  306. }
  307. rb_link_node(&se->rb_node, parent, p);
  308. rb_insert_color(&se->rb_node, tree);
  309. }
  310. static void print_sym_table(void)
  311. {
  312. int printed = 0, j;
  313. int counter, snap = !display_weighted ? sym_counter : 0;
  314. float samples_per_sec = samples/delay_secs;
  315. float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
  316. float sum_ksamples = 0.0;
  317. struct sym_entry *syme, *n;
  318. struct rb_root tmp = RB_ROOT;
  319. struct rb_node *nd;
  320. samples = userspace_samples = 0;
  321. /* Sort the active symbols */
  322. pthread_mutex_lock(&active_symbols_lock);
  323. syme = list_entry(active_symbols.next, struct sym_entry, node);
  324. pthread_mutex_unlock(&active_symbols_lock);
  325. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  326. syme->snap_count = syme->count[snap];
  327. if (syme->snap_count != 0) {
  328. syme->weight = sym_weight(syme);
  329. rb_insert_active_sym(&tmp, syme);
  330. sum_ksamples += syme->snap_count;
  331. for (j = 0; j < nr_counters; j++)
  332. syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
  333. } else
  334. list_remove_active_sym(syme);
  335. }
  336. puts(CONSOLE_CLEAR);
  337. printf(
  338. "------------------------------------------------------------------------------\n");
  339. printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% [",
  340. samples_per_sec,
  341. 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)));
  342. if (nr_counters == 1 || !display_weighted) {
  343. printf("%Ld", (u64)attrs[0].sample_period);
  344. if (freq)
  345. printf("Hz ");
  346. else
  347. printf(" ");
  348. }
  349. if (!display_weighted)
  350. printf("%s", event_name(sym_counter));
  351. else for (counter = 0; counter < nr_counters; counter++) {
  352. if (counter)
  353. printf("/");
  354. printf("%s", event_name(counter));
  355. }
  356. printf( "], ");
  357. if (target_pid != -1)
  358. printf(" (target_pid: %d", target_pid);
  359. else
  360. printf(" (all");
  361. if (profile_cpu != -1)
  362. printf(", cpu: %d)\n", profile_cpu);
  363. else {
  364. if (target_pid != -1)
  365. printf(")\n");
  366. else
  367. printf(", %d CPUs)\n", nr_cpus);
  368. }
  369. printf("------------------------------------------------------------------------------\n\n");
  370. if (sym_filter_entry) {
  371. show_details(sym_filter_entry);
  372. return;
  373. }
  374. if (nr_counters == 1)
  375. printf(" samples pcnt");
  376. else
  377. printf(" weight samples pcnt");
  378. if (verbose)
  379. printf(" RIP ");
  380. printf(" kernel function\n");
  381. printf(" %s _______ _____",
  382. nr_counters == 1 ? " " : "______");
  383. if (verbose)
  384. printf(" ________________");
  385. printf(" _______________\n\n");
  386. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  387. struct symbol *sym;
  388. double pcnt;
  389. syme = rb_entry(nd, struct sym_entry, rb_node);
  390. sym = (struct symbol *)(syme + 1);
  391. if (++printed > print_entries || (int)syme->snap_count < count_filter)
  392. continue;
  393. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  394. sum_ksamples));
  395. if (nr_counters == 1 || !display_weighted)
  396. printf("%20.2f - ", syme->weight);
  397. else
  398. printf("%9.1f %10ld - ", syme->weight, syme->snap_count);
  399. percent_color_fprintf(stdout, "%4.1f%%", pcnt);
  400. if (verbose)
  401. printf(" - %016llx", sym->start);
  402. printf(" : %s", sym->name);
  403. if (syme->map->dso->name[0] == '[')
  404. printf(" \t%s", syme->map->dso->name);
  405. printf("\n");
  406. }
  407. }
  408. static void prompt_integer(int *target, const char *msg)
  409. {
  410. char *buf = malloc(0), *p;
  411. size_t dummy = 0;
  412. int tmp;
  413. fprintf(stdout, "\n%s: ", msg);
  414. if (getline(&buf, &dummy, stdin) < 0)
  415. return;
  416. p = strchr(buf, '\n');
  417. if (p)
  418. *p = 0;
  419. p = buf;
  420. while(*p) {
  421. if (!isdigit(*p))
  422. goto out_free;
  423. p++;
  424. }
  425. tmp = strtoul(buf, NULL, 10);
  426. *target = tmp;
  427. out_free:
  428. free(buf);
  429. }
  430. static void prompt_percent(int *target, const char *msg)
  431. {
  432. int tmp = 0;
  433. prompt_integer(&tmp, msg);
  434. if (tmp >= 0 && tmp <= 100)
  435. *target = tmp;
  436. }
  437. static void prompt_symbol(struct sym_entry **target, const char *msg)
  438. {
  439. char *buf = malloc(0), *p;
  440. struct sym_entry *syme = *target, *n, *found = NULL;
  441. size_t dummy = 0;
  442. /* zero counters of active symbol */
  443. if (syme) {
  444. pthread_mutex_lock(&syme->source_lock);
  445. __zero_source_counters(syme);
  446. *target = NULL;
  447. pthread_mutex_unlock(&syme->source_lock);
  448. }
  449. fprintf(stdout, "\n%s: ", msg);
  450. if (getline(&buf, &dummy, stdin) < 0)
  451. goto out_free;
  452. p = strchr(buf, '\n');
  453. if (p)
  454. *p = 0;
  455. pthread_mutex_lock(&active_symbols_lock);
  456. syme = list_entry(active_symbols.next, struct sym_entry, node);
  457. pthread_mutex_unlock(&active_symbols_lock);
  458. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  459. struct symbol *sym = (struct symbol *)(syme + 1);
  460. if (!strcmp(buf, sym->name)) {
  461. found = syme;
  462. break;
  463. }
  464. }
  465. if (!found) {
  466. fprintf(stderr, "Sorry, %s is not active.\n", sym_filter);
  467. sleep(1);
  468. return;
  469. } else
  470. parse_source(found);
  471. out_free:
  472. free(buf);
  473. }
  474. static void print_mapped_keys(void)
  475. {
  476. char *name = NULL;
  477. if (sym_filter_entry) {
  478. struct symbol *sym = (struct symbol *)(sym_filter_entry+1);
  479. name = sym->name;
  480. }
  481. fprintf(stdout, "\nMapped keys:\n");
  482. fprintf(stdout, "\t[d] display refresh delay. \t(%d)\n", delay_secs);
  483. fprintf(stdout, "\t[e] display entries (lines). \t(%d)\n", print_entries);
  484. if (nr_counters > 1)
  485. fprintf(stdout, "\t[E] active event counter. \t(%s)\n", event_name(sym_counter));
  486. fprintf(stdout, "\t[f] profile display filter (count). \t(%d)\n", count_filter);
  487. if (vmlinux_name) {
  488. fprintf(stdout, "\t[F] annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
  489. fprintf(stdout, "\t[s] annotate symbol. \t(%s)\n", name?: "NULL");
  490. fprintf(stdout, "\t[S] stop annotation.\n");
  491. }
  492. if (nr_counters > 1)
  493. fprintf(stdout, "\t[w] toggle display weighted/count[E]r. \t(%d)\n", display_weighted ? 1 : 0);
  494. fprintf(stdout, "\t[z] toggle sample zeroing. \t(%d)\n", zero ? 1 : 0);
  495. fprintf(stdout, "\t[qQ] quit.\n");
  496. }
  497. static int key_mapped(int c)
  498. {
  499. switch (c) {
  500. case 'd':
  501. case 'e':
  502. case 'f':
  503. case 'z':
  504. case 'q':
  505. case 'Q':
  506. return 1;
  507. case 'E':
  508. case 'w':
  509. return nr_counters > 1 ? 1 : 0;
  510. case 'F':
  511. case 's':
  512. case 'S':
  513. return vmlinux_name ? 1 : 0;
  514. default:
  515. break;
  516. }
  517. return 0;
  518. }
  519. static void handle_keypress(int c)
  520. {
  521. if (!key_mapped(c)) {
  522. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  523. struct termios tc, save;
  524. print_mapped_keys();
  525. fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
  526. fflush(stdout);
  527. tcgetattr(0, &save);
  528. tc = save;
  529. tc.c_lflag &= ~(ICANON | ECHO);
  530. tc.c_cc[VMIN] = 0;
  531. tc.c_cc[VTIME] = 0;
  532. tcsetattr(0, TCSANOW, &tc);
  533. poll(&stdin_poll, 1, -1);
  534. c = getc(stdin);
  535. tcsetattr(0, TCSAFLUSH, &save);
  536. if (!key_mapped(c))
  537. return;
  538. }
  539. switch (c) {
  540. case 'd':
  541. prompt_integer(&delay_secs, "Enter display delay");
  542. break;
  543. case 'e':
  544. prompt_integer(&print_entries, "Enter display entries (lines)");
  545. break;
  546. case 'E':
  547. if (nr_counters > 1) {
  548. int i;
  549. fprintf(stderr, "\nAvailable events:");
  550. for (i = 0; i < nr_counters; i++)
  551. fprintf(stderr, "\n\t%d %s", i, event_name(i));
  552. prompt_integer(&sym_counter, "Enter details event counter");
  553. if (sym_counter >= nr_counters) {
  554. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
  555. sym_counter = 0;
  556. sleep(1);
  557. }
  558. } else sym_counter = 0;
  559. break;
  560. case 'f':
  561. prompt_integer(&count_filter, "Enter display event count filter");
  562. break;
  563. case 'F':
  564. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  565. break;
  566. case 'q':
  567. case 'Q':
  568. printf("exiting.\n");
  569. exit(0);
  570. case 's':
  571. prompt_symbol(&sym_filter_entry, "Enter details symbol");
  572. break;
  573. case 'S':
  574. if (!sym_filter_entry)
  575. break;
  576. else {
  577. struct sym_entry *syme = sym_filter_entry;
  578. pthread_mutex_lock(&syme->source_lock);
  579. sym_filter_entry = NULL;
  580. __zero_source_counters(syme);
  581. pthread_mutex_unlock(&syme->source_lock);
  582. }
  583. break;
  584. case 'w':
  585. display_weighted = ~display_weighted;
  586. break;
  587. case 'z':
  588. zero = ~zero;
  589. break;
  590. default:
  591. break;
  592. }
  593. }
  594. static void *display_thread(void *arg __used)
  595. {
  596. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  597. struct termios tc, save;
  598. int delay_msecs, c;
  599. tcgetattr(0, &save);
  600. tc = save;
  601. tc.c_lflag &= ~(ICANON | ECHO);
  602. tc.c_cc[VMIN] = 0;
  603. tc.c_cc[VTIME] = 0;
  604. repeat:
  605. delay_msecs = delay_secs * 1000;
  606. tcsetattr(0, TCSANOW, &tc);
  607. /* trash return*/
  608. getc(stdin);
  609. do {
  610. print_sym_table();
  611. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  612. c = getc(stdin);
  613. tcsetattr(0, TCSAFLUSH, &save);
  614. handle_keypress(c);
  615. goto repeat;
  616. return NULL;
  617. }
  618. /* Tag samples to be skipped. */
  619. static const char *skip_symbols[] = {
  620. "default_idle",
  621. "cpu_idle",
  622. "enter_idle",
  623. "exit_idle",
  624. "mwait_idle",
  625. "mwait_idle_with_hints",
  626. "ppc64_runlatch_off",
  627. "pseries_dedicated_idle_sleep",
  628. NULL
  629. };
  630. static int symbol_filter(struct map *map, struct symbol *sym)
  631. {
  632. struct sym_entry *syme;
  633. const char *name = sym->name;
  634. int i;
  635. /*
  636. * ppc64 uses function descriptors and appends a '.' to the
  637. * start of every instruction address. Remove it.
  638. */
  639. if (name[0] == '.')
  640. name++;
  641. if (!strcmp(name, "_text") ||
  642. !strcmp(name, "_etext") ||
  643. !strcmp(name, "_sinittext") ||
  644. !strncmp("init_module", name, 11) ||
  645. !strncmp("cleanup_module", name, 14) ||
  646. strstr(name, "_text_start") ||
  647. strstr(name, "_text_end"))
  648. return 1;
  649. syme = dso__sym_priv(map->dso, sym);
  650. syme->map = map;
  651. pthread_mutex_init(&syme->source_lock, NULL);
  652. if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
  653. sym_filter_entry = syme;
  654. for (i = 0; skip_symbols[i]; i++) {
  655. if (!strcmp(skip_symbols[i], name)) {
  656. syme->skip = 1;
  657. break;
  658. }
  659. }
  660. return 0;
  661. }
  662. static int parse_symbols(void)
  663. {
  664. int use_modules = vmlinux_name ? 1 : 0;
  665. if (dsos__load_kernel(vmlinux_name, sizeof(struct sym_entry),
  666. symbol_filter, verbose, use_modules) <= 0)
  667. return -1;
  668. if (dump_symtab)
  669. dsos__fprintf(stderr);
  670. return 0;
  671. }
  672. /*
  673. * Binary search in the histogram table and record the hit:
  674. */
  675. static void record_ip(u64 ip, int counter)
  676. {
  677. struct map *map;
  678. struct symbol *sym = kernel_maps__find_symbol(ip, &map);
  679. if (sym != NULL) {
  680. struct sym_entry *syme = dso__sym_priv(map->dso, sym);
  681. if (!syme->skip) {
  682. syme->count[counter]++;
  683. record_precise_ip(syme, counter, ip);
  684. pthread_mutex_lock(&active_symbols_lock);
  685. if (list_empty(&syme->node) || !syme->node.next)
  686. __list_insert_active_sym(syme);
  687. pthread_mutex_unlock(&active_symbols_lock);
  688. return;
  689. }
  690. }
  691. samples--;
  692. }
  693. static void process_event(u64 ip, int counter, int user)
  694. {
  695. samples++;
  696. if (user) {
  697. userspace_samples++;
  698. return;
  699. }
  700. record_ip(ip, counter);
  701. }
  702. struct mmap_data {
  703. int counter;
  704. void *base;
  705. int mask;
  706. unsigned int prev;
  707. };
  708. static unsigned int mmap_read_head(struct mmap_data *md)
  709. {
  710. struct perf_event_mmap_page *pc = md->base;
  711. int head;
  712. head = pc->data_head;
  713. rmb();
  714. return head;
  715. }
  716. struct timeval last_read, this_read;
  717. static void mmap_read_counter(struct mmap_data *md)
  718. {
  719. unsigned int head = mmap_read_head(md);
  720. unsigned int old = md->prev;
  721. unsigned char *data = md->base + page_size;
  722. int diff;
  723. gettimeofday(&this_read, NULL);
  724. /*
  725. * If we're further behind than half the buffer, there's a chance
  726. * the writer will bite our tail and mess up the samples under us.
  727. *
  728. * If we somehow ended up ahead of the head, we got messed up.
  729. *
  730. * In either case, truncate and restart at head.
  731. */
  732. diff = head - old;
  733. if (diff > md->mask / 2 || diff < 0) {
  734. struct timeval iv;
  735. unsigned long msecs;
  736. timersub(&this_read, &last_read, &iv);
  737. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  738. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  739. " Last read %lu msecs ago.\n", msecs);
  740. /*
  741. * head points to a known good entry, start there.
  742. */
  743. old = head;
  744. }
  745. last_read = this_read;
  746. for (; old != head;) {
  747. event_t *event = (event_t *)&data[old & md->mask];
  748. event_t event_copy;
  749. size_t size = event->header.size;
  750. /*
  751. * Event straddles the mmap boundary -- header should always
  752. * be inside due to u64 alignment of output.
  753. */
  754. if ((old & md->mask) + size != ((old + size) & md->mask)) {
  755. unsigned int offset = old;
  756. unsigned int len = min(sizeof(*event), size), cpy;
  757. void *dst = &event_copy;
  758. do {
  759. cpy = min(md->mask + 1 - (offset & md->mask), len);
  760. memcpy(dst, &data[offset & md->mask], cpy);
  761. offset += cpy;
  762. dst += cpy;
  763. len -= cpy;
  764. } while (len);
  765. event = &event_copy;
  766. }
  767. old += size;
  768. if (event->header.type == PERF_RECORD_SAMPLE) {
  769. int user =
  770. (event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK) == PERF_RECORD_MISC_USER;
  771. process_event(event->ip.ip, md->counter, user);
  772. }
  773. }
  774. md->prev = old;
  775. }
  776. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  777. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  778. static void mmap_read(void)
  779. {
  780. int i, counter;
  781. for (i = 0; i < nr_cpus; i++) {
  782. for (counter = 0; counter < nr_counters; counter++)
  783. mmap_read_counter(&mmap_array[i][counter]);
  784. }
  785. }
  786. int nr_poll;
  787. int group_fd;
  788. static void start_counter(int i, int counter)
  789. {
  790. struct perf_event_attr *attr;
  791. int cpu;
  792. cpu = profile_cpu;
  793. if (target_pid == -1 && profile_cpu == -1)
  794. cpu = i;
  795. attr = attrs + counter;
  796. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  797. attr->freq = freq;
  798. attr->inherit = (cpu < 0) && inherit;
  799. try_again:
  800. fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
  801. if (fd[i][counter] < 0) {
  802. int err = errno;
  803. if (err == EPERM)
  804. die("No permission - are you root?\n");
  805. /*
  806. * If it's cycles then fall back to hrtimer
  807. * based cpu-clock-tick sw counter, which
  808. * is always available even if no PMU support:
  809. */
  810. if (attr->type == PERF_TYPE_HARDWARE
  811. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  812. if (verbose)
  813. warning(" ... trying to fall back to cpu-clock-ticks\n");
  814. attr->type = PERF_TYPE_SOFTWARE;
  815. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  816. goto try_again;
  817. }
  818. printf("\n");
  819. error("perfcounter syscall returned with %d (%s)\n",
  820. fd[i][counter], strerror(err));
  821. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  822. exit(-1);
  823. }
  824. assert(fd[i][counter] >= 0);
  825. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  826. /*
  827. * First counter acts as the group leader:
  828. */
  829. if (group && group_fd == -1)
  830. group_fd = fd[i][counter];
  831. event_array[nr_poll].fd = fd[i][counter];
  832. event_array[nr_poll].events = POLLIN;
  833. nr_poll++;
  834. mmap_array[i][counter].counter = counter;
  835. mmap_array[i][counter].prev = 0;
  836. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  837. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  838. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  839. if (mmap_array[i][counter].base == MAP_FAILED)
  840. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  841. }
  842. static int __cmd_top(void)
  843. {
  844. pthread_t thread;
  845. int i, counter;
  846. int ret;
  847. for (i = 0; i < nr_cpus; i++) {
  848. group_fd = -1;
  849. for (counter = 0; counter < nr_counters; counter++)
  850. start_counter(i, counter);
  851. }
  852. /* Wait for a minimal set of events before starting the snapshot */
  853. poll(event_array, nr_poll, 100);
  854. mmap_read();
  855. if (pthread_create(&thread, NULL, display_thread, NULL)) {
  856. printf("Could not create display thread.\n");
  857. exit(-1);
  858. }
  859. if (realtime_prio) {
  860. struct sched_param param;
  861. param.sched_priority = realtime_prio;
  862. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  863. printf("Could not set realtime priority.\n");
  864. exit(-1);
  865. }
  866. }
  867. while (1) {
  868. int hits = samples;
  869. mmap_read();
  870. if (hits == samples)
  871. ret = poll(event_array, nr_poll, 100);
  872. }
  873. return 0;
  874. }
  875. static const char * const top_usage[] = {
  876. "perf top [<options>]",
  877. NULL
  878. };
  879. static const struct option options[] = {
  880. OPT_CALLBACK('e', "event", NULL, "event",
  881. "event selector. use 'perf list' to list available events",
  882. parse_events),
  883. OPT_INTEGER('c', "count", &default_interval,
  884. "event period to sample"),
  885. OPT_INTEGER('p', "pid", &target_pid,
  886. "profile events on existing pid"),
  887. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  888. "system-wide collection from all CPUs"),
  889. OPT_INTEGER('C', "CPU", &profile_cpu,
  890. "CPU to profile on"),
  891. OPT_STRING('k', "vmlinux", &vmlinux_name, "file", "vmlinux pathname"),
  892. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  893. "number of mmap data pages"),
  894. OPT_INTEGER('r', "realtime", &realtime_prio,
  895. "collect data with this RT SCHED_FIFO priority"),
  896. OPT_INTEGER('d', "delay", &delay_secs,
  897. "number of seconds to delay between refreshes"),
  898. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  899. "dump the symbol table used for profiling"),
  900. OPT_INTEGER('f', "count-filter", &count_filter,
  901. "only display functions with more events than this"),
  902. OPT_BOOLEAN('g', "group", &group,
  903. "put the counters into a counter group"),
  904. OPT_BOOLEAN('i', "inherit", &inherit,
  905. "child tasks inherit counters"),
  906. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  907. "symbol to annotate - requires -k option"),
  908. OPT_BOOLEAN('z', "zero", &zero,
  909. "zero history across updates"),
  910. OPT_INTEGER('F', "freq", &freq,
  911. "profile at this frequency"),
  912. OPT_INTEGER('E', "entries", &print_entries,
  913. "display this many functions"),
  914. OPT_BOOLEAN('v', "verbose", &verbose,
  915. "be more verbose (show counter open errors, etc)"),
  916. OPT_END()
  917. };
  918. int cmd_top(int argc, const char **argv, const char *prefix __used)
  919. {
  920. int counter;
  921. symbol__init();
  922. page_size = sysconf(_SC_PAGE_SIZE);
  923. argc = parse_options(argc, argv, options, top_usage, 0);
  924. if (argc)
  925. usage_with_options(top_usage, options);
  926. if (freq) {
  927. default_interval = freq;
  928. freq = 1;
  929. }
  930. /* CPU and PID are mutually exclusive */
  931. if (target_pid != -1 && profile_cpu != -1) {
  932. printf("WARNING: PID switch overriding CPU\n");
  933. sleep(1);
  934. profile_cpu = -1;
  935. }
  936. if (!nr_counters)
  937. nr_counters = 1;
  938. if (delay_secs < 1)
  939. delay_secs = 1;
  940. parse_symbols();
  941. parse_source(sym_filter_entry);
  942. /*
  943. * Fill in the ones not specifically initialized via -c:
  944. */
  945. for (counter = 0; counter < nr_counters; counter++) {
  946. if (attrs[counter].sample_period)
  947. continue;
  948. attrs[counter].sample_period = default_interval;
  949. }
  950. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  951. assert(nr_cpus <= MAX_NR_CPUS);
  952. assert(nr_cpus >= 0);
  953. if (target_pid != -1 || profile_cpu != -1)
  954. nr_cpus = 1;
  955. return __cmd_top();
  956. }