builtin-top.c 27.8 KB
Newer Older
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 * builtin-top.c
 *
 * Builtin top command: Display a continuously updated profile of
 * any workload, CPU or specific PID.
 *
 * Copyright (C) 2008, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
 *
 * Improvements and fixes by:
 *
 *   Arjan van de Ven <arjan@linux.intel.com>
 *   Yanmin Zhang <yanmin.zhang@intel.com>
 *   Wu Fengguang <fengguang.wu@intel.com>
 *   Mike Galbraith <efault@gmx.de>
 *   Paul Mackerras <paulus@samba.org>
 *
 * Released under the GPL v2. (and only v2, not any later version)
18
 */
19
#include "builtin.h"
20

21
#include "perf.h"
22

23
#include "util/annotate.h"
24
#include "util/cache.h"
25
#include "util/color.h"
26
#include "util/evlist.h"
27
#include "util/evsel.h"
28 29
#include "util/session.h"
#include "util/symbol.h"
30
#include "util/thread.h"
31
#include "util/thread_map.h"
32
#include "util/top.h"
33
#include "util/util.h"
34
#include <linux/rbtree.h>
35 36
#include "util/parse-options.h"
#include "util/parse-events.h"
37
#include "util/cpumap.h"
38
#include "util/xyarray.h"
39

40 41
#include "util/debug.h"

42 43
#include <assert.h>
#include <fcntl.h>
44

45
#include <stdio.h>
46 47
#include <termios.h>
#include <unistd.h>
48
#include <inttypes.h>
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <errno.h>
#include <time.h>
#include <sched.h>

#include <sys/syscall.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <sys/uio.h>
#include <sys/mman.h>

#include <linux/unistd.h>
#include <linux/types.h>

65 66 67 68 69 70 71 72
static struct perf_top top = {
	.count_filter		= 5,
	.delay_secs		= 2,
	.display_weighted	= -1,
	.target_pid		= -1,
	.target_tid		= -1,
	.active_symbols		= LIST_HEAD_INIT(top.active_symbols),
	.active_symbols_lock	= PTHREAD_MUTEX_INITIALIZER,
73
	.active_symbols_cond	= PTHREAD_COND_INITIALIZER,
74 75
	.freq			= 1000, /* 1 KHz */
};
76

77
static bool			system_wide			=  false;
78

79 80
static bool			use_tui, use_stdio;

81
static int			default_interval		=      0;
82

83
static bool			kptr_restrict_warned;
84
static bool			vmlinux_warned;
85
static bool			inherit				=  false;
86
static int			realtime_prio			=      0;
87
static bool			group				=  false;
88
static unsigned int		page_size;
89
static unsigned int		mmap_pages			=    128;
90

91
static bool			dump_symtab                     =  false;
92

93
static struct winsize		winsize;
94

95
static const char		*sym_filter			=   NULL;
96
struct sym_entry		*sym_filter_entry_sched		=   NULL;
97
static int			sym_pcnt_filter			=      5;
98

99 100 101 102
/*
 * Source functions
 */

103
void get_term_dimensions(struct winsize *ws)
104
{
105 106 107 108 109 110 111 112 113 114
	char *s = getenv("LINES");

	if (s != NULL) {
		ws->ws_row = atoi(s);
		s = getenv("COLUMNS");
		if (s != NULL) {
			ws->ws_col = atoi(s);
			if (ws->ws_row && ws->ws_col)
				return;
		}
115
	}
116 117 118 119
#ifdef TIOCGWINSZ
	if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
	    ws->ws_row && ws->ws_col)
		return;
120
#endif
121 122
	ws->ws_row = 25;
	ws->ws_col = 80;
123 124
}

125
static void update_print_entries(struct winsize *ws)
126
{
127
	top.print_entries = ws->ws_row;
128

129 130
	if (top.print_entries > 9)
		top.print_entries -= 9;
131 132 133 134
}

static void sig_winch_handler(int sig __used)
{
135 136
	get_term_dimensions(&winsize);
	update_print_entries(&winsize);
137 138
}

139
static int parse_source(struct sym_entry *syme)
140 141
{
	struct symbol *sym;
142
	struct annotation *notes;
143
	struct map *map;
144
	int err = -1;
145 146

	if (!syme)
147 148 149 150 151 152 153 154
		return -1;

	sym = sym_entry__symbol(syme);
	map = syme->map;

	/*
	 * We can't annotate with just /proc/kallsyms
	 */
155
	if (map->dso->symtab_type == SYMTAB__KALLSYMS) {
156 157 158
		pr_err("Can't annotate %s: No vmlinux file was found in the "
		       "path\n", sym->name);
		sleep(1);
159
		return -1;
160 161
	}

162 163 164
	notes = symbol__annotation(sym);
	if (notes->src != NULL) {
		pthread_mutex_lock(&notes->lock);
165 166 167
		goto out_assign;
	}

168
	pthread_mutex_lock(&notes->lock);
169

170
	if (symbol__alloc_hist(sym, top.evlist->nr_entries) < 0) {
171
		pthread_mutex_unlock(&notes->lock);
172 173
		pr_err("Not enough memory for annotating '%s' symbol!\n",
		       sym->name);
174
		sleep(1);
175
		return err;
176
	}
177

178
	err = symbol__annotate(sym, syme->map, 0);
179
	if (err == 0) {
180
out_assign:
181
		top.sym_filter_entry = syme;
182
	}
183

184
	pthread_mutex_unlock(&notes->lock);
185
	return err;
186 187 188 189
}

