builtin-top.c 27 KB

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