builtin-top.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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 "util/rbtree.h"
  25. #include "util/parse-options.h"
  26. #include "util/parse-events.h"
  27. #include <assert.h>
  28. #include <fcntl.h>
  29. #include <stdio.h>
  30. #include <errno.h>
  31. #include <time.h>
  32. #include <sched.h>
  33. #include <pthread.h>
  34. #include <sys/syscall.h>
  35. #include <sys/ioctl.h>
  36. #include <sys/poll.h>
  37. #include <sys/prctl.h>
  38. #include <sys/wait.h>
  39. #include <sys/uio.h>
  40. #include <sys/mman.h>
  41. #include <linux/unistd.h>
  42. #include <linux/types.h>
  43. static int system_wide = 0;
  44. static __u64 default_event_id[MAX_COUNTERS] = {
  45. EID(PERF_TYPE_SOFTWARE, PERF_COUNT_TASK_CLOCK),
  46. EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES),
  47. EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS),
  48. EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS),
  49. EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES),
  50. EID(PERF_TYPE_HARDWARE, PERF_COUNT_INSTRUCTIONS),
  51. EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_REFERENCES),
  52. EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_MISSES),
  53. };
  54. static int default_interval = 100000;
  55. static int event_count[MAX_COUNTERS];
  56. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  57. static __u64 count_filter = 5;
  58. static int print_entries = 15;
  59. static int target_pid = -1;
  60. static int profile_cpu = -1;
  61. static int nr_cpus = 0;
  62. static unsigned int realtime_prio = 0;
  63. static int group = 0;
  64. static unsigned int page_size;
  65. static unsigned int mmap_pages = 16;
  66. static int freq = 0;
  67. static char *sym_filter;
  68. static unsigned long filter_start;
  69. static unsigned long filter_end;
  70. static int delay_secs = 2;
  71. static int zero;
  72. static int dump_symtab;
  73. static const unsigned int default_count[] = {
  74. 1000000,
  75. 1000000,
  76. 10000,
  77. 10000,
  78. 1000000,
  79. 10000,
  80. };
  81. /*
  82. * Symbols
  83. */
  84. static uint64_t min_ip;
  85. static uint64_t max_ip = -1ll;
  86. struct sym_entry {
  87. struct rb_node rb_node;
  88. struct list_head node;
  89. unsigned long count[MAX_COUNTERS];
  90. unsigned long snap_count;
  91. double weight;
  92. int skip;
  93. };
  94. struct sym_entry *sym_filter_entry;
  95. struct dso *kernel_dso;
  96. /*
  97. * Symbols will be added here in record_ip and will get out
  98. * after decayed.
  99. */
  100. static LIST_HEAD(active_symbols);
  101. static pthread_mutex_t active_symbols_lock = PTHREAD_MUTEX_INITIALIZER;
  102. /*
  103. * Ordering weight: count-1 * count-2 * ... / count-n
  104. */
  105. static double sym_weight(const struct sym_entry *sym)
  106. {
  107. double weight = sym->snap_count;
  108. int counter;
  109. for (counter = 1; counter < nr_counters-1; counter++)
  110. weight *= sym->count[counter];
  111. weight /= (sym->count[counter] + 1);
  112. return weight;
  113. }
  114. static long samples;
  115. static long userspace_samples;
  116. static const char CONSOLE_CLEAR[] = "";
  117. static void __list_insert_active_sym(struct sym_entry *syme)
  118. {
  119. list_add(&syme->node, &active_symbols);
  120. }
  121. static void list_remove_active_sym(struct sym_entry *syme)
  122. {
  123. pthread_mutex_lock(&active_symbols_lock);
  124. list_del_init(&syme->node);
  125. pthread_mutex_unlock(&active_symbols_lock);
  126. }
  127. static void rb_insert_active_sym(struct rb_root *tree, struct sym_entry *se)
  128. {
  129. struct rb_node **p = &tree->rb_node;
  130. struct rb_node *parent = NULL;
  131. struct sym_entry *iter;
  132. while (*p != NULL) {
  133. parent = *p;
  134. iter = rb_entry(parent, struct sym_entry, rb_node);
  135. if (se->weight > iter->weight)
  136. p = &(*p)->rb_left;
  137. else
  138. p = &(*p)->rb_right;
  139. }
  140. rb_link_node(&se->rb_node, parent, p);
  141. rb_insert_color(&se->rb_node, tree);
  142. }
  143. static void print_sym_table(void)
  144. {
  145. int printed = 0, j;
  146. int counter;
  147. float samples_per_sec = samples/delay_secs;
  148. float ksamples_per_sec = (samples-userspace_samples)/delay_secs;
  149. float sum_ksamples = 0.0;
  150. struct sym_entry *syme, *n;
  151. struct rb_root tmp = RB_ROOT;
  152. struct rb_node *nd;
  153. samples = userspace_samples = 0;
  154. /* Sort the active symbols */
  155. pthread_mutex_lock(&active_symbols_lock);
  156. syme = list_entry(active_symbols.next, struct sym_entry, node);
  157. pthread_mutex_unlock(&active_symbols_lock);
  158. list_for_each_entry_safe_from(syme, n, &active_symbols, node) {
  159. syme->snap_count = syme->count[0];
  160. if (syme->snap_count != 0) {
  161. syme->weight = sym_weight(syme);
  162. rb_insert_active_sym(&tmp, syme);
  163. sum_ksamples += syme->snap_count;
  164. for (j = 0; j < nr_counters; j++)
  165. syme->count[j] = zero ? 0 : syme->count[j] * 7 / 8;
  166. } else
  167. list_remove_active_sym(syme);
  168. }
  169. puts(CONSOLE_CLEAR);
  170. printf(
  171. "------------------------------------------------------------------------------\n");
  172. printf( " PerfTop:%8.0f irqs/sec kernel:%4.1f%% [",
  173. samples_per_sec,
  174. 100.0 - (100.0*((samples_per_sec-ksamples_per_sec)/samples_per_sec)));
  175. if (nr_counters == 1) {
  176. printf("%d", event_count[0]);
  177. if (freq)
  178. printf("Hz ");
  179. else
  180. printf(" ");
  181. }
  182. for (counter = 0; counter < nr_counters; counter++) {
  183. if (counter)
  184. printf("/");
  185. printf("%s", event_name(counter));
  186. }
  187. printf( "], ");
  188. if (target_pid != -1)
  189. printf(" (target_pid: %d", target_pid);
  190. else
  191. printf(" (all");
  192. if (profile_cpu != -1)
  193. printf(", cpu: %d)\n", profile_cpu);
  194. else {
  195. if (target_pid != -1)
  196. printf(")\n");
  197. else
  198. printf(", %d CPUs)\n", nr_cpus);
  199. }
  200. printf("------------------------------------------------------------------------------\n\n");
  201. if (nr_counters == 1)
  202. printf(" samples pcnt");
  203. else
  204. printf(" weight samples pcnt");
  205. printf(" RIP kernel function\n"
  206. " ______ _______ _____ ________________ _______________\n\n"
  207. );
  208. for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
  209. struct sym_entry *syme = rb_entry(nd, struct sym_entry, rb_node);
  210. struct symbol *sym = (struct symbol *)(syme + 1);
  211. char *color = PERF_COLOR_NORMAL;
  212. double pcnt;
  213. if (++printed > print_entries || syme->snap_count < count_filter)
  214. continue;
  215. pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
  216. sum_ksamples));
  217. /*
  218. * We color high-overhead entries in red, low-overhead
  219. * entries in green - and keep the middle ground normal:
  220. */
  221. if (pcnt >= 5.0)
  222. color = PERF_COLOR_RED;
  223. if (pcnt < 0.5)
  224. color = PERF_COLOR_GREEN;
  225. if (nr_counters == 1)
  226. printf("%20.2f - ", syme->weight);
  227. else
  228. printf("%9.1f %10ld - ", syme->weight, syme->snap_count);
  229. color_fprintf(stdout, color, "%4.1f%%", pcnt);
  230. printf(" - %016llx : %s\n", sym->start, sym->name);
  231. }
  232. }
  233. static void *display_thread(void *arg)
  234. {
  235. struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
  236. int delay_msecs = delay_secs * 1000;
  237. printf("PerfTop refresh period: %d seconds\n", delay_secs);
  238. do {
  239. print_sym_table();
  240. } while (!poll(&stdin_poll, 1, delay_msecs) == 1);
  241. printf("key pressed - exiting.\n");
  242. exit(0);
  243. return NULL;
  244. }
  245. static int symbol_filter(struct dso *self, struct symbol *sym)
  246. {
  247. static int filter_match;
  248. struct sym_entry *syme;
  249. const char *name = sym->name;
  250. if (!strcmp(name, "_text") ||
  251. !strcmp(name, "_etext") ||
  252. !strcmp(name, "_sinittext") ||
  253. !strncmp("init_module", name, 11) ||
  254. !strncmp("cleanup_module", name, 14) ||
  255. strstr(name, "_text_start") ||
  256. strstr(name, "_text_end"))
  257. return 1;
  258. syme = dso__sym_priv(self, sym);
  259. /* Tag samples to be skipped. */
  260. if (!strcmp("default_idle", name) ||
  261. !strcmp("cpu_idle", name) ||
  262. !strcmp("enter_idle", name) ||
  263. !strcmp("exit_idle", name) ||
  264. !strcmp("mwait_idle", name))
  265. syme->skip = 1;
  266. if (filter_match == 1) {
  267. filter_end = sym->start;
  268. filter_match = -1;
  269. if (filter_end - filter_start > 10000) {
  270. fprintf(stderr,
  271. "hm, too large filter symbol <%s> - skipping.\n",
  272. sym_filter);
  273. fprintf(stderr, "symbol filter start: %016lx\n",
  274. filter_start);
  275. fprintf(stderr, " end: %016lx\n",
  276. filter_end);
  277. filter_end = filter_start = 0;
  278. sym_filter = NULL;
  279. sleep(1);
  280. }
  281. }
  282. if (filter_match == 0 && sym_filter && !strcmp(name, sym_filter)) {
  283. filter_match = 1;
  284. filter_start = sym->start;
  285. }
  286. return 0;
  287. }
  288. static int parse_symbols(void)
  289. {
  290. struct rb_node *node;
  291. struct symbol *sym;
  292. kernel_dso = dso__new("[kernel]", sizeof(struct sym_entry));
  293. if (kernel_dso == NULL)
  294. return -1;
  295. if (dso__load_kernel(kernel_dso, NULL, symbol_filter, 1) != 0)
  296. goto out_delete_dso;
  297. node = rb_first(&kernel_dso->syms);
  298. sym = rb_entry(node, struct symbol, rb_node);
  299. min_ip = sym->start;
  300. node = rb_last(&kernel_dso->syms);
  301. sym = rb_entry(node, struct symbol, rb_node);
  302. max_ip = sym->end;
  303. if (dump_symtab)
  304. dso__fprintf(kernel_dso, stderr);
  305. return 0;
  306. out_delete_dso:
  307. dso__delete(kernel_dso);
  308. kernel_dso = NULL;
  309. return -1;
  310. }
  311. #define TRACE_COUNT 3
  312. /*
  313. * Binary search in the histogram table and record the hit:
  314. */
  315. static void record_ip(uint64_t ip, int counter)
  316. {
  317. struct symbol *sym = dso__find_symbol(kernel_dso, ip);
  318. if (sym != NULL) {
  319. struct sym_entry *syme = dso__sym_priv(kernel_dso, sym);
  320. if (!syme->skip) {
  321. syme->count[counter]++;
  322. pthread_mutex_lock(&active_symbols_lock);
  323. if (list_empty(&syme->node) || !syme->node.next)
  324. __list_insert_active_sym(syme);
  325. pthread_mutex_unlock(&active_symbols_lock);
  326. return;
  327. }
  328. }
  329. samples--;
  330. }
  331. static void process_event(uint64_t ip, int counter)
  332. {
  333. samples++;
  334. if (ip < min_ip || ip > max_ip) {
  335. userspace_samples++;
  336. return;
  337. }
  338. record_ip(ip, counter);
  339. }
  340. struct mmap_data {
  341. int counter;
  342. void *base;
  343. unsigned int mask;
  344. unsigned int prev;
  345. };
  346. static unsigned int mmap_read_head(struct mmap_data *md)
  347. {
  348. struct perf_counter_mmap_page *pc = md->base;
  349. int head;
  350. head = pc->data_head;
  351. rmb();
  352. return head;
  353. }
  354. struct timeval last_read, this_read;
  355. static void mmap_read(struct mmap_data *md)
  356. {
  357. unsigned int head = mmap_read_head(md);
  358. unsigned int old = md->prev;
  359. unsigned char *data = md->base + page_size;
  360. int diff;
  361. gettimeofday(&this_read, NULL);
  362. /*
  363. * If we're further behind than half the buffer, there's a chance
  364. * the writer will bite our tail and mess up the samples under us.
  365. *
  366. * If we somehow ended up ahead of the head, we got messed up.
  367. *
  368. * In either case, truncate and restart at head.
  369. */
  370. diff = head - old;
  371. if (diff > md->mask / 2 || diff < 0) {
  372. struct timeval iv;
  373. unsigned long msecs;
  374. timersub(&this_read, &last_read, &iv);
  375. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  376. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  377. " Last read %lu msecs ago.\n", msecs);
  378. /*
  379. * head points to a known good entry, start there.
  380. */
  381. old = head;
  382. }
  383. last_read = this_read;
  384. for (; old != head;) {
  385. struct ip_event {
  386. struct perf_event_header header;
  387. __u64 ip;
  388. __u32 pid, target_pid;
  389. };
  390. struct mmap_event {
  391. struct perf_event_header header;
  392. __u32 pid, target_pid;
  393. __u64 start;
  394. __u64 len;
  395. __u64 pgoff;
  396. char filename[PATH_MAX];
  397. };
  398. typedef union event_union {
  399. struct perf_event_header header;
  400. struct ip_event ip;
  401. struct mmap_event mmap;
  402. } event_t;
  403. event_t *event = (event_t *)&data[old & md->mask];
  404. event_t event_copy;
  405. size_t size = event->header.size;
  406. /*
  407. * Event straddles the mmap boundary -- header should always
  408. * be inside due to u64 alignment of output.
  409. */
  410. if ((old & md->mask) + size != ((old + size) & md->mask)) {
  411. unsigned int offset = old;
  412. unsigned int len = min(sizeof(*event), size), cpy;
  413. void *dst = &event_copy;
  414. do {
  415. cpy = min(md->mask + 1 - (offset & md->mask), len);
  416. memcpy(dst, &data[offset & md->mask], cpy);
  417. offset += cpy;
  418. dst += cpy;
  419. len -= cpy;
  420. } while (len);
  421. event = &event_copy;
  422. }
  423. old += size;
  424. if (event->header.misc & PERF_EVENT_MISC_OVERFLOW) {
  425. if (event->header.type & PERF_SAMPLE_IP)
  426. process_event(event->ip.ip, md->counter);
  427. }
  428. }
  429. md->prev = old;
  430. }
  431. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  432. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  433. static int __cmd_top(void)
  434. {
  435. struct perf_counter_attr attr;
  436. pthread_t thread;
  437. int i, counter, group_fd, nr_poll = 0;
  438. unsigned int cpu;
  439. int ret;
  440. for (i = 0; i < nr_cpus; i++) {
  441. group_fd = -1;
  442. for (counter = 0; counter < nr_counters; counter++) {
  443. cpu = profile_cpu;
  444. if (target_pid == -1 && profile_cpu == -1)
  445. cpu = i;
  446. memset(&attr, 0, sizeof(attr));
  447. attr.config = event_id[counter];
  448. attr.sample_period = event_count[counter];
  449. attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  450. attr.freq = freq;
  451. fd[i][counter] = sys_perf_counter_open(&attr, target_pid, cpu, group_fd, 0);
  452. if (fd[i][counter] < 0) {
  453. int err = errno;
  454. error("syscall returned with %d (%s)\n",
  455. fd[i][counter], strerror(err));
  456. if (err == EPERM)
  457. printf("Are you root?\n");
  458. exit(-1);
  459. }
  460. assert(fd[i][counter] >= 0);
  461. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  462. /*
  463. * First counter acts as the group leader:
  464. */
  465. if (group && group_fd == -1)
  466. group_fd = fd[i][counter];
  467. event_array[nr_poll].fd = fd[i][counter];
  468. event_array[nr_poll].events = POLLIN;
  469. nr_poll++;
  470. mmap_array[i][counter].counter = counter;
  471. mmap_array[i][counter].prev = 0;
  472. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  473. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  474. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  475. if (mmap_array[i][counter].base == MAP_FAILED)
  476. die("failed to mmap with %d (%s)\n", errno, strerror(errno));
  477. }
  478. }
  479. if (pthread_create(&thread, NULL, display_thread, NULL)) {
  480. printf("Could not create display thread.\n");
  481. exit(-1);
  482. }
  483. if (realtime_prio) {
  484. struct sched_param param;
  485. param.sched_priority = realtime_prio;
  486. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  487. printf("Could not set realtime priority.\n");
  488. exit(-1);
  489. }
  490. }
  491. while (1) {
  492. int hits = samples;
  493. for (i = 0; i < nr_cpus; i++) {
  494. for (counter = 0; counter < nr_counters; counter++)
  495. mmap_read(&mmap_array[i][counter]);
  496. }
  497. if (hits == samples)
  498. ret = poll(event_array, nr_poll, 100);
  499. }
  500. return 0;
  501. }
  502. static const char * const top_usage[] = {
  503. "perf top [<options>]",
  504. NULL
  505. };
  506. static char events_help_msg[EVENTS_HELP_MAX];
  507. static const struct option options[] = {
  508. OPT_CALLBACK('e', "event", NULL, "event",
  509. events_help_msg, parse_events),
  510. OPT_INTEGER('c', "count", &default_interval,
  511. "event period to sample"),
  512. OPT_INTEGER('p', "pid", &target_pid,
  513. "profile events on existing pid"),
  514. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  515. "system-wide collection from all CPUs"),
  516. OPT_INTEGER('C', "CPU", &profile_cpu,
  517. "CPU to profile on"),
  518. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  519. "number of mmap data pages"),
  520. OPT_INTEGER('r', "realtime", &realtime_prio,
  521. "collect data with this RT SCHED_FIFO priority"),
  522. OPT_INTEGER('d', "delay", &delay_secs,
  523. "number of seconds to delay between refreshes"),
  524. OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
  525. "dump the symbol table used for profiling"),
  526. OPT_INTEGER('f', "count-filter", &count_filter,
  527. "only display functions with more events than this"),
  528. OPT_BOOLEAN('g', "group", &group,
  529. "put the counters into a counter group"),
  530. OPT_STRING('s', "sym-filter", &sym_filter, "pattern",
  531. "only display symbols matchig this pattern"),
  532. OPT_BOOLEAN('z', "zero", &group,
  533. "zero history across updates"),
  534. OPT_INTEGER('F', "freq", &freq,
  535. "profile at this frequency"),
  536. OPT_INTEGER('E', "entries", &print_entries,
  537. "display this many functions"),
  538. OPT_END()
  539. };
  540. int cmd_top(int argc, const char **argv, const char *prefix)
  541. {
  542. int counter;
  543. page_size = sysconf(_SC_PAGE_SIZE);
  544. create_events_help(events_help_msg);
  545. memcpy(event_id, default_event_id, sizeof(default_event_id));
  546. argc = parse_options(argc, argv, options, top_usage, 0);
  547. if (argc)
  548. usage_with_options(top_usage, options);
  549. if (freq) {
  550. default_interval = freq;
  551. freq = 1;
  552. }
  553. /* CPU and PID are mutually exclusive */
  554. if (target_pid != -1 && profile_cpu != -1) {
  555. printf("WARNING: PID switch overriding CPU\n");
  556. sleep(1);
  557. profile_cpu = -1;
  558. }
  559. if (!nr_counters) {
  560. nr_counters = 1;
  561. event_id[0] = 0;
  562. }
  563. if (delay_secs < 1)
  564. delay_secs = 1;
  565. for (counter = 0; counter < nr_counters; counter++) {
  566. if (event_count[counter])
  567. continue;
  568. event_count[counter] = default_interval;
  569. }
  570. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  571. assert(nr_cpus <= MAX_NR_CPUS);
  572. assert(nr_cpus >= 0);
  573. if (target_pid != -1 || profile_cpu != -1)
  574. nr_cpus = 1;
  575. parse_symbols();
  576. return __cmd_top();
  577. }