static void __zero_source_counters(struct sym_entry *syme)
{
190 191
	struct symbol *sym = sym_entry__symbol(syme);
	symbol__annotate_zero_histograms(sym);
192 193
}

194 195
static void record_precise_ip(struct sym_entry *syme, struct map *map,
			      int counter, u64 ip)
196
{
197 198 199
	struct annotation *notes;
	struct symbol *sym;

200
	if (syme != top.sym_filter_entry)
201 202
		return;

203 204 205 206
	sym = sym_entry__symbol(syme);
	notes = symbol__annotation(sym);

	if (pthread_mutex_trylock(&notes->lock))
207 208
		return;

209 210
	ip = map->map_ip(map, ip);
	symbol__inc_addr_samples(sym, map, counter, ip);
211

212
	pthread_mutex_unlock(&notes->lock);
213 214 215 216
}

static void show_details(struct sym_entry *syme)
{
217
	struct annotation *notes;
218
	struct symbol *symbol;
219
	int more;
220 221 222 223

	if (!syme)
		return;

224
	symbol = sym_entry__symbol(syme);
225 226 227 228 229 230
	notes = symbol__annotation(symbol);

	pthread_mutex_lock(&notes->lock);

	if (notes->src == NULL)
		goto out_unlock;
231

232
	printf("Showing %s for %s\n", event_name(top.sym_evsel), symbol->name);
233 234
	printf("  Events  Pcnt (>=%d%%)\n", sym_pcnt_filter);

235
	more = symbol__annotate_printf(symbol, syme->map, top.sym_evsel->idx,
236
				       0, sym_pcnt_filter, top.print_entries, 4);
237 238 239
	if (top.zero)
		symbol__annotate_zero_histogram(symbol, top.sym_evsel->idx);
	else
240
		symbol__annotate_decay_histogram(symbol, top.sym_evsel->idx);
241
	if (more != 0)
242
		printf("%d lines not displayed, maybe increase display entries [e]\n", more);
243 244
out_unlock:
	pthread_mutex_unlock(&notes->lock);
245
}
246 247 248

static const char		CONSOLE_CLEAR[] = "";

249
static void __list_insert_active_sym(struct sym_entry *syme)
250
{
251
	list_add(&syme->node, &top.active_symbols);
252
}
253

254
static void print_sym_table(struct perf_session *session)
255
{
256 257
	char bf[160];
	int printed = 0;
258
	struct rb_node *nd;
259 260
	struct sym_entry *syme;
	struct rb_root tmp = RB_ROOT;
261
	const int win_width = winsize.ws_col - 1;
262 263
	int sym_width, dso_width, dso_short_width;
	float sum_ksamples = perf_top__decay_samples(&top, &tmp);
264

265
	puts(CONSOLE_CLEAR);
266

267 268
	perf_top__header_snprintf(&top, bf, sizeof(bf));
	printf("%s\n", bf);
269

270
	perf_top__reset_sample_counters(&top);
271

272
	printf("%-*.*s\n", win_width, win_width, graph_dotted_line);
273

274 275 276 277 278 279
	if (session->hists.stats.total_lost != 0) {
		color_fprintf(stdout, PERF_COLOR_RED, "WARNING:");
		printf(" LOST %" PRIu64 " events, Check IO/CPU overload\n",
		       session->hists.stats.total_lost);
	}

280 281
	if (top.sym_filter_entry) {
		show_details(top.sym_filter_entry);
282 283 284
		return;
	}

285 286
	perf_top__find_widths(&top, &tmp, &dso_width, &dso_short_width,
			      &sym_width);
287

288 289 290 291 292
	if (sym_width + dso_width > winsize.ws_col - 29) {
		dso_width = dso_short_width;
		if (sym_width + dso_width > winsize.ws_col - 29)
			sym_width = winsize.ws_col - dso_width - 29;
	}
293
	putchar('\n');
294
	if (top.evlist->nr_entries == 1)
295
		printf("             samples  pcnt");
296
	else
297
		printf("   weight    samples  pcnt");
298

299 300
	if (verbose)
		printf("         RIP       ");
301
	printf(" %-*.*s DSO\n", sym_width, sym_width, "function");
302
	printf("   %s    _______ _____",
303
	       top.evlist->nr_entries == 1 ? "      " : "______");
304
	if (verbose)
305
		printf(" ________________");
306
	printf(" %-*.*s", sym_width, sym_width, graph_line);
307
	printf(" %-*.*s", dso_width, dso_width, graph_line);
308
	puts("\n");
309

310
	for (nd = rb_first(&tmp); nd; nd = rb_next(nd)) {
311
		struct symbol *sym;
312
		double pcnt;
313

314
		syme = rb_entry(nd, struct sym_entry, rb_node);
315
		sym = sym_entry__symbol(syme);
316 317
		if (++printed > top.print_entries ||
		    (int)syme->snap_count < top.count_filter)
318
			continue;
319

320 321
		pcnt = 100.0 - (100.0 * ((sum_ksamples - syme->snap_count) /
					 sum_ksamples));
322

323
		if (top.evlist->nr_entries == 1 || !top.display_weighted)
324
			printf("%20.2f ", syme->weight);
325
		else
326
			printf("%9.1f %10ld ", syme->weight, syme->snap_count);
327

328
		percent_color_fprintf(stdout, "%4.1f%%", pcnt);
329
		if (verbose)
330
			printf(" %016" PRIx64, sym->start);
331
		printf(" %-*.*s", sym_width, sym_width, sym->name);
332 333 334 335
		printf(" %-*.*s\n", dso_width, dso_width,
		       dso_width >= syme->map->dso->long_name_len ?
					syme->map->dso->long_name :
					syme->map->dso->short_name);
336 337 338
	}
}

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
static void prompt_integer(int *target, const char *msg)
{
	char *buf = malloc(0), *p;
	size_t dummy = 0;
	int tmp;

	fprintf(stdout, "\n%s: ", msg);
	if (getline(&buf, &dummy, stdin) < 0)
		return;

	p = strchr(buf, '\n');
	if (p)
		*p = 0;

	p = buf;
	while(*p) {
		if (!isdigit(*p))
			goto out_free;
		p++;
	}
	tmp = strtoul(buf, NULL, 10);
	*target = tmp;
out_free:
	free(buf);
}

