builtin-kvm.c 38.0 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4
#include "builtin.h"
#include "perf.h"

X
Xiao Guangrong 已提交
5
#include "util/evsel.h"
D
David Ahern 已提交
6
#include "util/evlist.h"
7
#include "util/term.h"
8 9 10 11 12 13
#include "util/util.h"
#include "util/cache.h"
#include "util/symbol.h"
#include "util/thread.h"
#include "util/header.h"
#include "util/session.h"
14
#include "util/intlist.h"
15
#include <subcmd/parse-options.h>
16 17
#include "util/trace-event.h"
#include "util/debug.h"
X
Xiao Guangrong 已提交
18 19
#include "util/tool.h"
#include "util/stat.h"
D
David Ahern 已提交
20
#include "util/top.h"
21
#include "util/data.h"
22
#include "util/ordered-events.h"
23 24

#include <sys/prctl.h>
25
#ifdef HAVE_TIMERFD_SUPPORT
D
David Ahern 已提交
26
#include <sys/timerfd.h>
27
#endif
28
#include <sys/time.h>
29 30 31
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
32

33
#include <linux/kernel.h>
34
#include <linux/time64.h>
35
#include <errno.h>
36
#include <inttypes.h>
37
#include <poll.h>
D
David Ahern 已提交
38
#include <termios.h>
39
#include <semaphore.h>
40
#include <signal.h>
41 42
#include <math.h>

43 44 45 46 47 48 49 50 51 52 53 54 55 56
static const char *get_filename_for_perf_kvm(void)
{
	const char *filename;

	if (perf_host && !perf_guest)
		filename = strdup("perf.data.host");
	else if (!perf_host && perf_guest)
		filename = strdup("perf.data.guest");
	else
		filename = strdup("perf.data.kvm");

	return filename;
}

57
#ifdef HAVE_KVM_STAT_SUPPORT
58
#include "util/kvm-stat.h"
X
Xiao Guangrong 已提交
59

60 61 62
void exit_event_get_key(struct perf_evsel *evsel,
			struct perf_sample *sample,
			struct event_key *key)
X
Xiao Guangrong 已提交
63 64
{
	key->info = 0;
65
	key->key = perf_evsel__intval(evsel, sample, kvm_exit_reason);
X
Xiao Guangrong 已提交
66 67
}

68
bool kvm_exit_event(struct perf_evsel *evsel)
X
Xiao Guangrong 已提交
69
{
70
	return !strcmp(evsel->name, kvm_exit_trace);
X
Xiao Guangrong 已提交
71 72
}

73 74
bool exit_event_begin(struct perf_evsel *evsel,
		      struct perf_sample *sample, struct event_key *key)
X
Xiao Guangrong 已提交
75
{
76 77
	if (kvm_exit_event(evsel)) {
		exit_event_get_key(evsel, sample, key);
X
Xiao Guangrong 已提交
78 79 80 81 82 83
		return true;
	}

	return false;
}

84
bool kvm_entry_event(struct perf_evsel *evsel)
X
Xiao Guangrong 已提交
85
{
86
	return !strcmp(evsel->name, kvm_entry_trace);
X
Xiao Guangrong 已提交
87 88
}

89 90 91
bool exit_event_end(struct perf_evsel *evsel,
		    struct perf_sample *sample __maybe_unused,
		    struct event_key *key __maybe_unused)
X
Xiao Guangrong 已提交
92
{
93
	return kvm_entry_event(evsel);
X
Xiao Guangrong 已提交
94 95
}

96 97 98
static const char *get_exit_reason(struct perf_kvm_stat *kvm,
				   struct exit_reasons_table *tbl,
				   u64 exit_code)
X
Xiao Guangrong 已提交
99
{
100
	while (tbl->reason != NULL) {
101 102 103
		if (tbl->exit_code == exit_code)
			return tbl->reason;
		tbl++;
X
Xiao Guangrong 已提交
104 105 106
	}

	pr_err("unknown kvm exit code:%lld on %s\n",
107
		(unsigned long long)exit_code, kvm->exit_reasons_isa);
X
Xiao Guangrong 已提交
108 109 110
	return "UNKNOWN";
}

111 112 113
void exit_event_decode_key(struct perf_kvm_stat *kvm,
			   struct event_key *key,
			   char *decode)
X
Xiao Guangrong 已提交
114
{
115
	const char *exit_reason = get_exit_reason(kvm, key->exit_reasons,
116
						  key->key);
X
Xiao Guangrong 已提交
117

118
	scnprintf(decode, decode_str_len, "%s", exit_reason);
X
Xiao Guangrong 已提交
119 120
}

