builtin-top.c 26 KB

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