static void prompt_percent(int *target, const char *msg)
{
	int tmp = 0;

	prompt_integer(&tmp, msg);
	if (tmp >= 0 && tmp <= 100)
		*target = tmp;
}

static void prompt_symbol(struct sym_entry **target, const char *msg)
{
	char *buf = malloc(0), *p;
	struct sym_entry *syme = *target, *n, *found = NULL;
	size_t dummy = 0;

	/* zero counters of active symbol */
	if (syme) {
		__zero_source_counters(syme);
		*target = NULL;
	}

	fprintf(stdout, "\n%s: ", msg);
	if (getline(&buf, &dummy, stdin) < 0)
		goto out_free;

	p = strchr(buf, '\n');
	if (p)
		*p = 0;

394 395 396
	pthread_mutex_lock(&top.active_symbols_lock);
	syme = list_entry(top.active_symbols.next, struct sym_entry, node);
	pthread_mutex_unlock(&top.active_symbols_lock);
397

398
	list_for_each_entry_safe_from(syme, n, &top.active_symbols, node) {
399
		struct symbol *sym = sym_entry__symbol(syme);
400 401 402 403 404 405 406 407

		if (!strcmp(buf, sym->name)) {
			found = syme;
			break;
		}
	}

	if (!found) {
408
		fprintf(stderr, "Sorry, %s is not active.\n", buf);
409 410 411 412 413 414 415 416 417
		sleep(1);
		return;
	} else
		parse_source(found);

out_free:
	free(buf);
}

418
static void print_mapped_keys(void)
419
{
420 421
	char *name = NULL;

422 423
	if (top.sym_filter_entry) {
		struct symbol *sym = sym_entry__symbol(top.sym_filter_entry);
424 425 426 427
		name = sym->name;
	}

	fprintf(stdout, "\nMapped keys:\n");
428 429
	fprintf(stdout, "\t[d]     display refresh delay.             \t(%d)\n", top.delay_secs);
	fprintf(stdout, "\t[e]     display entries (lines).           \t(%d)\n", top.print_entries);
430

431 432
	if (top.evlist->nr_entries > 1)
		fprintf(stdout, "\t[E]     active event counter.              \t(%s)\n", event_name(top.sym_evsel));
433

434
	fprintf(stdout, "\t[f]     profile display filter (count).    \t(%d)\n", top.count_filter);
435

436 437 438
	fprintf(stdout, "\t[F]     annotate display filter (percent). \t(%d%%)\n", sym_pcnt_filter);
	fprintf(stdout, "\t[s]     annotate symbol.                   \t(%s)\n", name?: "NULL");
	fprintf(stdout, "\t[S]     stop annotation.\n");
439

440 441
	if (top.evlist->nr_entries > 1)
		fprintf(stdout, "\t[w]     toggle display weighted/count[E]r. \t(%d)\n", top.display_weighted ? 1 : 0);
442

443
	fprintf(stdout,
444
		"\t[K]     hide kernel_symbols symbols.     \t(%s)\n",
445
		top.hide_kernel_symbols ? "yes" : "no");
446 447
	fprintf(stdout,
		"\t[U]     hide user symbols.               \t(%s)\n",
448 449
		top.hide_user_symbols ? "yes" : "no");
	fprintf(stdout, "\t[z]     toggle sample zeroing.             \t(%d)\n", top.zero ? 1 : 0);
450 451 452 453 454 455 456 457 458 459 460 461
	fprintf(stdout, "\t[qQ]    quit.\n");
}