121
static bool register_kvm_events_ops(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
122
{
123
	struct kvm_reg_events_ops *events_ops = kvm_reg_events_ops;
X
Xiao Guangrong 已提交
124

125 126 127 128 129
	for (events_ops = kvm_reg_events_ops; events_ops->name; events_ops++) {
		if (!strcmp(events_ops->name, kvm->report_event)) {
			kvm->events_ops = events_ops->ops;
			return true;
		}
X
Xiao Guangrong 已提交
130 131 132 133 134 135 136 137 138 139 140 141
	}

	return false;
}

struct vcpu_event_record {
	int vcpu_id;
	u64 start_time;
	struct kvm_event *last_event;
};


142
static void init_kvm_event_record(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
143
{
144
	unsigned int i;
X
Xiao Guangrong 已提交
145

146
	for (i = 0; i < EVENTS_CACHE_SIZE; i++)
147
		INIT_LIST_HEAD(&kvm->kvm_events_cache[i]);
X
Xiao Guangrong 已提交
148 149
}

150
#ifdef HAVE_TIMERFD_SUPPORT
D
David Ahern 已提交
151 152 153 154 155
static void clear_events_cache_stats(struct list_head *kvm_events_cache)
{
	struct list_head *head;
	struct kvm_event *event;
	unsigned int i;
156
	int j;
D
David Ahern 已提交
157 158 159 160 161

	for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
		head = &kvm_events_cache[i];
		list_for_each_entry(event, head, hash_entry) {
			/* reset stats for event */
162 163 164 165 166 167 168
			event->total.time = 0;
			init_stats(&event->total.stats);

			for (j = 0; j < event->max_vcpu; ++j) {
				event->vcpu[j].time = 0;
				init_stats(&event->vcpu[j].stats);
			}
D
David Ahern 已提交
169 170 171
		}
	}
}
172
#endif
D
David Ahern 已提交
173

X
Xiao Guangrong 已提交
174 175 176 177 178 179 180 181
static int kvm_events_hash_fn(u64 key)
{
	return key & (EVENTS_CACHE_SIZE - 1);
}

static bool kvm_event_expand(struct kvm_event *event, int vcpu_id)
{
	int old_max_vcpu = event->max_vcpu;
D
David Ahern 已提交
182
	void *prev;
X
Xiao Guangrong 已提交
183 184 185 186 187 188 189

	if (vcpu_id < event->max_vcpu)
		return true;

	while (event->max_vcpu <= vcpu_id)
		event->max_vcpu += DEFAULT_VCPU_NUM;

D
David Ahern 已提交
190
	prev = event->vcpu;
X
Xiao Guangrong 已提交
191 192 193
	event->vcpu = realloc(event->vcpu,
			      event->max_vcpu * sizeof(*event->vcpu));
	if (!event->vcpu) {
D
David Ahern 已提交
194
		free(prev);
X
Xiao Guangrong 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
		pr_err("Not enough memory\n");
		return false;
	}

	memset(event->vcpu + old_max_vcpu, 0,
	       (event->max_vcpu - old_max_vcpu) * sizeof(*event->vcpu));
	return true;
}

static struct kvm_event *kvm_alloc_init_event(struct event_key *key)
{
	struct kvm_event *event;

	event = zalloc(sizeof(*event));
	if (!event) {
		pr_err("Not enough memory\n");
		return NULL;
	}

	event->key = *key;
215
	init_stats(&event->total.stats);
X
Xiao Guangrong 已提交
216 217 218
	return event;
}

219
static struct kvm_event *find_create_kvm_event(struct perf_kvm_stat *kvm,
220
					       struct event_key *key)
X
Xiao Guangrong 已提交
221 222 223 224 225 226
{
	struct kvm_event *event;
	struct list_head *head;

	BUG_ON(key->key == INVALID_KEY);

227
	head = &kvm->kvm_events_cache[kvm_events_hash_fn(key->key)];
228
	list_for_each_entry(event, head, hash_entry) {
X
Xiao Guangrong 已提交
229 230
		if (event->key.key == key->key && event->key.info == key->info)
			return event;
231
	}
X
Xiao Guangrong 已提交
232 233 234 235 236 237 238 239 240

	event = kvm_alloc_init_event(key);
	if (!event)
		return NULL;

	list_add(&event->hash_entry, head);
	return event;
}

241
static bool handle_begin_event(struct perf_kvm_stat *kvm,
242
			       struct vcpu_event_record *vcpu_record,
X
Xiao Guangrong 已提交
243 244 245 246 247
			       struct event_key *key, u64 timestamp)
{
	struct kvm_event *event = NULL;

	if (key->key != INVALID_KEY)
248
		event = find_create_kvm_event(kvm, key);
X
Xiao Guangrong 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

	vcpu_record->last_event = event;
	vcpu_record->start_time = timestamp;
	return true;
}

static void
kvm_update_event_stats(struct kvm_event_stats *kvm_stats, u64 time_diff)
{
	kvm_stats->time += time_diff;
	update_stats(&kvm_stats->stats, time_diff);
}

static double kvm_event_rel_stddev(int vcpu_id, struct kvm_event *event)
{
	struct kvm_event_stats *kvm_stats = &event->total;

	if (vcpu_id != -1)
		kvm_stats = &event->vcpu[vcpu_id];

	return rel_stddev_stats(stddev_stats(&kvm_stats->stats),
				avg_stats(&kvm_stats->stats));
}

static bool update_kvm_event(struct kvm_event *event, int vcpu_id,
			     u64 time_diff)
{
276 277 278 279
	if (vcpu_id == -1) {
		kvm_update_event_stats(&event->total, time_diff);
		return true;
	}
X
Xiao Guangrong 已提交
280 281 282 283 284 285 286 287

	if (!kvm_event_expand(event, vcpu_id))
		return false;

	kvm_update_event_stats(&event->vcpu[vcpu_id], time_diff);
	return true;
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
static bool is_child_event(struct perf_kvm_stat *kvm,
			   struct perf_evsel *evsel,
			   struct perf_sample *sample,
			   struct event_key *key)
{
	struct child_event_ops *child_ops;

	child_ops = kvm->events_ops->child_ops;

	if (!child_ops)
		return false;

	for (; child_ops->name; child_ops++) {
		if (!strcmp(evsel->name, child_ops->name)) {
			child_ops->get_key(evsel, sample, key);
			return true;
		}
	}

	return false;
}

static bool handle_child_event(struct perf_kvm_stat *kvm,
			       struct vcpu_event_record *vcpu_record,
			       struct event_key *key,
			       struct perf_sample *sample __maybe_unused)
{
	struct kvm_event *event = NULL;

	if (key->key != INVALID_KEY)
		event = find_create_kvm_event(kvm, key);

	vcpu_record->last_event = event;

	return true;
}

325 326 327 328 329 330 331 332 333 334 335
static bool skip_event(const char *event)
{
	const char * const *skip_events;

	for (skip_events = kvm_skip_events; *skip_events; skip_events++)
		if (!strcmp(event, *skip_events))
			return true;

	return false;
}

336
static bool handle_end_event(struct perf_kvm_stat *kvm,
337 338
			     struct vcpu_event_record *vcpu_record,
			     struct event_key *key,
339
			     struct perf_sample *sample)
X
Xiao Guangrong 已提交
340 341 342
{
	struct kvm_event *event;
	u64 time_begin, time_diff;
343 344 345 346 347 348
	int vcpu;

	if (kvm->trace_vcpu == -1)
		vcpu = -1;
	else
		vcpu = vcpu_record->vcpu_id;
X
Xiao Guangrong 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

	event = vcpu_record->last_event;
	time_begin = vcpu_record->start_time;

	/* The begin event is not caught. */
	if (!time_begin)
		return true;

	/*
	 * In some case, the 'begin event' only records the start timestamp,
	 * the actual event is recognized in the 'end event' (e.g. mmio-event).
	 */

	/* Both begin and end events did not get the key. */
	if (!event && key->key == INVALID_KEY)
		return true;

	if (!event)
367
		event = find_create_kvm_event(kvm, key);
X
Xiao Guangrong 已提交
368 369 370 371 372 373 374

	if (!event)
		return false;

	vcpu_record->last_event = NULL;
	vcpu_record->start_time = 0;

D
David Ahern 已提交
375
	/* seems to happen once in a while during live mode */
376
	if (sample->time < time_begin) {
D
David Ahern 已提交
377 378 379
		pr_debug("End time before begin time; skipping event.\n");
		return true;
	}
X
Xiao Guangrong 已提交
380

381 382 383
	time_diff = sample->time - time_begin;

	if (kvm->duration && time_diff > kvm->duration) {
384
		char decode[decode_str_len];
385 386

		kvm->events_ops->decode_key(kvm, &event->key, decode);
387
		if (!skip_event(decode)) {
388 389
			pr_info("%" PRIu64 " VM %d, vcpu %d: %s event took %" PRIu64 "usec\n",
				 sample->time, sample->pid, vcpu_record->vcpu_id,
390
				 decode, time_diff / NSEC_PER_USEC);
391 392 393
		}
	}

394
	return update_kvm_event(event, vcpu, time_diff);
X
Xiao Guangrong 已提交
395 396
}

397 398 399 400
static
struct vcpu_event_record *per_vcpu_record(struct thread *thread,
					  struct perf_evsel *evsel,
					  struct perf_sample *sample)
X
Xiao Guangrong 已提交
401 402
{
	/* Only kvm_entry records vcpu id. */
403
	if (!thread__priv(thread) && kvm_entry_event(evsel)) {
X
Xiao Guangrong 已提交
404 405
		struct vcpu_event_record *vcpu_record;

406
		vcpu_record = zalloc(sizeof(*vcpu_record));
X
Xiao Guangrong 已提交
407
		if (!vcpu_record) {
408
			pr_err("%s: Not enough memory\n", __func__);
X
Xiao Guangrong 已提交
409 410 411
			return NULL;
		}

412 413
		vcpu_record->vcpu_id = perf_evsel__intval(evsel, sample,
							  vcpu_id_str);
414
		thread__set_priv(thread, vcpu_record);
X
Xiao Guangrong 已提交
415 416
	}

417
	return thread__priv(thread);
X
Xiao Guangrong 已提交
418 419
}

420
static bool handle_kvm_event(struct perf_kvm_stat *kvm,
421 422
			     struct thread *thread,
			     struct perf_evsel *evsel,
423
			     struct perf_sample *sample)
X
Xiao Guangrong 已提交
424 425
{
	struct vcpu_event_record *vcpu_record;
426 427
	struct event_key key = { .key = INVALID_KEY,
				 .exit_reasons = kvm->exit_reasons };
X
Xiao Guangrong 已提交
428

429
	vcpu_record = per_vcpu_record(thread, evsel, sample);
X
Xiao Guangrong 已提交
430 431 432
	if (!vcpu_record)
		return true;

433 434 435 436 437
	/* only process events for vcpus user cares about */
	if ((kvm->trace_vcpu != -1) &&
	    (kvm->trace_vcpu != vcpu_record->vcpu_id))
		return true;

438 439
	if (kvm->events_ops->is_begin_event(evsel, sample, &key))
		return handle_begin_event(kvm, vcpu_record, &key, sample->time);
X
Xiao Guangrong 已提交
440

441 442 443
	if (is_child_event(kvm, evsel, sample, &key))
		return handle_child_event(kvm, vcpu_record, &key, sample);

444
	if (kvm->events_ops->is_end_event(evsel, sample, &key))
445
		return handle_end_event(kvm, vcpu_record, &key, sample);
X
Xiao Guangrong 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

	return true;
}

#define GET_EVENT_KEY(func, field)					\
static u64 get_event_ ##func(struct kvm_event *event, int vcpu)		\
{									\
	if (vcpu == -1)							\
		return event->total.field;				\
									\
	if (vcpu >= event->max_vcpu)					\
		return 0;						\
									\
	return event->vcpu[vcpu].field;					\
}

#define COMPARE_EVENT_KEY(func, field)					\
GET_EVENT_KEY(func, field)						\
static int compare_kvm_event_ ## func(struct kvm_event *one,		\
					struct kvm_event *two, int vcpu)\
{									\
	return get_event_ ##func(one, vcpu) >				\
				get_event_ ##func(two, vcpu);		\
}

GET_EVENT_KEY(time, time);
COMPARE_EVENT_KEY(count, stats.n);
COMPARE_EVENT_KEY(mean, stats.mean);
474 475
GET_EVENT_KEY(max, stats.max);
GET_EVENT_KEY(min, stats.min);
X
Xiao Guangrong 已提交
476 477 478 479 480 481 482 483 484 485

#define DEF_SORT_NAME_KEY(name, compare_key)				\
	{ #name, compare_kvm_event_ ## compare_key }

static struct kvm_event_key keys[] = {
	DEF_SORT_NAME_KEY(sample, count),
	DEF_SORT_NAME_KEY(time, mean),
	{ NULL, NULL }
};

486
static bool select_key(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
487 488 489 490
{
	int i;

	for (i = 0; keys[i].name; i++) {
491 492
		if (!strcmp(keys[i].name, kvm->sort_key)) {
			kvm->compare = keys[i].key;
X
Xiao Guangrong 已提交
493 494 495 496
			return true;
		}
	}

497
	pr_err("Unknown compare key:%s\n", kvm->sort_key);
X
Xiao Guangrong 已提交
498 499 500
	return false;
}

501 502
static void insert_to_result(struct rb_root *result, struct kvm_event *event,
			     key_cmp_fun bigger, int vcpu)
X
Xiao Guangrong 已提交
503
{
504
	struct rb_node **rb = &result->rb_node;
X
Xiao Guangrong 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518
	struct rb_node *parent = NULL;
	struct kvm_event *p;

	while (*rb) {
		p = container_of(*rb, struct kvm_event, rb);
		parent = *rb;

		if (bigger(event, p, vcpu))
			rb = &(*rb)->rb_left;
		else
			rb = &(*rb)->rb_right;
	}

	rb_link_node(&event->rb, parent, rb);
519
	rb_insert_color(&event->rb, result);
X
Xiao Guangrong 已提交
520 521
}

522 523
static void
update_total_count(struct perf_kvm_stat *kvm, struct kvm_event *event)
X
Xiao Guangrong 已提交
524
{
525 526 527 528
	int vcpu = kvm->trace_vcpu;

	kvm->total_count += get_event_count(event, vcpu);
	kvm->total_time += get_event_time(event, vcpu);
X
Xiao Guangrong 已提交
529 530 531 532 533 534 535
}

static bool event_is_valid(struct kvm_event *event, int vcpu)
{
	return !!get_event_count(event, vcpu);
}

536
static void sort_result(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
537 538
{
	unsigned int i;
539
	int vcpu = kvm->trace_vcpu;
X
Xiao Guangrong 已提交
540 541
	struct kvm_event *event;

542 543
	for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
		list_for_each_entry(event, &kvm->kvm_events_cache[i], hash_entry) {
X
Xiao Guangrong 已提交
544
			if (event_is_valid(event, vcpu)) {
545 546 547
				update_total_count(kvm, event);
				insert_to_result(&kvm->result, event,
						 kvm->compare, vcpu);
X
Xiao Guangrong 已提交
548
			}
549 550
		}
	}
X
Xiao Guangrong 已提交
551 552 553
}

/* returns left most element of result, and erase it */
554
static struct kvm_event *pop_from_result(struct rb_root *result)
X
Xiao Guangrong 已提交
555
{
556
	struct rb_node *node = rb_first(result);
X
Xiao Guangrong 已提交
557 558 559 560

	if (!node)
		return NULL;

561
	rb_erase(node, result);
X
Xiao Guangrong 已提交
562 563 564
	return container_of(node, struct kvm_event, rb);
}

D
David Ahern 已提交
565
static void print_vcpu_info(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
566
{
D
David Ahern 已提交
567 568
	int vcpu = kvm->trace_vcpu;

X
Xiao Guangrong 已提交
569 570
	pr_info("Analyze events for ");

571 572 573 574 575 576
	if (kvm->opts.target.system_wide)
		pr_info("all VMs, ");
	else if (kvm->opts.target.pid)
		pr_info("pid(s) %s, ", kvm->opts.target.pid);
	else
		pr_info("dazed and confused on what is monitored, ");
D
David Ahern 已提交
577

X
Xiao Guangrong 已提交
578 579 580 581 582 583
	if (vcpu == -1)
		pr_info("all VCPUs:\n\n");
	else
		pr_info("VCPU %d:\n\n", vcpu);
}

D
David Ahern 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
static void show_timeofday(void)
{
	char date[64];
	struct timeval tv;
	struct tm ltime;

	gettimeofday(&tv, NULL);
	if (localtime_r(&tv.tv_sec, &ltime)) {
		strftime(date, sizeof(date), "%H:%M:%S", &ltime);
		pr_info("%s.%06ld", date, tv.tv_usec);
	} else
		pr_info("00:00:00.000000");

	return;
}

600
static void print_result(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
601
{
602
	char decode[decode_str_len];
X
Xiao Guangrong 已提交
603
	struct kvm_event *event;
604
	int vcpu = kvm->trace_vcpu;
X
Xiao Guangrong 已提交
605

D
David Ahern 已提交
606 607 608 609 610
	if (kvm->live) {
		puts(CONSOLE_CLEAR);
		show_timeofday();
	}

X
Xiao Guangrong 已提交
611
	pr_info("\n\n");
D
David Ahern 已提交
612
	print_vcpu_info(kvm);
613
	pr_info("%*s ", decode_str_len, kvm->events_ops->name);
X
Xiao Guangrong 已提交
614 615 616 617
	pr_info("%10s ", "Samples");
	pr_info("%9s ", "Samples%");

	pr_info("%9s ", "Time%");
618 619
	pr_info("%11s ", "Min Time");
	pr_info("%11s ", "Max Time");
X
Xiao Guangrong 已提交
620 621 622
	pr_info("%16s ", "Avg time");
	pr_info("\n\n");

623
	while ((event = pop_from_result(&kvm->result))) {
624
		u64 ecount, etime, max, min;
X
Xiao Guangrong 已提交
625 626 627

		ecount = get_event_count(event, vcpu);
		etime = get_event_time(event, vcpu);
628 629
		max = get_event_max(event, vcpu);
		min = get_event_min(event, vcpu);
X
Xiao Guangrong 已提交
630

631
		kvm->events_ops->decode_key(kvm, &event->key, decode);
632
		pr_info("%*s ", decode_str_len, decode);
X
Xiao Guangrong 已提交
633
		pr_info("%10llu ", (unsigned long long)ecount);
634 635
		pr_info("%8.2f%% ", (double)ecount / kvm->total_count * 100);
		pr_info("%8.2f%% ", (double)etime / kvm->total_time * 100);
636 637 638
		pr_info("%9.2fus ", (double)min / NSEC_PER_USEC);
		pr_info("%9.2fus ", (double)max / NSEC_PER_USEC);
		pr_info("%9.2fus ( +-%7.2f%% )", (double)etime / ecount / NSEC_PER_USEC,
X
Xiao Guangrong 已提交
639 640 641 642
			kvm_event_rel_stddev(vcpu, event));
		pr_info("\n");
	}

643
	pr_info("\nTotal Samples:%" PRIu64 ", Total events handled time:%.2fus.\n\n",
644
		kvm->total_count, kvm->total_time / (double)NSEC_PER_USEC);
D
David Ahern 已提交
645 646 647 648 649

	if (kvm->lost_events)
		pr_info("\nLost events: %" PRIu64 "\n\n", kvm->lost_events);
}

650
#ifdef HAVE_TIMERFD_SUPPORT
D
David Ahern 已提交
651 652 653 654 655 656 657 658 659
static int process_lost_event(struct perf_tool *tool,
			      union perf_event *event __maybe_unused,
			      struct perf_sample *sample __maybe_unused,
			      struct machine *machine __maybe_unused)
{
	struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat, tool);

	kvm->lost_events++;
	return 0;
X
Xiao Guangrong 已提交
660
}
661
#endif
X
Xiao Guangrong 已提交
662

663 664 665 666 667 668 669 670 671
static bool skip_sample(struct perf_kvm_stat *kvm,
			struct perf_sample *sample)
{
	if (kvm->pid_list && intlist__find(kvm->pid_list, sample->pid) == NULL)
		return true;

	return false;
}

672
static int process_sample_event(struct perf_tool *tool,
X
Xiao Guangrong 已提交
673 674 675 676 677
				union perf_event *event,
				struct perf_sample *sample,
				struct perf_evsel *evsel,
				struct machine *machine)
{
678
	int err = 0;
679
	struct thread *thread;
680 681
	struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat,
						 tool);
X
Xiao Guangrong 已提交
682

683 684 685
	if (skip_sample(kvm, sample))
		return 0;

686
	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
X
Xiao Guangrong 已提交
687 688 689 690 691 692
	if (thread == NULL) {
		pr_debug("problem processing %d event, skipping it.\n",
			event->header.type);
		return -1;
	}

693
	if (!handle_kvm_event(kvm, thread, evsel, sample))
694
		err = -1;
X
Xiao Guangrong 已提交
695

696 697
	thread__put(thread);
	return err;
X
Xiao Guangrong 已提交
698 699
}

D
David Ahern 已提交
700
static int cpu_isa_config(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
701
{
D
David Ahern 已提交
702
	char buf[64], *cpuid;
703
	int err;
D
David Ahern 已提交
704 705 706 707

	if (kvm->live) {
		err = get_cpuid(buf, sizeof(buf));
		if (err != 0) {
708
			pr_err("Failed to look up CPU type\n");
D
David Ahern 已提交
709 710 711 712 713
			return err;
		}
		cpuid = buf;
	} else
		cpuid = kvm->session->header.env.cpuid;
X
Xiao Guangrong 已提交
714

715 716 717
	if (!cpuid) {
		pr_err("Failed to look up CPU type\n");
		return -EINVAL;
D
David Ahern 已提交
718 719
	}

720 721 722
	err = cpu_isa_init(kvm, cpuid);
	if (err == -ENOTSUP)
		pr_err("CPU %s is not supported.\n", cpuid);
D
David Ahern 已提交
723

724
	return err;
D
David Ahern 已提交
725 726 727 728 729 730 731 732 733 734 735 736
}

static bool verify_vcpu(int vcpu)
{
	if (vcpu != -1 && vcpu < 0) {
		pr_err("Invalid vcpu:%d.\n", vcpu);
		return false;
	}

	return true;
}

737
#ifdef HAVE_TIMERFD_SUPPORT
D
David Ahern 已提交
738 739 740 741 742 743 744 745
/* keeping the max events to a modest level to keep
 * the processing of samples per mmap smooth.
 */
#define PERF_KVM__MAX_EVENTS_PER_MMAP  25

static s64 perf_kvm__mmap_read_idx(struct perf_kvm_stat *kvm, int idx,
				   u64 *mmap_time)
{
746
	struct perf_evlist *evlist = kvm->evlist;
D
David Ahern 已提交
747
	union perf_event *event;
748 749
	struct perf_mmap *md;
	u64 end, start;
750
	u64 timestamp;
D
David Ahern 已提交
751 752 753 754
	s64 n = 0;
	int err;

	*mmap_time = ULLONG_MAX;
755 756 757 758 759 760 761
	md = &evlist->mmap[idx];
	err = perf_mmap__read_init(md, false, &start, &end);
	if (err < 0)
		return (err == -EAGAIN) ? 0 : -1;

	while ((event = perf_mmap__read_event(md, false, &start, end)) != NULL) {
		err = perf_evlist__parse_sample_timestamp(evlist, event, &timestamp);
D
David Ahern 已提交
762
		if (err) {
763
			perf_mmap__consume(md);
D
David Ahern 已提交
764 765 766 767
			pr_err("Failed to parse sample\n");
			return -1;
		}

768
		err = perf_session__queue_event(kvm->session, event, timestamp, 0);
769
		/*
770
		 * FIXME: Here we can't consume the event, as perf_session__queue_event will
771 772
		 *        point to it, and it'll get possibly overwritten by the kernel.
		 */
773
		perf_mmap__consume(md);
774

D
David Ahern 已提交
775 776 777 778 779 780 781
		if (err) {
			pr_err("Failed to enqueue sample: %d\n", err);
			return -1;
		}

		/* save time stamp of our first sample for this mmap */
		if (n == 0)
782
			*mmap_time = timestamp;
D
David Ahern 已提交
783 784 785 786 787 788 789

		/* limit events per mmap handled all at once */
		n++;
		if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
			break;
	}

790
	perf_mmap__read_done(md);
D
David Ahern 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
	return n;
}

static int perf_kvm__mmap_read(struct perf_kvm_stat *kvm)
{
	int i, err, throttled = 0;
	s64 n, ntotal = 0;
	u64 flush_time = ULLONG_MAX, mmap_time;

	for (i = 0; i < kvm->evlist->nr_mmaps; i++) {
		n = perf_kvm__mmap_read_idx(kvm, i, &mmap_time);
		if (n < 0)
			return -1;

		/* flush time is going to be the minimum of all the individual
		 * mmap times. Essentially, we flush all the samples queued up
		 * from the last pass under our minimal start time -- that leaves
		 * a very small race for samples to come in with a lower timestamp.
		 * The ioctl to return the perf_clock timestamp should close the
		 * race entirely.
		 */
		if (mmap_time < flush_time)
			flush_time = mmap_time;

		ntotal += n;
		if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
			throttled = 1;
	}

	/* flush queue after each round in which we processed events */
	if (ntotal) {
822 823 824 825
		struct ordered_events *oe = &kvm->session->ordered_events;

		oe->next_flush = flush_time;
		err = ordered_events__flush(oe, OE_FLUSH__ROUND);
D
David Ahern 已提交
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
		if (err) {
			if (kvm->lost_events)
				pr_info("\nLost events: %" PRIu64 "\n\n",
					kvm->lost_events);
			return err;
		}
	}

	return throttled;
}

static volatile int done;

static void sig_handler(int sig __maybe_unused)
{
	done = 1;
}

static int perf_kvm__timerfd_create(struct perf_kvm_stat *kvm)
{
	struct itimerspec new_value;
	int rc = -1;

	kvm->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
	if (kvm->timerfd < 0) {
		pr_err("timerfd_create failed\n");
		goto out;
	}

	new_value.it_value.tv_sec = kvm->display_time;
	new_value.it_value.tv_nsec = 0;
	new_value.it_interval.tv_sec = kvm->display_time;
	new_value.it_interval.tv_nsec = 0;

	if (timerfd_settime(kvm->timerfd, 0, &new_value, NULL) != 0) {
		pr_err("timerfd_settime failed: %d\n", errno);
		close(kvm->timerfd);
		goto out;
	}

	rc = 0;
out:
	return rc;
}

static int perf_kvm__handle_timerfd(struct perf_kvm_stat *kvm)
{
	uint64_t c;
	int rc;

	rc = read(kvm->timerfd, &c, sizeof(uint64_t));
	if (rc < 0) {
		if (errno == EAGAIN)
			return 0;

		pr_err("Failed to read timer fd: %d\n", errno);
		return -1;
	}

	if (rc != sizeof(uint64_t)) {
		pr_err("Error reading timer fd - invalid size returned\n");
		return -1;
	}

	if (c != 1)
		pr_debug("Missed timer beats: %" PRIu64 "\n", c-1);

	/* update display */
	sort_result(kvm);
	print_result(kvm);

	/* reset counts */
	clear_events_cache_stats(kvm->kvm_events_cache);
	kvm->total_count = 0;
	kvm->total_time = 0;
	kvm->lost_events = 0;

	return 0;
}

static int fd_set_nonblock(int fd)
{
	long arg = 0;

	arg = fcntl(fd, F_GETFL);
	if (arg < 0) {
		pr_err("Failed to get current flags for fd %d\n", fd);
		return -1;
	}

	if (fcntl(fd, F_SETFL, arg | O_NONBLOCK) < 0) {
		pr_err("Failed to set non-block option on fd %d\n", fd);
		return -1;
	}

	return 0;
}

924
static int perf_kvm__handle_stdin(void)
D
David Ahern 已提交
925 926 927 928 929 930 931 932 933 934 935 936
{
	int c;

	c = getc(stdin);
	if (c == 'q')
		return 1;

	return 0;
}

static int kvm_events_live_report(struct perf_kvm_stat *kvm)
{
937
	int nr_stdin, ret, err = -EINVAL;
938
	struct termios save;
D
David Ahern 已提交
939 940 941 942 943 944 945 946 947 948 949 950 951 952

	/* live flag must be set first */
	kvm->live = true;

	ret = cpu_isa_config(kvm);
	if (ret < 0)
		return ret;

	if (!verify_vcpu(kvm->trace_vcpu) ||
	    !select_key(kvm) ||
	    !register_kvm_events_ops(kvm)) {
		goto out;
	}

953
	set_term_quiet_input(&save);
D
David Ahern 已提交
954 955 956 957 958 959 960 961 962 963 964
	init_kvm_event_record(kvm);

	signal(SIGINT, sig_handler);
	signal(SIGTERM, sig_handler);

	/* add timer fd */
	if (perf_kvm__timerfd_create(kvm) < 0) {
		err = -1;
		goto out;
	}

965
	if (perf_evlist__add_pollfd(kvm->evlist, kvm->timerfd) < 0)
966 967
		goto out;

968 969
	nr_stdin = perf_evlist__add_pollfd(kvm->evlist, fileno(stdin));
	if (nr_stdin < 0)
970 971
		goto out;

D
David Ahern 已提交
972 973 974 975 976 977 978
	if (fd_set_nonblock(fileno(stdin)) != 0)
		goto out;

	/* everything is good - enable the events and process */
	perf_evlist__enable(kvm->evlist);

	while (!done) {
979
		struct fdarray *fda = &kvm->evlist->pollfd;
D
David Ahern 已提交
980 981 982 983 984 985 986 987 988 989
		int rc;

		rc = perf_kvm__mmap_read(kvm);
		if (rc < 0)
			break;

		err = perf_kvm__handle_timerfd(kvm);
		if (err)
			goto out;

990
		if (fda->entries[nr_stdin].revents & POLLIN)
991
			done = perf_kvm__handle_stdin();
D
David Ahern 已提交
992 993

		if (!rc && !done)
994
			err = fdarray__poll(fda, 100);
D
David Ahern 已提交
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	}

	perf_evlist__disable(kvm->evlist);

	if (err == 0) {
		sort_result(kvm);
		print_result(kvm);
	}

out:
	if (kvm->timerfd >= 0)
		close(kvm->timerfd);

1008
	tcsetattr(0, TCSAFLUSH, &save);
D
David Ahern 已提交
1009 1010 1011 1012 1013 1014 1015 1016
	return err;
}

static int kvm_live_open_events(struct perf_kvm_stat *kvm)
{
	int err, rc = -1;
	struct perf_evsel *pos;
	struct perf_evlist *evlist = kvm->evlist;
1017
	char sbuf[STRERR_BUFSIZE];
D
David Ahern 已提交
1018

1019
	perf_evlist__config(evlist, &kvm->opts, NULL);
D
David Ahern 已提交
1020 1021 1022 1023 1024

	/*
	 * Note: exclude_{guest,host} do not apply here.
	 *       This command processes KVM tracepoints from host only
	 */
1025
	evlist__for_each_entry(evlist, pos) {
D
David Ahern 已提交
1026 1027 1028
		struct perf_event_attr *attr = &pos->attr;

		/* make sure these *are* set */
1029 1030 1031 1032
		perf_evsel__set_sample_bit(pos, TID);
		perf_evsel__set_sample_bit(pos, TIME);
		perf_evsel__set_sample_bit(pos, CPU);
		perf_evsel__set_sample_bit(pos, RAW);
D
David Ahern 已提交
1033
		/* make sure these are *not*; want as small a sample as possible */
1034 1035 1036 1037 1038
		perf_evsel__reset_sample_bit(pos, PERIOD);
		perf_evsel__reset_sample_bit(pos, IP);
		perf_evsel__reset_sample_bit(pos, CALLCHAIN);
		perf_evsel__reset_sample_bit(pos, ADDR);
		perf_evsel__reset_sample_bit(pos, READ);
D
David Ahern 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
		attr->mmap = 0;
		attr->comm = 0;
		attr->task = 0;

		attr->sample_period = 1;

		attr->watermark = 0;
		attr->wakeup_events = 1000;

		/* will enable all once we are ready */
		attr->disabled = 1;
	}

	err = perf_evlist__open(evlist);
	if (err < 0) {
1054
		printf("Couldn't create the events: %s\n",
1055
		       str_error_r(errno, sbuf, sizeof(sbuf)));
D
David Ahern 已提交
1056
		goto out;
X
Xiao Guangrong 已提交
1057 1058
	}

1059
	if (perf_evlist__mmap(evlist, kvm->opts.mmap_pages) < 0) {
1060
		ui__error("Failed to mmap the events: %s\n",
1061
			  str_error_r(errno, sbuf, sizeof(sbuf)));
D
David Ahern 已提交
1062 1063 1064 1065 1066 1067 1068 1069
		perf_evlist__close(evlist);
		goto out;
	}

	rc = 0;

out:
	return rc;
X
Xiao Guangrong 已提交
1070
}
1071
#endif
X
Xiao Guangrong 已提交
1072

1073
static int read_events(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
1074 1075 1076
{
	int ret;

1077 1078 1079
	struct perf_tool eops = {
		.sample			= process_sample_event,
		.comm			= perf_event__process_comm,
1080
		.namespaces		= perf_event__process_namespaces,
1081
		.ordered_events		= true,
1082
	};
1083
	struct perf_data file = {
J
Jiri Olsa 已提交
1084 1085 1086 1087 1088
		.file      = {
			.path = kvm->file_name,
		},
		.mode      = PERF_DATA_MODE_READ,
		.force     = kvm->force,
1089
	};
1090 1091

	kvm->tool = eops;
1092
	kvm->session = perf_session__new(&file, false, &kvm->tool);
1093
	if (!kvm->session) {
X
Xiao Guangrong 已提交
1094
		pr_err("Initializing perf session failed\n");
1095
		return -1;
X
Xiao Guangrong 已提交
1096 1097
	}

1098
	symbol__init(&kvm->session->header.env);
1099

1100 1101 1102 1103
	if (!perf_session__has_traces(kvm->session, "kvm record")) {
		ret = -EINVAL;
		goto out_delete;
	}
X
Xiao Guangrong 已提交
1104 1105 1106 1107 1108

	/*
	 * Do not use 'isa' recorded in kvm_exit tracepoint since it is not
	 * traced in the old kernel.
	 */
D
David Ahern 已提交
1109
	ret = cpu_isa_config(kvm);
X
Xiao Guangrong 已提交
1110
	if (ret < 0)
1111 1112 1113
		goto out_delete;

	ret = perf_session__process_events(kvm->session);
X
Xiao Guangrong 已提交
1114

1115 1116 1117
out_delete:
	perf_session__delete(kvm->session);
	return ret;
X
Xiao Guangrong 已提交
1118 1119
}

1120 1121
static int parse_target_str(struct perf_kvm_stat *kvm)
{
1122 1123
	if (kvm->opts.target.pid) {
		kvm->pid_list = intlist__new(kvm->opts.target.pid);
1124 1125 1126 1127 1128 1129 1130 1131 1132
		if (kvm->pid_list == NULL) {
			pr_err("Error parsing process id string\n");
			return -EINVAL;
		}
	}

	return 0;
}

1133
static int kvm_events_report_vcpu(struct perf_kvm_stat *kvm)
X
Xiao Guangrong 已提交
1134 1135
{
	int ret = -EINVAL;
1136
	int vcpu = kvm->trace_vcpu;
X
Xiao Guangrong 已提交
1137

1138 1139 1140
	if (parse_target_str(kvm) != 0)
		goto exit;

X
Xiao Guangrong 已提交
1141 1142 1143
	if (!verify_vcpu(vcpu))
		goto exit;

1144
	if (!select_key(kvm))
X
Xiao Guangrong 已提交
1145 1146
		goto exit;

1147
	if (!register_kvm_events_ops(kvm))
X
Xiao Guangrong 已提交
1148 1149
		goto exit;

1150
	init_kvm_event_record(kvm);
X
Xiao Guangrong 已提交
1151 1152
	setup_pager();

1153
	ret = read_events(kvm);
X
Xiao Guangrong 已提交
1154 1155 1156
	if (ret)
		goto exit;

1157 1158 1159
	sort_result(kvm);
	print_result(kvm);

X
Xiao Guangrong 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
exit:
	return ret;
}

#define STRDUP_FAIL_EXIT(s)		\
	({	char *_p;		\
	_p = strdup(s);		\
		if (!_p)		\
			return -ENOMEM;	\
		_p;			\
	})

1172 1173 1174 1175 1176
int __weak setup_kvm_events_tp(struct perf_kvm_stat *kvm __maybe_unused)
{
	return 0;
}

1177 1178
static int
kvm_events_record(struct perf_kvm_stat *kvm, int argc, const char **argv)
X
Xiao Guangrong 已提交
1179
{
1180
	unsigned int rec_argc, i, j, events_tp_size;
X
Xiao Guangrong 已提交
1181
	const char **rec_argv;
1182 1183 1184 1185 1186 1187
	const char * const record_args[] = {
		"record",
		"-R",
		"-m", "1024",
		"-c", "1",
	};
1188 1189 1190 1191
	const char * const kvm_stat_record_usage[] = {
		"perf kvm stat record [<options>]",
		NULL
	};
1192
	const char * const *events_tp;
1193 1194
	int ret;

1195
	events_tp_size = 0;
1196 1197 1198 1199 1200
	ret = setup_kvm_events_tp(kvm);
	if (ret < 0) {
		pr_err("Unable to setup the kvm tracepoints\n");
		return ret;
	}
1201 1202 1203

	for (events_tp = kvm_events_tp; *events_tp; events_tp++)
		events_tp_size++;
X
Xiao Guangrong 已提交
1204

1205
	rec_argc = ARRAY_SIZE(record_args) + argc + 2 +
1206
		   2 * events_tp_size;
X
Xiao Guangrong 已提交
1207 1208 1209 1210 1211 1212 1213 1214
	rec_argv = calloc(rec_argc + 1, sizeof(char *));

	if (rec_argv == NULL)
		return -ENOMEM;

	for (i = 0; i < ARRAY_SIZE(record_args); i++)
		rec_argv[i] = STRDUP_FAIL_EXIT(record_args[i]);

1215
	for (j = 0; j < events_tp_size; j++) {
1216 1217 1218 1219
		rec_argv[i++] = "-e";
		rec_argv[i++] = STRDUP_FAIL_EXIT(kvm_events_tp[j]);
	}

X
Xiao Guangrong 已提交
1220
	rec_argv[i++] = STRDUP_FAIL_EXIT("-o");
1221
	rec_argv[i++] = STRDUP_FAIL_EXIT(kvm->file_name);
X
Xiao Guangrong 已提交
1222 1223 1224 1225

	for (j = 1; j < (unsigned int)argc; j++, i++)
		rec_argv[i] = argv[j];

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	set_option_flag(record_options, 'e', "event", PARSE_OPT_HIDDEN);
	set_option_flag(record_options, 0, "filter", PARSE_OPT_HIDDEN);
	set_option_flag(record_options, 'R', "raw-samples", PARSE_OPT_HIDDEN);

	set_option_flag(record_options, 'F', "freq", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 0, "group", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'g', NULL, PARSE_OPT_DISABLED);
	set_option_flag(record_options, 0, "call-graph", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'd', "data", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'T', "timestamp", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'P', "period", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'n', "no-samples", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'N', "no-buildid-cache", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'B', "no-buildid", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'G', "cgroup", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'b', "branch-any", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'j', "branch-filter", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 'W', "weight", PARSE_OPT_DISABLED);
	set_option_flag(record_options, 0, "transaction", PARSE_OPT_DISABLED);

	record_usage = kvm_stat_record_usage;
1247
	return cmd_record(i, rec_argv);
X
Xiao Guangrong 已提交
1248 1249
}

1250 1251
static int
kvm_events_report(struct perf_kvm_stat *kvm, int argc, const char **argv)
1252 1253 1254
{
	const struct option kvm_events_report_options[] = {
		OPT_STRING(0, "event", &kvm->report_event, "report event",
1255 1256
			   "event for reporting: vmexit, "
			   "mmio (x86 only), ioport (x86 only)"),
1257 1258 1259 1260 1261
		OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
			    "vcpu id to report"),
		OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
			    "key for sorting: sample(sort by samples number)"
			    " time (sort by avg time)"),
1262
		OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1263
			   "analyze events only for given process id(s)"),
1264
		OPT_BOOLEAN('f', "force", &kvm->force, "don't complain, do it"),
1265 1266
		OPT_END()
	};
X
Xiao Guangrong 已提交
1267

1268 1269 1270 1271
	const char * const kvm_events_report_usage[] = {
		"perf kvm stat report [<options>]",
		NULL
	};
X
Xiao Guangrong 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

	if (argc) {
		argc = parse_options(argc, argv,
				     kvm_events_report_options,
				     kvm_events_report_usage, 0);
		if (argc)
			usage_with_options(kvm_events_report_usage,
					   kvm_events_report_options);
	}

1282 1283 1284
	if (!kvm->opts.target.pid)
		kvm->opts.target.system_wide = true;

1285
	return kvm_events_report_vcpu(kvm);
X
Xiao Guangrong 已提交
1286 1287
}

1288
#ifdef HAVE_TIMERFD_SUPPORT
D
David Ahern 已提交
1289 1290 1291 1292 1293
static struct perf_evlist *kvm_live_event_list(void)
{
	struct perf_evlist *evlist;
	char *tp, *name, *sys;
	int err = -1;
1294
	const char * const *events_tp;
D
David Ahern 已提交
1295 1296 1297 1298 1299

	evlist = perf_evlist__new();
	if (evlist == NULL)
		return NULL;

1300
	for (events_tp = kvm_events_tp; *events_tp; events_tp++) {
D
David Ahern 已提交
1301

1302
		tp = strdup(*events_tp);
D
David Ahern 已提交
1303 1304 1305 1306 1307 1308 1309 1310
		if (tp == NULL)
			goto out;

		/* split tracepoint into subsystem and name */
		sys = tp;
		name = strchr(tp, ':');
		if (name == NULL) {
			pr_err("Error parsing %s tracepoint: subsystem delimiter not found\n",
1311
			       *events_tp);
D
David Ahern 已提交
1312 1313 1314 1315 1316 1317 1318
			free(tp);
			goto out;
		}
		*name = '\0';
		name++;

		if (perf_evlist__add_newtp(evlist, sys, name, NULL)) {
1319
			pr_err("Failed to add %s tracepoint to the list\n", *events_tp);
D
David Ahern 已提交
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
			free(tp);
			goto out;
		}

		free(tp);
	}

	err = 0;

out:
	if (err) {
		perf_evlist__delete(evlist);
		evlist = NULL;
	}

	return evlist;
}

static int kvm_events_live(struct perf_kvm_stat *kvm,
			   int argc, const char **argv)
{
	char errbuf[BUFSIZ];
	int err;

	const struct option live_options[] = {
		OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
			"record events on existing process id"),
1347 1348 1349
		OPT_CALLBACK('m', "mmap-pages", &kvm->opts.mmap_pages, "pages",
			"number of mmap data pages",
			perf_evlist__parse_mmap_pages),
D
David Ahern 已提交
1350 1351 1352 1353 1354 1355 1356
		OPT_INCR('v', "verbose", &verbose,
			"be more verbose (show counter open errors, etc)"),
		OPT_BOOLEAN('a', "all-cpus", &kvm->opts.target.system_wide,
			"system-wide collection from all CPUs"),
		OPT_UINTEGER('d', "display", &kvm->display_time,
			"time in seconds between display updates"),
		OPT_STRING(0, "event", &kvm->report_event, "report event",
1357 1358
			"event for reporting: "
			"vmexit, mmio (x86 only), ioport (x86 only)"),
D
David Ahern 已提交
1359 1360 1361 1362 1363
		OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
			"vcpu id to report"),
		OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
			"key for sorting: sample(sort by samples number)"
			" time (sort by avg time)"),
1364
		OPT_U64(0, "duration", &kvm->duration,
1365 1366 1367
			"show events other than"
			" HLT (x86 only) or Wait state (s390 only)"
			" that take longer than duration usecs"),
1368 1369
		OPT_UINTEGER(0, "proc-map-timeout", &kvm->opts.proc_map_timeout,
				"per thread proc mmap processing timeout in ms"),
D
David Ahern 已提交
1370 1371 1372 1373 1374 1375
		OPT_END()
	};
	const char * const live_usage[] = {
		"perf kvm stat live [<options>]",
		NULL
	};
