builtin-top.c 27 KB

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