static int key_mapped(int c)
{
	switch (c) {
		case 'd':
		case 'e':
		case 'f':
		case 'z':
		case 'q':
		case 'Q':
462 463
		case 'K':
		case 'U':
464 465 466
		case 'F':
		case 's':
		case 'S':
467 468 469
			return 1;
		case 'E':
		case 'w':
470
			return top.evlist->nr_entries > 1 ? 1 : 0;
471 472
		default:
			break;
473 474 475
	}

	return 0;
476 477
}

478
static void handle_keypress(struct perf_session *session, int c)
479
{
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
	if (!key_mapped(c)) {
		struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
		struct termios tc, save;

		print_mapped_keys();
		fprintf(stdout, "\nEnter selection, or unmapped key to continue: ");
		fflush(stdout);

		tcgetattr(0, &save);
		tc = save;
		tc.c_lflag &= ~(ICANON | ECHO);
		tc.c_cc[VMIN] = 0;
		tc.c_cc[VTIME] = 0;
		tcsetattr(0, TCSANOW, &tc);

		poll(&stdin_poll, 1, -1);
		c = getc(stdin);

		tcsetattr(0, TCSAFLUSH, &save);
		if (!key_mapped(c))
			return;
	}

503 504
	switch (c) {
		case 'd':
505 506 507
			prompt_integer(&top.delay_secs, "Enter display delay");
			if (top.delay_secs < 1)
				top.delay_secs = 1;
508 509
			break;
		case 'e':
510 511
			prompt_integer(&top.print_entries, "Enter display entries (lines)");
			if (top.print_entries == 0) {
512
				sig_winch_handler(SIGWINCH);
513 514 515
				signal(SIGWINCH, sig_winch_handler);
			} else
				signal(SIGWINCH, SIG_DFL);
516 517
			break;
		case 'E':
518
			if (top.evlist->nr_entries > 1) {
519 520 521
				/* Select 0 as the default event: */
				int counter = 0;

522
				fprintf(stderr, "\nAvailable events:");
523

524 525
				list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
					fprintf(stderr, "\n\t%d %s", top.sym_evsel->idx, event_name(top.sym_evsel));
526

527
				prompt_integer(&counter, "Enter details event counter");
528

529
				if (counter >= top.evlist->nr_entries) {
530 531
					top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
					fprintf(stderr, "Sorry, no such event, using %s.\n", event_name(top.sym_evsel));
532
					sleep(1);
533
					break;
534
				}
535
				list_for_each_entry(top.sym_evsel, &top.evlist->entries, node)
536
					if (top.sym_evsel->idx == counter)
537
						break;
538 539
			} else
				top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
540 541
			break;
		case 'f':
542
			prompt_integer(&top.count_filter, "Enter display event count filter");
543 544 545 546
			break;
		case 'F':
			prompt_percent(&sym_pcnt_filter, "Enter details display event filter (percent)");
			break;
547
		case 'K':
548
			top.hide_kernel_symbols = !top.hide_kernel_symbols;
549
			break;
550 551 552
		case 'q':
		case 'Q':
			printf("exiting.\n");
553
			if (dump_symtab)
554
				perf_session__fprintf_dsos(session, stderr);
555 556
			exit(0);
		case 's':
557
			prompt_symbol(&top.sym_filter_entry, "Enter details symbol");
558 559
			break;
		case 'S':
560
			if (!top.sym_filter_entry)
561 562
				break;
			else {
563
				struct sym_entry *syme = top.sym_filter_entry;
564

565
				top.sym_filter_entry = NULL;
566 567 568
				__zero_source_counters(syme);
			}
			break;
569
		case 'U':
570
			top.hide_user_symbols = !top.hide_user_symbols;
571
			break;
572
		case 'w':
573
			top.display_weighted = ~top.display_weighted;
574
			break;
575
		case 'z':
576
			top.zero = !top.zero;
577
			break;
578 579
		default:
			break;
580 581 582
	}
}

583 584
static void *display_thread_tui(void *arg __used)
{
585 586 587 588 589 590 591 592 593 594 595
	int err = 0;
	pthread_mutex_lock(&top.active_symbols_lock);
	while (list_empty(&top.active_symbols)) {
		err = pthread_cond_wait(&top.active_symbols_cond,
					&top.active_symbols_lock);
		if (err)
			break;
	}
	pthread_mutex_unlock(&top.active_symbols_lock);
	if (!err)
		perf_top__tui_browser(&top);
596 597 598 599 600
	exit_browser(0);
	exit(0);
	return NULL;
}