1376
	struct perf_data data = {
1377 1378
		.mode = PERF_DATA_MODE_WRITE,
	};
D
David Ahern 已提交
1379 1380 1381 1382 1383 1384 1385 1386


	/* event handling */
	kvm->tool.sample = process_sample_event;
	kvm->tool.comm   = perf_event__process_comm;
	kvm->tool.exit   = perf_event__process_exit;
	kvm->tool.fork   = perf_event__process_fork;
	kvm->tool.lost   = process_lost_event;
1387
	kvm->tool.namespaces  = perf_event__process_namespaces;
1388
	kvm->tool.ordered_events = true;
D
David Ahern 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397
	perf_tool__fill_defaults(&kvm->tool);

	/* set defaults */
	kvm->display_time = 1;
	kvm->opts.user_interval = 1;
	kvm->opts.mmap_pages = 512;
	kvm->opts.target.uses_mmap = false;
	kvm->opts.target.uid_str = NULL;
	kvm->opts.target.uid = UINT_MAX;
1398
	kvm->opts.proc_map_timeout = 500;
D
David Ahern 已提交
1399

1400
	symbol__init(NULL);
D
David Ahern 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
	disable_buildid_cache();

	use_browser = 0;

	if (argc) {
		argc = parse_options(argc, argv, live_options,
				     live_usage, 0);
		if (argc)
			usage_with_options(live_usage, live_options);
	}

