builtin-top.c 32 KB

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