601
static void *display_thread(void *arg __used)
602
{
603
	struct pollfd stdin_poll = { .fd = 0, .events = POLLIN };
604 605
	struct termios tc, save;
	int delay_msecs, c;
606
	struct perf_session *session = (struct perf_session *) arg;
607 608 609 610 611 612

	tcgetattr(0, &save);
	tc = save;
	tc.c_lflag &= ~(ICANON | ECHO);
	tc.c_cc[VMIN] = 0;
	tc.c_cc[VTIME] = 0;
613

614
repeat:
615
	delay_msecs = top.delay_secs * 1000;
616 617 618
	tcsetattr(0, TCSANOW, &tc);
	/* trash return*/
	getc(stdin);
619

620
	do {
621
		print_sym_table(session);
622 623
	} while (!poll(&stdin_poll, 1, delay_msecs) == 1);

624 625 626
	c = getc(stdin);
	tcsetattr(0, TCSAFLUSH, &save);

627
	handle_keypress(session, c);
628
	goto repeat;
629 630 631 632

	return NULL;
}

633
/* Tag samples to be skipped. */
634
static const char *skip_symbols[] = {
635
	"default_idle",
636
	"native_safe_halt",
637 638 639 640
	"cpu_idle",
	"enter_idle",
	"exit_idle",
	"mwait_idle",
641
	"mwait_idle_with_hints",
642
	"poll_idle",
643 644
	"ppc64_runlatch_off",
	"pseries_dedicated_idle_sleep",
645 646 647
	NULL
};

648
static int symbol_filter(struct map *map, struct symbol *sym)
649
{
650 651
	struct sym_entry *syme;
	const char *name = sym->name;
652
	int i;
653

654 655 656 657 658 659 660
	/*
	 * ppc64 uses function descriptors and appends a '.' to the
	 * start of every instruction address. Remove it.
	 */
	if (name[0] == '.')
		name++;

661 662 663 664 665 666 667
	if (!strcmp(name, "_text") ||
	    !strcmp(name, "_etext") ||
	    !strcmp(name, "_sinittext") ||
	    !strncmp("init_module", name, 11) ||
	    !strncmp("cleanup_module", name, 14) ||
	    strstr(name, "_text_start") ||
	    strstr(name, "_text_end"))
668 669
		return 1;

670
	syme = symbol__priv(sym);
671
	syme->map = map;
672
	symbol__annotate_init(map, sym);
673

674
	if (!top.sym_filter_entry && sym_filter && !strcmp(name, sym_filter)) {
675 676 677 678
		/* schedule initial sym_filter_entry setup */
		sym_filter_entry_sched = syme;
		sym_filter = NULL;
	}
679

680 681
	for (i = 0; skip_symbols[i]; i++) {
		if (!strcmp(skip_symbols[i], name)) {
682
			sym->ignore = true;
683 684 685
			break;
		}
	}
686 687 688 689

	return 0;
}

690 691 692
static void perf_event__process_sample(const union perf_event *event,
				       struct perf_sample *sample,
				       struct perf_session *session)
693
{
694
	u64 ip = event->ip.ip;
695
	struct sym_entry *syme;
696
	struct addr_location al;
697
	struct machine *machine;
698
	u8 origin = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
699

700
	++top.samples;
701

702
	switch (origin) {
703
	case PERF_RECORD_MISC_USER:
704 705
		++top.us_samples;
		if (top.hide_user_symbols)
706
			return;
707
		machine = perf_session__find_host_machine(session);
708
		break;
709
	case PERF_RECORD_MISC_KERNEL:
710 711
		++top.kernel_samples;
		if (top.hide_kernel_symbols)
712
			return;
713
		machine = perf_session__find_host_machine(session);
714 715
		break;
	case PERF_RECORD_MISC_GUEST_KERNEL:
716
		++top.guest_kernel_samples;
717
		machine = perf_session__find_machine(session, event->ip.pid);
718
		break;
719
	case PERF_RECORD_MISC_GUEST_USER:
720
		++top.guest_us_samples;
721 722 723 724 725
		/*
		 * TODO: we don't process guest user from host side
		 * except simple counting.
		 */
		return;
726 727 728 729
	default:
		return;
	}

730
	if (!machine && perf_guest) {
731
		pr_err("Can't find guest [%d]'s kernel information\n",
732
			event->ip.pid);
733 734 735
		return;
	}

736
	if (event->header.misc & PERF_RECORD_MISC_EXACT_IP)
737
		top.exact_samples++;
738

739 740
	if (perf_event__preprocess_sample(event, session, &al, sample,
					  symbol_filter) < 0 ||
741
	    al.filtered)
742
		return;
743

744 745 746 747 748 749 750 751 752 753 754 755 756 757
	if (!kptr_restrict_warned &&
	    symbol_conf.kptr_restrict &&
	    al.cpumode == PERF_RECORD_MISC_KERNEL) {
		ui__warning(
"Kernel address maps (/proc/{kallsyms,modules}) are restricted.\n\n"
"Check /proc/sys/kernel/kptr_restrict.\n\n"
"Kernel%s samples will not be resolved.\n",
			  !RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION]) ?
			  " modules" : "");
		if (use_browser <= 0)
			sleep(5);
		kptr_restrict_warned = true;
	}