1412 1413
	kvm->duration *= NSEC_PER_USEC;   /* convert usec to nsec */

D
David Ahern 已提交
1414 1415 1416
	/*
	 * target related setups
	 */
1417
	err = target__validate(&kvm->opts.target);
D
David Ahern 已提交
1418
	if (err) {
1419
		target__strerror(&kvm->opts.target, err, errbuf, BUFSIZ);
D
David Ahern 已提交
1420 1421 1422
		ui__warning("%s", errbuf);
	}

1423
	if (target__none(&kvm->opts.target))
D
David Ahern 已提交
1424 1425 1426 1427 1428 1429
		kvm->opts.target.system_wide = true;


	/*
	 * generate the event list
	 */
1430 1431 1432 1433 1434 1435
	err = setup_kvm_events_tp(kvm);
	if (err < 0) {
		pr_err("Unable to setup the kvm tracepoints\n");
		return err;
	}

D
David Ahern 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
	kvm->evlist = kvm_live_event_list();
	if (kvm->evlist == NULL) {
		err = -1;
		goto out;
	}

	symbol_conf.nr_events = kvm->evlist->nr_entries;

	if (perf_evlist__create_maps(kvm->evlist, &kvm->opts.target) < 0)
		usage_with_options(live_usage, live_options);

	/*
	 * perf session
	 */
