builtin-top.c 31 KB

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