builtin-top.c 26 KB

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