1450
	kvm->session = perf_session__new(&data, false, &kvm->tool);
D
David Ahern 已提交
1451
	if (kvm->session == NULL) {
1452
		err = -1;
D
David Ahern 已提交
1453 1454 1455 1456
		goto out;
	}
	kvm->session->evlist = kvm->evlist;
	perf_session__set_id_hdr_size(kvm->session);
1457
	ordered_events__set_copy_on_queue(&kvm->session->ordered_events, true);
1458
	machine__synthesize_threads(&kvm->session->machines.host, &kvm->opts.target,
1459 1460
				    kvm->evlist->threads, false,
				    kvm->opts.proc_map_timeout, 1);
D
David Ahern 已提交
1461 1462 1463 1464 1465 1466 1467
	err = kvm_live_open_events(kvm);
	if (err)
		goto out;

	err = kvm_events_live_report(kvm);

out:
1468
	perf_session__delete(kvm->session);
D
David Ahern 已提交
1469
	kvm->session = NULL;
1470
	perf_evlist__delete(kvm->evlist);
D
David Ahern 已提交
1471 1472 1473

	return err;
}
1474
#endif
D
David Ahern 已提交
1475

X
Xiao Guangrong 已提交
1476 1477 1478 1479 1480 1481 1482
static void print_kvm_stat_usage(void)
{
	printf("Usage: perf kvm stat <command>\n\n");

	printf("# Available commands:\n");
	printf("\trecord: record kvm events\n");
	printf("\treport: report statistical data of kvm events\n");
D
David Ahern 已提交
1483
	printf("\tlive:   live reporting of statistical data of kvm events\n");
X
Xiao Guangrong 已提交
1484 1485 1486 1487

	printf("\nOtherwise, it is the alias of 'perf stat':\n");
}

