builtin-top.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. break;
  561. case 'e':
  562. prompt_integer(&print_entries, "Enter display entries (lines)");
  563. break;
  564. case 'E':
  565. if (nr_counters > 1) {
  566. int i;
  567. fprintf(stderr, "\nAvailable events:");
  568. for (i = 0; i < nr_counters; i++)
  569. fprintf(stderr, "\n\t%d %s", i, event_name(i));
  570. prompt_integer(&sym_counter, "Enter details event counter");
  571. if (sym_counter >= nr_counters) {
  572. fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(0));
  573. sym_counter = 0;
  574. sleep(1);
  575. }
  576. } else sym_counter = 0;
  577. break;
  578. case 'f':
  579. prompt_integer(&count_filter, "Enter display event count filter");
  580. break;
  581. case 'F':
  582. prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
  583. break;
  584. case 'q':
  585. case 'Q':
  586. printf("exiting.\n");
  587. exit(0);
  588. case 's':
  589. prompt_symbol(&sym_filter_entry, "Enter details symbol");
  590. break;
  591. case 'S':
  592. if (!sym_filter_entry)
  593. break;
  594. else {
  595. struct sym_entry *syme = sym_filter_entry;
  596. pthread_mutex_lock(&syme->source_lock);
  597. sym_filter_entry = NULL;
  598. __zero_source_counters(syme);
  599. pthread_mutex_unlock(&syme->source_lock);
  600. }
  601. break;
  602. case 'w':
  603. display_weighted = ~display_weighted;
  604. break;
  605. case 'z':
  606. zero = ~zero;
  607. break;
  608. default:
  609. break;
  610. }
  611. }
  612. static void *display_thread(void *arg __used)
  613. {
  614. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  615. struct termios tc, save;
  616. int delay_msecs, c;
  617. tcgetattr(0, &save);
  618. tc = save;
  619. tc.c_lflag &= ~(ICANON | ECHO);
  620. tc.c_cc[VMIN] = 0;
  621. tc.c_cc[VTIME] = 0;
  622. repeat:
  623. delay_msecs = delay_secs * 1000;
  624. tcsetattr(0, TCSANOW, &tc);
  625. /* trash return*/
  626. getc(stdin);
  627. do {
  628. print_sym_table();
  629. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  630. c = getc(stdin);
  631. tcsetattr(0, TCSAFLUSH, &save);
  632. handle_keypress(c);
  633. goto repeat;
  634. return NULL;
  635. }
  636. /* Tag samples to be skipped. */
  637. static const char *skip_symbols[] = {
  638. "default_idle",
  639. "cpu_idle",
  640. "enter_idle",
  641. "exit_idle",
  642. "mwait_idle",
  643. "mwait_idle_with_hints",
  644. "ppc64_runlatch_off",
  645. "pseries_dedicated_idle_sleep",
  646. NULL
  647. };
  648. static int symbol_filter(struct dso *self, struct symbol *sym)
  649. {
  650. struct sym_entry *syme;
  651. const char *name = sym->name;
  652. int i;
  653. /*
  654. * ppc64 uses function descriptors and appends a '.' to the
  655. * start of every instruction address. Remove it.
  656. */
  657. if (name[0] == '.')
  658. name++;
  659. if (!strcmp(name, "_text") ||
  660. !strcmp(name, "_etext") ||
  661. !strcmp(name, "_sinittext") ||
  662. !strncmp("init_module", name, 11) ||
  663. !strncmp("cleanup_module", name, 14) ||
  664. strstr(name, "_text_start") ||
  665. strstr(name, "_text_end"))
  666. return 1;
  667. syme = dso__sym_priv(self, sym);
  668. pthread_mutex_init(&syme->source_lock, NULL);
  669. if (!sym_filter_entry && sym_filter && !strcmp(name, sym_filter))
  670. sym_filter_entry = syme;
  671. for (i = 0; skip_symbols[i]; i++) {
  672. if (!strcmp(skip_symbols[i], name)) {
  673. syme->skip = 1;
  674. break;
  675. }
  676. }
  677. return 0;
  678. }
  679. static int parse_symbols(void)
  680. {
  681. struct rb_node *node;
  682. struct symbol *sym;
  683. int use_modules = vmlinux_name ? 1 : 0;
  684. kernel_dso = dso__new("[kernel]", sizeof(struct sym_entry));
  685. if (kernel_dso == NULL)
  686. return -1;
  687. if (dso__load_kernel(kernel_dso, vmlinux_name, symbol_filter, verbose, use_modules) <= 0)
  688. goto out_delete_dso;
  689. node = rb_first(&kernel_dso->syms);
  690. sym = rb_entry(node, struct symbol, rb_node);
  691. min_ip = sym->start;
  692. node = rb_last(&kernel_dso->syms);
  693. sym = rb_entry(node, struct symbol, rb_node);
  694. max_ip = sym->end;
  695. if (dump_symtab)
  696. dso__fprintf(kernel_dso, stderr);
  697. return 0;
  698. out_delete_dso:
  699. dso__delete(kernel_dso);
  700. kernel_dso = NULL;
  701. return -1;
  702. }
  703. /*
  704. * Binary search in the histogram table and record the hit:
  705. */
  706. static void record_ip(u64 ip, int counter)
  707. {
  708. struct symbol *sym = dso__find_symbol(kernel_dso, ip);
  709. if (sym != NULL) {
  710. struct sym_entry *syme = dso__sym_priv(kernel_dso, sym);
  711. if (!syme->skip) {
  712. syme->count[counter]++;
  713. record_precise_ip(syme, counter, ip);
  714. pthread_mutex_lock(&active_symbols_lock);
  715. if (list_empty(&syme->node) || !syme->node.next)
  716. __list_insert_active_sym(syme);
  717. pthread_mutex_unlock(&active_symbols_lock);
  718. return;
  719. }
  720. }
  721. samples--;
  722. }
  723. static void process_event(u64 ip, int counter, int user)
  724. {
  725. samples++;
  726. if (user) {
  727. userspace_samples++;
  728. return;
  729. }
  730. record_ip(ip, counter);
  731. }
  732. struct mmap_data {
  733. int counter;
  734. void *base;
  735. int mask;
  736. unsigned int prev;
  737. };
  738. static unsigned int mmap_read_head(struct mmap_data *md)
  739. {
  740. struct perf_event_mmap_page *pc = md->base;
  741. int head;
  742. head = pc->data_head;
  743. rmb();
  744. return head;
  745. }
  746. struct timeval last_read, this_read;
  747. static void mmap_read_counter(struct mmap_data *md)
  748. {
  749. unsigned int head = mmap_read_head(md);
  750. unsigned int old = md->prev;
  751. unsigned char *data = md->base + page_size;
  752. int diff;
  753. gettimeofday(&this_read, NULL);
  754. /*
  755. * If we're further behind than half the buffer, there's a chance
  756. * the writer will bite our tail and mess up the samples under us.
  757. *
  758. * If we somehow ended up ahead of the head, we got messed up.
  759. *
  760. * In either case, truncate and restart at head.
  761. */
  762. diff = head - old;
  763. if (diff > md->mask / 2 || diff < 0) {
  764. struct timeval iv;
  765. unsigned long msecs;
  766. timersub(&this_read, &last_read, &iv);
  767. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  768. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  769. " Last read %lu msecs ago.\n", msecs);
  770. /*
  771. * head points to a known good entry, start there.
  772. */
  773. old = head;
  774. }
  775. last_read = this_read;
  776. for (; old != head;) {
  777. event_t *event = (event_t *)&data[old & md->mask];
  778. event_t event_copy;
  779. size_t size = event->header.size;
  780. /*
  781. * Event straddles the mmap boundary -- header should always
  782. * be inside due to u64 alignment of output.
  783. */
  784. if ((old & md->mask) + size != ((old + size) & md->mask)) {
  785. unsigned int offset = old;
  786. unsigned int len = min(sizeof(*event), size), cpy;
  787. void *dst = &event_copy;
  788. do {
  789. cpy = min(md->mask + 1 - (offset & md->mask), len);
  790. memcpy(dst, &data[offset & md->mask], cpy);
  791. offset += cpy;
  792. dst += cpy;
  793. len -= cpy;
  794. } while (len);
  795. event = &event_copy;
  796. }
  797. old += size;
  798. if (event->header.type == PERF_RECORD_SAMPLE) {
  799. int user =
  800. (event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK) == PERF_RECORD_MISC_USER;
  801. process_event(event->ip.ip, md->counter, user);
  802. }
  803. }
  804. md->prev = old;
  805. }
  806. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  807. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  808. static void mmap_read(void)
  809. {
  810. int i, counter;
  811. for (i = 0; i < nr_cpus; i++) {
  812. for (counter = 0; counter < nr_counters; counter++)
  813. mmap_read_counter(&mmap_array[i][counter]);
  814. }
  815. }
  816. int nr_poll;
  817. int group_fd;
  818. static void start_counter(int i, int counter)
  819. {
  820. struct perf_event_attr *attr;
  821. int cpu;
  822. cpu = profile_cpu;
  823. if (target_pid == -1 && profile_cpu == -1)
  824. cpu = i;
  825. attr = attrs + counter;
  826. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  827. attr->freq = freq;
  828. attr->inherit = (cpu < 0) && inherit;
  829. try_again:
  830. fd[i][counter] = sys_perf_event_open(attr, target_pid, cpu, group_fd, 0);
  831. if (fd[i][counter] < 0) {
  832. int err = errno;
  833. if (err == EPERM)
  834. die("No permission - are you root?\n");
  835. /*
  836. * If it's cycles then fall back to hrtimer
  837. * based cpu-clock-tick sw counter, which
  838. * is always available even if no PMU support:
  839. */
  840. if (attr->type == PERF_TYPE_HARDWARE
  841. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  842. if (verbose)
  843. warning(" ... trying to fall back to cpu-clock-ticks\n");
  844. attr->type = PERF_TYPE_SOFTWARE;
  845. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  846. goto try_again;
  847. }
  848. printf("\n");
  849. error("perfcounter syscall returned with %d (%s)\n",
  850. fd[i][counter], strerror(err));
  851. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  852. exit(-1);
  853. }
  854. assert(fd[i][counter] >= 0);
  855. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  856. /*
  857. * First counter acts as the group leader:
  858. */
  859. if (group && group_fd == -1)
  860. group_fd = fd[i][counter];
  861. event_array[nr_poll].fd = fd[i][counter];
  862. event_array[nr_poll].events = POLLIN;
  863. nr_poll++;
  864. mmap_array[i][counter].counter = counter;
  865. mmap_array[i][counter].prev = 0;
  866. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  867. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  868. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  869. if (mmap_array[i][counter].base == MAP_FAILED)
  870. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  871. }
  872. static int __cmd_top(void)
  873. {
  874. pthread_t thread;
  875. int i, counter;
  876. int ret;
  877. for (i = 0; i < nr_cpus; i++) {
  878. group_fd = -1;
  879. for (counter = 0; counter < nr_counters; counter++)
  880. start_counter(i, counter);
  881. }
  882. /* Wait for a minimal set of events before starting the snapshot */
  883. poll(event_array, nr_poll, 100);
  884. mmap_read();
  885. if (pthread_create(&thread, NULL, display_thread, NULL)) {
  886. printf("Could not create display thread.\n");
  887. exit(-1);
  888. }
  889. if (realtime_prio) {
  890. struct sched_param param;
  891. param.sched_priority = realtime_prio;
  892. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  893. printf("Could not set realtime priority.\n");
  894. exit(-1);
  895. }
  896. }
  897. while (1) {
  898. int hits = samples;
  899. mmap_read();
  900. if (hits == samples)
  901. ret = poll(event_array, nr_poll, 100);
  902. }
  903. return 0;
  904. }
  905. static const char * const top_usage[] = {
  906. "perf top [<options>]",
  907. NULL
  908. };
  909. static const struct option options[] = {
  910. OPT_CALLBACK('e', "event", NULL, "event",
  911. "event selector. use 'perf list' to list available events",
  912. parse_events),
  913. OPT_INTEGER('c', "count", &default_interval,
  914. "event period to sample"),
  915. OPT_INTEGER('p', "pid", &target_pid,
  916. "profile events on existing pid"),
  917. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  918. "system-wide collection from all CPUs"),
  919. OPT_INTEGER('C', "CPU", &profile_cpu,
  920. "CPU to profile on"),
  921. OPT_STRING('k', "vmlinux", &vmlinux_name, "file", "vmlinux pathname"),
  922. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  923. "number of mmap data pages"),
  924. OPT_INTEGER('r', "realtime", &realtime_prio,
  925. "collect data with this RT SCHED_FIFO priority"),
  926. OPT_INTEGER('d', "delay", &delay_secs,
  927. "number of seconds to delay between refreshes"),
  928. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  929. "dump the symbol table used for profiling"),
  930. OPT_INTEGER('f', "count-filter", &count_filter,
  931. "only display functions with more events than this"),
  932. OPT_BOOLEAN('g', "group", &group,
  933. "put the counters into a counter group"),
  934. OPT_BOOLEAN('i', "inherit", &inherit,
  935. "child tasks inherit counters"),
  936. OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
  937. "symbol to annotate - requires -k option"),
  938. OPT_BOOLEAN('z', "zero", &zero,
  939. "zero history across updates"),
  940. OPT_INTEGER('F', "freq", &freq,
  941. "profile at this frequency"),
  942. OPT_INTEGER('E', "entries", &print_entries,
  943. "display this many functions"),
  944. OPT_BOOLEAN('v', "verbose", &verbose,
  945. "be more verbose (show counter open errors, etc)"),
  946. OPT_END()
  947. };
  948. int cmd_top(int argc, const char **argv, const char *prefix __used)
  949. {
  950. int counter;
  951. symbol__init();
  952. page_size = sysconf(_SC_PAGE_SIZE);
  953. argc = parse_options(argc, argv, options, top_usage, 0);
  954. if (argc)
  955. usage_with_options(top_usage, options);
  956. if (freq) {
  957. default_interval = freq;
  958. freq = 1;
  959. }
  960. /* CPU and PID are mutually exclusive */
  961. if (target_pid != -1 && profile_cpu != -1) {
  962. printf("WARNING: PID switch overriding CPU\n");
  963. sleep(1);
  964. profile_cpu = -1;
  965. }
  966. if (!nr_counters)
  967. nr_counters = 1;
  968. if (delay_secs < 1)
  969. delay_secs = 1;
  970. parse_symbols();
  971. parse_source(sym_filter_entry);
  972. /*
  973. * Fill in the ones not specifically initialized via -c:
  974. */
  975. for (counter = 0; counter < nr_counters; counter++) {
  976. if (attrs[counter].sample_period)
  977. continue;
  978. attrs[counter].sample_period = default_interval;
  979. }
  980. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  981. assert(nr_cpus <= MAX_NR_CPUS);
  982. assert(nr_cpus >= 0);
  983. if (target_pid != -1 || profile_cpu != -1)
  984. nr_cpus = 1;
  985. return __cmd_top();
  986. }