builtin-top.c 27 KB

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