1488
static int kvm_cmd_stat(const char *file_name, int argc, const char **argv)
X
Xiao Guangrong 已提交
1489
{
1490 1491 1492 1493 1494 1495 1496 1497 1498
	struct perf_kvm_stat kvm = {
		.file_name = file_name,

		.trace_vcpu	= -1,
		.report_event	= "vmexit",
		.sort_key	= "sample",

	};

X
Xiao Guangrong 已提交
1499 1500 1501 1502 1503 1504
	if (argc == 1) {
		print_kvm_stat_usage();
		goto perf_stat;
	}

	if (!strncmp(argv[1], "rec", 3))
1505
		return kvm_events_record(&kvm, argc - 1, argv + 1);
X
Xiao Guangrong 已提交
1506 1507

	if (!strncmp(argv[1], "rep", 3))
1508
		return kvm_events_report(&kvm, argc - 1 , argv + 1);
X
Xiao Guangrong 已提交
1509

1510
#ifdef HAVE_TIMERFD_SUPPORT
D
David Ahern 已提交
1511 1512
	if (!strncmp(argv[1], "live", 4))
		return kvm_events_live(&kvm, argc - 1 , argv + 1);
1513
#endif
D
David Ahern 已提交
1514

X
Xiao Guangrong 已提交
1515
perf_stat:
1516
	return cmd_stat(argc, argv);
X
Xiao Guangrong 已提交
1517
}
1518
#endif /* HAVE_KVM_STAT_SUPPORT */
X
Xiao Guangrong 已提交
1519

