builtin-top.c 16 KB

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