builtin-top.c 27 KB

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