1520
static int __cmd_record(const char *file_name, int argc, const char **argv)
1521 1522 1523 1524 1525 1526 1527 1528
{
	int rec_argc, i = 0, j;
	const char **rec_argv;

	rec_argc = argc + 2;
	rec_argv = calloc(rec_argc + 1, sizeof(char *));
	rec_argv[i++] = strdup("record");
	rec_argv[i++] = strdup("-o");
1529
	rec_argv[i++] = strdup(file_name);
1530 1531 1532 1533 1534
	for (j = 1; j < argc; j++, i++)
		rec_argv[i] = argv[j];

	BUG_ON(i != rec_argc);

1535
	return cmd_record(i, rec_argv);
1536 1537
}

1538
static int __cmd_report(const char *file_name, int argc, const char **argv)
1539 1540 1541 1542 1543 1544 1545 1546
{
	int rec_argc, i = 0, j;
	const char **rec_argv;

	rec_argc = argc + 2;
	rec_argv = calloc(rec_argc + 1, sizeof(char *));
	rec_argv[i++] = strdup("report");
	rec_argv[i++] = strdup("-i");
1547
	rec_argv[i++] = strdup(file_name);
1548 1549 1550 1551 1552
	for (j = 1; j < argc; j++, i++)
		rec_argv[i] = argv[j];

	BUG_ON(i != rec_argc);

1553
	return cmd_report(i, rec_argv);
1554 1555
}