758
	if (al.sym == NULL) {
759
		const char *msg = "Kernel samples will not be resolved.\n";
760 761 762 763 764 765 766 767 768 769 770
		/*
		 * As we do lazy loading of symtabs we only will know if the
		 * specified vmlinux file is invalid when we actually have a
		 * hit in kernel space and then try to load it. So if we get
		 * here and there are _no_ symbols in the DSO backing the
		 * kernel map, bail out.
		 *
		 * We may never get here, for instance, if we use -K/
		 * --hide-kernel-symbols, even if the user specifies an
		 * invalid --vmlinux ;-)
		 */
771 772
		if (!kptr_restrict_warned && !vmlinux_warned &&
		    al.map == machine->vmlinux_maps[MAP__FUNCTION] &&
773
		    RB_EMPTY_ROOT(&al.map->dso->symbols[MAP__FUNCTION])) {
774 775 776 777 778 779 780 781 782 783 784
			if (symbol_conf.vmlinux_name) {
				ui__warning("The %s file can't be used.\n%s",
					    symbol_conf.vmlinux_name, msg);
			} else {
				ui__warning("A vmlinux file was not found.\n%s",
					    msg);
			}

			if (use_browser <= 0)
				sleep(5);
			vmlinux_warned = true;
785 786 787 788 789
		}

		return;
	}

790 791
	/* let's see, whether we need to install initial sym_filter_entry */
	if (sym_filter_entry_sched) {
792
		top.sym_filter_entry = sym_filter_entry_sched;
793
		sym_filter_entry_sched = NULL;
794 795
		if (parse_source(top.sym_filter_entry) < 0) {
			struct symbol *sym = sym_entry__symbol(top.sym_filter_entry);
796 797

			pr_err("Can't annotate %s", sym->name);
798
			if (top.sym_filter_entry->map->dso->symtab_type == SYMTAB__KALLSYMS) {
799
				pr_err(": No vmlinux file was found in the path:\n");
800
				machine__fprintf_vmlinux_path(machine, stderr);
801 802 803 804
			} else
				pr_err(".\n");
			exit(1);
		}
805 806
	}

807
	syme = symbol__priv(al.sym);
808
	if (!al.sym->ignore) {
809 810
		struct perf_evsel *evsel;

811
		evsel = perf_evlist__id2evsel(top.evlist, sample->id);
812 813
		assert(evsel != NULL);
		syme->count[evsel->idx]++;
814
		record_precise_ip(syme, al.map, evsel->idx, ip);
815
		pthread_mutex_lock(&top.active_symbols_lock);
816 817
		if (list_empty(&syme->node) || !syme->node.next) {
			static bool first = true;
818
			__list_insert_active_sym(syme);
819 820 821 822 823
			if (first) {
				pthread_cond_broadcast(&top.active_symbols_cond);
				first = false;
			}
		}
824
		pthread_mutex_unlock(&top.active_symbols_lock);
825
	}
826 827
}

828
static void perf_session__mmap_read_idx(struct perf_session *self, int idx)
829
{
830
	struct perf_sample sample;
831
	union perf_event *event;
832
	int ret;
833

834
	while ((event = perf_evlist__mmap_read(top.evlist, idx)) != NULL) {
835 836 837 838 839
		ret = perf_session__parse_sample(self, event, &sample);
		if (ret) {
			pr_err("Can't parse sample, err = %d\n", ret);
			continue;
		}
840

841
		if (event->header.type == PERF_RECORD_SAMPLE)
842
			perf_event__process_sample(event, &sample, self);
843
		else
844
			perf_event__process(event, &sample, self);
845 846 847
	}
}

848
static void perf_session__mmap_read(struct perf_session *self)
849
{
850 851
	int i;

852 853
	for (i = 0; i < top.evlist->nr_mmaps; i++)
		perf_session__mmap_read_idx(self, i);
854 855
}

