builtin-top.c 27 KB

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