1556 1557
static int
__cmd_buildid_list(const char *file_name, int argc, const char **argv)
1558 1559 1560 1561 1562 1563 1564 1565
{
	int rec_argc, i = 0, j;
	const char **rec_argv;

	rec_argc = argc + 2;
	rec_argv = calloc(rec_argc + 1, sizeof(char *));
	rec_argv[i++] = strdup("buildid-list");
	rec_argv[i++] = strdup("-i");
1566
	rec_argv[i++] = strdup(file_name);
1567 1568 1569 1570 1571
	for (j = 1; j < argc; j++, i++)
		rec_argv[i] = argv[j];

	BUG_ON(i != rec_argc);

1572
	return cmd_buildid_list(i, rec_argv);
1573 1574
}

1575
int cmd_kvm(int argc, const char **argv)
1576
{
1577
	const char *file_name = NULL;
1578
	const struct option kvm_options[] = {
1579
		OPT_STRING('i', "input", &file_name, "file",
1580
			   "Input file name"),
1581
		OPT_STRING('o', "output", &file_name, "file",
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
			   "Output file name"),
		OPT_BOOLEAN(0, "guest", &perf_guest,
			    "Collect guest os data"),
		OPT_BOOLEAN(0, "host", &perf_host,
			    "Collect host os data"),
		OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
			   "guest mount directory under which every guest os"
			   " instance has a subdir"),
		OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
			   "file", "file saving guest os vmlinux"),
		OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
			   "file", "file saving guest os /proc/kallsyms"),
		OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
			   "file", "file saving guest os /proc/modules"),
1596 1597
		OPT_INCR('v', "verbose", &verbose,
			    "be more verbose (show counter open errors, etc)"),
1598 1599 1600
		OPT_END()
	};

1601 1602 1603
	const char *const kvm_subcommands[] = { "top", "record", "report", "diff",
						"buildid-list", "stat", NULL };
	const char *kvm_usage[] = { NULL, NULL };
1604

1605 1606
	perf_host  = 0;
	perf_guest = 1;
1607

1608 1609
	argc = parse_options_subcommand(argc, argv, kvm_options, kvm_subcommands, kvm_usage,
					PARSE_OPT_STOP_AT_NON_OPTION);
1610 1611 1612 1613 1614 1615
	if (!argc)
		usage_with_options(kvm_usage, kvm_options);

	if (!perf_host)
		perf_guest = 1;

1616
	if (!file_name) {
1617
		file_name = get_filename_for_perf_kvm();
1618

1619
		if (!file_name) {
1620 1621 1622
			pr_err("Failed to allocate memory for filename\n");
			return -ENOMEM;
		}
1623 1624 1625
	}

	if (!strncmp(argv[0], "rec", 3))
1626
		return __cmd_record(file_name, argc, argv);
1627
	else if (!strncmp(argv[0], "rep", 3))
1628
		return __cmd_report(file_name, argc, argv);
1629
	else if (!strncmp(argv[0], "diff", 4))
1630
		return cmd_diff(argc, argv);
1631
	else if (!strncmp(argv[0], "top", 3))
1632
		return cmd_top(argc, argv);
1633
	else if (!strncmp(argv[0], "buildid-list", 12))
1634
		return __cmd_buildid_list(file_name, argc, argv);
1635
#ifdef HAVE_KVM_STAT_SUPPORT
X
Xiao Guangrong 已提交
1636
	else if (!strncmp(argv[0], "stat", 4))
1637
		return kvm_cmd_stat(file_name, argc, argv);
1638
#endif
1639 1640 1641 1642 1643
	else
		usage_with_options(kvm_usage, kvm_options);

	return 0;
}