856 857 858
static void start_counters(struct perf_evlist *evlist)
{
	struct perf_evsel *counter;
859

860 861
	list_for_each_entry(counter, &evlist->entries, node) {
		struct perf_event_attr *attr = &counter->attr;
862

863 864
		attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;

865
		if (top.freq) {
866 867
			attr->sample_type |= PERF_SAMPLE_PERIOD;
			attr->freq	  = 1;
868
			attr->sample_freq = top.freq;
869
		}
870

871 872 873 874 875
		if (evlist->nr_entries > 1) {
			attr->sample_type |= PERF_SAMPLE_ID;
			attr->read_format |= PERF_FORMAT_ID;
		}

876
		attr->mmap = 1;
877
		attr->inherit = inherit;
878
try_again:
879
		if (perf_evsel__open(counter, top.evlist->cpus,
880
				     top.evlist->threads, group) < 0) {
881 882
			int err = errno;

883 884 885 886
			if (err == EPERM || err == EACCES) {
				ui__warning_paranoid();
				goto out_err;
			}
887 888 889 890 891
			/*
			 * If it's cycles then fall back to hrtimer
			 * based cpu-clock-tick sw counter, which
			 * is always available even if no PMU support:
			 */
892 893
			if (attr->type == PERF_TYPE_HARDWARE &&
			    attr->config == PERF_COUNT_HW_CPU_CYCLES) {
894
				if (verbose)
895 896
					ui__warning("Cycles event not supported,\n"
						    "trying to fall back to cpu-clock-ticks\n");
897 898 899 900 901

				attr->type = PERF_TYPE_SOFTWARE;
				attr->config = PERF_COUNT_SW_CPU_CLOCK;
				goto try_again;
			}
902

903 904 905 906 907 908
			if (err == ENOENT) {
				ui__warning("The %s event is not supported.\n",
					    event_name(counter));
				goto out_err;
			}

909 910 911 912 913 914
			ui__warning("The sys_perf_event_open() syscall "
				    "returned with %d (%s).  /bin/dmesg "
				    "may provide additional information.\n"
				    "No CONFIG_PERF_EVENTS=y kernel support "
				    "configured?\n", err, strerror(err));
			goto out_err;
915
		}
916
	}
917

918 919 920 921 922 923 924 925 926 927 928
	if (perf_evlist__mmap(evlist, mmap_pages, false) < 0) {
		ui__warning("Failed to mmap with %d (%s)\n",
			    errno, strerror(errno));
		goto out_err;
	}

	return;

out_err:
	exit_browser(0);
	exit(0);
929 930 931 932 933
}

static int __cmd_top(void)
{
	pthread_t thread;
K
Kyle McMartin 已提交
934
	int ret __used;
935
	/*
936 937
	 * FIXME: perf_session__new should allow passing a O_MMAP, so that all this
	 * mmap reading, etc is encapsulated in it. Use O_WRONLY for now.
938
	 */
939
	struct perf_session *session = perf_session__new(NULL, O_WRONLY, false, false, NULL);
940 941
	if (session == NULL)
		return -ENOMEM;
942

943
	if (top.target_tid != -1)
944 945
		perf_event__synthesize_thread_map(top.evlist->threads,
						  perf_event__process, session);
946
	else
947
		perf_event__synthesize_threads(perf_event__process, session);
948

949
	start_counters(top.evlist);
950 951
	session->evlist = top.evlist;
	perf_session__update_sample_type(session);
952

953
	/* Wait for a minimal set of events before starting the snapshot */
954
	poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
955

956
	perf_session__mmap_read(session);
957

958 959
	if (pthread_create(&thread, NULL, (use_browser > 0 ? display_thread_tui :
							     display_thread), session)) {
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
		printf("Could not create display thread.\n");
		exit(-1);
	}

	if (realtime_prio) {
		struct sched_param param;

		param.sched_priority = realtime_prio;
		if (sched_setscheduler(0, SCHED_FIFO, &param)) {
			printf("Could not set realtime priority.\n");
			exit(-1);
		}
	}

	while (1) {
975
		u64 hits = top.samples;
976

977
		perf_session__mmap_read(session);
978

979 980
		if (hits == top.samples)
			ret = poll(top.evlist->pollfd, top.evlist->nr_fds, 100);
981 982 983 984
	}

	return 0;
}
985 986 987 988 989 990 991

static const char * const top_usage[] = {
	"perf top [<options>]",
	NULL
};

static const struct option options[] = {
992
	OPT_CALLBACK('e', "event", &top.evlist, "event",
993
		     "event selector. use 'perf list' to list available events",
994
		     parse_events_option),
995 996
	OPT_INTEGER('c', "count", &default_interval,
		    "event period to sample"),
997
	OPT_INTEGER('p', "pid", &top.target_pid,
998
		    "profile events on existing process id"),
999
	OPT_INTEGER('t', "tid", &top.target_tid,
1000
		    "profile events on existing thread id"),
1001 1002
	OPT_BOOLEAN('a', "all-cpus", &system_wide,
			    "system-wide collection from all CPUs"),
1003
	OPT_STRING('C', "cpu", &top.cpu_list, "cpu",
1004
		    "list of cpus to monitor"),
1005 1006
	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
		   "file", "vmlinux pathname"),
1007
	OPT_BOOLEAN('K', "hide_kernel_symbols", &top.hide_kernel_symbols,
1008
		    "hide kernel symbols"),
1009
	OPT_UINTEGER('m', "mmap-pages", &mmap_pages, "number of mmap data pages"),
1010 1011
	OPT_INTEGER('r', "realtime", &realtime_prio,
		    "collect data with this RT SCHED_FIFO priority"),
1012
	OPT_INTEGER('d', "delay", &top.delay_secs,
1013 1014 1015
		    "number of seconds to delay between refreshes"),
	OPT_BOOLEAN('D', "dump-symtab", &dump_symtab,
			    "dump the symbol table used for profiling"),
1016
	OPT_INTEGER('f', "count-filter", &top.count_filter,
1017 1018 1019
		    "only display functions with more events than this"),
	OPT_BOOLEAN('g', "group", &group,
			    "put the counters into a counter group"),
1020 1021
	OPT_BOOLEAN('i', "inherit", &inherit,
		    "child tasks inherit counters"),
1022
	OPT_STRING('s', "sym-annotate", &sym_filter, "symbol name",
1023
		    "symbol to annotate"),
1024
	OPT_BOOLEAN('z', "zero", &top.zero,
1025
		    "zero history across updates"),
1026
	OPT_INTEGER('F', "freq", &top.freq,
1027
		    "profile at this frequency"),
1028
	OPT_INTEGER('E', "entries", &top.print_entries,
1029
		    "display this many functions"),
1030
	OPT_BOOLEAN('U', "hide_user_symbols", &top.hide_user_symbols,
1031
		    "hide user symbols"),
1032 1033
	OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
	OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
1034
	OPT_INCR('v', "verbose", &verbose,
1035
		    "be more verbose (show counter open errors, etc)"),
1036 1037 1038
	OPT_END()
};

1039
int cmd_top(int argc, const char **argv, const char *prefix __used)
1040
{
1041 1042
	struct perf_evsel *pos;
	int status = -ENOMEM;
1043

1044 1045
	top.evlist = perf_evlist__new(NULL, NULL);
	if (top.evlist == NULL)
1046 1047
		return -ENOMEM;

1048 1049 1050 1051 1052 1053
	page_size = sysconf(_SC_PAGE_SIZE);

	argc = parse_options(argc, argv, options, top_usage, 0);
	if (argc)
		usage_with_options(top_usage, options);

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
	/*
 	 * XXX For now start disabled, only using TUI if explicitely asked for.
 	 * Change that when handle_keys equivalent gets written, live annotation
 	 * done, etc.
 	 */
	use_browser = 0;

	if (use_stdio)
		use_browser = 0;
	else if (use_tui)
		use_browser = 1;

	setup_browser(false);

1068
	/* CPU and PID are mutually exclusive */
1069
	if (top.target_tid > 0 && top.cpu_list) {
1070 1071
		printf("WARNING: PID switch overriding CPU\n");
		sleep(1);
1072
		top.cpu_list = NULL;
1073 1074
	}

1075 1076
	if (top.target_pid != -1)
		top.target_tid = top.target_pid;
1077

1078 1079
	if (perf_evlist__create_maps(top.evlist, top.target_pid,
				     top.target_tid, top.cpu_list) < 0)
1080 1081
		usage_with_options(top_usage, options);

1082 1083
	if (!top.evlist->nr_entries &&
	    perf_evlist__add_default(top.evlist) < 0) {
1084 1085 1086
		pr_err("Not enough memory for event selector list\n");
		return -ENOMEM;
	}
1087

1088 1089
	if (top.delay_secs < 1)
		top.delay_secs = 1;
1090

1091 1092 1093 1094
	/*
	 * User specified count overrides default frequency.
	 */
	if (default_interval)
1095 1096 1097
		top.freq = 0;
	else if (top.freq) {
		default_interval = top.freq;
1098 1099 1100 1101 1102
	} else {
		fprintf(stderr, "frequency and count are zero, aborting\n");
		exit(EXIT_FAILURE);
	}

1103 1104 1105
	list_for_each_entry(pos, &top.evlist->entries, node) {
		if (perf_evsel__alloc_fd(pos, top.evlist->cpus->nr,
					 top.evlist->threads->nr) < 0)
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
			goto out_free_fd;
		/*
		 * Fill in the ones not specifically initialized via -c:
		 */
		if (pos->attr.sample_period)
			continue;

		pos->attr.sample_period = default_interval;
	}

1116 1117
	if (perf_evlist__alloc_pollfd(top.evlist) < 0 ||
	    perf_evlist__alloc_mmap(top.evlist) < 0)
1118 1119
		goto out_free_fd;

1120
	top.sym_evsel = list_entry(top.evlist->entries.next, struct perf_evsel, node);
1121

1122
	symbol_conf.priv_size = (sizeof(struct sym_entry) + sizeof(struct annotation) +
1123
				 (top.evlist->nr_entries + 1) * sizeof(unsigned long));
1124 1125 1126 1127 1128

	symbol_conf.try_vmlinux_path = (symbol_conf.vmlinux_name == NULL);
	if (symbol__init() < 0)
		return -1;

1129
	get_term_dimensions(&winsize);
1130
	if (top.print_entries == 0) {
1131
		update_print_entries(&winsize);
1132 1133 1134
		signal(SIGWINCH, sig_winch_handler);
	}

1135 1136
	status = __cmd_top();
out_free_fd:
1137
	perf_evlist__delete(top.evlist);
1138 1139

	return status;
1140
}