xref: /openbmc/linux/tools/perf/builtin-kvm.c (revision ece7f7c0)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "builtin.h"
3 #include "perf.h"
4 
5 #include "util/build-id.h"
6 #include "util/evsel.h"
7 #include "util/evlist.h"
8 #include "util/mmap.h"
9 #include "util/term.h"
10 #include "util/symbol.h"
11 #include "util/thread.h"
12 #include "util/header.h"
13 #include "util/session.h"
14 #include "util/intlist.h"
15 #include <subcmd/pager.h>
16 #include <subcmd/parse-options.h>
17 #include "util/trace-event.h"
18 #include "util/debug.h"
19 #include "util/tool.h"
20 #include "util/stat.h"
21 #include "util/synthetic-events.h"
22 #include "util/top.h"
23 #include "util/data.h"
24 #include "util/ordered-events.h"
25 #include "util/kvm-stat.h"
26 #include "ui/browsers/hists.h"
27 #include "ui/progress.h"
28 #include "ui/ui.h"
29 #include "util/string2.h"
30 
31 #include <sys/prctl.h>
32 #ifdef HAVE_TIMERFD_SUPPORT
33 #include <sys/timerfd.h>
34 #endif
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <fcntl.h>
39 
40 #include <linux/err.h>
41 #include <linux/kernel.h>
42 #include <linux/string.h>
43 #include <linux/time64.h>
44 #include <linux/zalloc.h>
45 #include <errno.h>
46 #include <inttypes.h>
47 #include <poll.h>
48 #include <termios.h>
49 #include <semaphore.h>
50 #include <signal.h>
51 #include <math.h>
52 #include <perf/mmap.h>
53 
54 #if defined(HAVE_KVM_STAT_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
55 #define GET_EVENT_KEY(func, field)					\
56 static u64 get_event_ ##func(struct kvm_event *event, int vcpu)		\
57 {									\
58 	if (vcpu == -1)							\
59 		return event->total.field;				\
60 									\
61 	if (vcpu >= event->max_vcpu)					\
62 		return 0;						\
63 									\
64 	return event->vcpu[vcpu].field;					\
65 }
66 
67 #define COMPARE_EVENT_KEY(func, field)					\
68 GET_EVENT_KEY(func, field)						\
69 static int64_t cmp_event_ ## func(struct kvm_event *one,		\
70 			      struct kvm_event *two, int vcpu)		\
71 {									\
72 	return get_event_ ##func(one, vcpu) -				\
73 	       get_event_ ##func(two, vcpu);				\
74 }
75 
76 COMPARE_EVENT_KEY(time, time);
77 COMPARE_EVENT_KEY(max, stats.max);
78 COMPARE_EVENT_KEY(min, stats.min);
79 COMPARE_EVENT_KEY(count, stats.n);
80 COMPARE_EVENT_KEY(mean, stats.mean);
81 
82 struct kvm_hists {
83 	struct hists		hists;
84 	struct perf_hpp_list	list;
85 };
86 
87 struct kvm_dimension {
88 	const char *name;
89 	const char *header;
90 	int width;
91 	int64_t (*cmp)(struct perf_hpp_fmt *fmt, struct hist_entry *left,
92 		       struct hist_entry *right);
93 	int (*entry)(struct perf_hpp_fmt *fmt, struct perf_hpp *hpp,
94 		     struct hist_entry *he);
95 };
96 
97 struct kvm_fmt {
98 	struct perf_hpp_fmt	fmt;
99 	struct kvm_dimension	*dim;
100 };
101 
102 static struct kvm_hists kvm_hists;
103 
104 static int64_t ev_name_cmp(struct perf_hpp_fmt *fmt __maybe_unused,
105 			   struct hist_entry *left,
106 			   struct hist_entry *right)
107 {
108 	/* Return opposite number for sorting in alphabetical order */
109 	return -strcmp(left->kvm_info->name, right->kvm_info->name);
110 }
111 
112 static int fmt_width(struct perf_hpp_fmt *fmt,
113 		     struct perf_hpp *hpp __maybe_unused,
114 		     struct hists *hists __maybe_unused);
115 
116 static int ev_name_entry(struct perf_hpp_fmt *fmt, struct perf_hpp *hpp,
117 			 struct hist_entry *he)
118 {
119 	int width = fmt_width(fmt, hpp, he->hists);
120 
121 	return scnprintf(hpp->buf, hpp->size, "%*s", width, he->kvm_info->name);
122 }
123 
124 static struct kvm_dimension dim_event = {
125 	.header		= "Event name",
126 	.name		= "ev_name",
127 	.cmp		= ev_name_cmp,
128 	.entry		= ev_name_entry,
129 	.width		= 40,
130 };
131 
132 #define EV_METRIC_CMP(metric)						\
133 static int64_t ev_cmp_##metric(struct perf_hpp_fmt *fmt __maybe_unused,	\
134 			       struct hist_entry *left,			\
135 			       struct hist_entry *right)		\
136 {									\
137 	struct kvm_event *event_left;					\
138 	struct kvm_event *event_right;					\
139 	struct perf_kvm_stat *perf_kvm;					\
140 									\
141 	event_left  = container_of(left, struct kvm_event, he);		\
142 	event_right = container_of(right, struct kvm_event, he);	\
143 									\
144 	perf_kvm = event_left->perf_kvm;				\
145 	return cmp_event_##metric(event_left, event_right,		\
146 				  perf_kvm->trace_vcpu);		\
147 }
148 
149 EV_METRIC_CMP(time)
150 EV_METRIC_CMP(count)
151 EV_METRIC_CMP(max)
152 EV_METRIC_CMP(min)
153 EV_METRIC_CMP(mean)
154 
155 #define EV_METRIC_ENTRY(metric)						\
156 static int ev_entry_##metric(struct perf_hpp_fmt *fmt,			\
157 			     struct perf_hpp *hpp,			\
158 			     struct hist_entry *he)			\
159 {									\
160 	struct kvm_event *event;					\
161 	int width = fmt_width(fmt, hpp, he->hists);			\
162 	struct perf_kvm_stat *perf_kvm;					\
163 									\
164 	event = container_of(he, struct kvm_event, he);			\
165 	perf_kvm = event->perf_kvm;					\
166 	return scnprintf(hpp->buf, hpp->size, "%*lu", width,		\
167 		get_event_##metric(event, perf_kvm->trace_vcpu));	\
168 }
169 
170 EV_METRIC_ENTRY(time)
171 EV_METRIC_ENTRY(count)
172 EV_METRIC_ENTRY(max)
173 EV_METRIC_ENTRY(min)
174 
175 static struct kvm_dimension dim_time = {
176 	.header		= "Time (ns)",
177 	.name		= "time",
178 	.cmp		= ev_cmp_time,
179 	.entry		= ev_entry_time,
180 	.width		= 12,
181 };
182 
183 static struct kvm_dimension dim_count = {
184 	.header		= "Samples",
185 	.name		= "sample",
186 	.cmp		= ev_cmp_count,
187 	.entry		= ev_entry_count,
188 	.width		= 12,
189 };
190 
191 static struct kvm_dimension dim_max_time = {
192 	.header		= "Max Time (ns)",
193 	.name		= "max_t",
194 	.cmp		= ev_cmp_max,
195 	.entry		= ev_entry_max,
196 	.width		= 14,
197 };
198 
199 static struct kvm_dimension dim_min_time = {
200 	.header		= "Min Time (ns)",
201 	.name		= "min_t",
202 	.cmp		= ev_cmp_min,
203 	.entry		= ev_entry_min,
204 	.width		= 14,
205 };
206 
207 static int ev_entry_mean(struct perf_hpp_fmt *fmt, struct perf_hpp *hpp,
208 			 struct hist_entry *he)
209 {
210 	struct kvm_event *event;
211 	int width = fmt_width(fmt, hpp, he->hists);
212 	struct perf_kvm_stat *perf_kvm;
213 
214 	event = container_of(he, struct kvm_event, he);
215 	perf_kvm = event->perf_kvm;
216 	return scnprintf(hpp->buf, hpp->size, "%*lu", width,
217 			 get_event_mean(event, perf_kvm->trace_vcpu));
218 }
219 
220 static struct kvm_dimension dim_mean_time = {
221 	.header		= "Mean Time (ns)",
222 	.name		= "mean_t",
223 	.cmp		= ev_cmp_mean,
224 	.entry		= ev_entry_mean,
225 	.width		= 14,
226 };
227 
228 #define PERC_STR(__s, __v)				\
229 ({							\
230 	scnprintf(__s, sizeof(__s), "%.2F%%", __v);	\
231 	__s;						\
232 })
233 
234 static double percent(u64 st, u64 tot)
235 {
236 	return tot ? 100. * (double) st / (double) tot : 0;
237 }
238 
239 #define EV_METRIC_PERCENT(metric)					\
240 static int ev_percent_##metric(struct hist_entry *he)			\
241 {									\
242 	struct kvm_event *event;					\
243 	struct perf_kvm_stat *perf_kvm;					\
244 									\
245 	event = container_of(he, struct kvm_event, he);			\
246 	perf_kvm = event->perf_kvm;					\
247 									\
248 	return percent(get_event_##metric(event, perf_kvm->trace_vcpu),	\
249 		       perf_kvm->total_##metric);			\
250 }
251 
252 EV_METRIC_PERCENT(time)
253 EV_METRIC_PERCENT(count)
254 
255 static int ev_entry_time_precent(struct perf_hpp_fmt *fmt,
256 				 struct perf_hpp *hpp,
257 				 struct hist_entry *he)
258 {
259 	int width = fmt_width(fmt, hpp, he->hists);
260 	double per;
261 	char buf[10];
262 
263 	per = ev_percent_time(he);
264 	return scnprintf(hpp->buf, hpp->size, "%*s", width, PERC_STR(buf, per));
265 }
266 
267 static int64_t
268 ev_cmp_time_precent(struct perf_hpp_fmt *fmt __maybe_unused,
269 		    struct hist_entry *left, struct hist_entry *right)
270 {
271 	double per_left;
272 	double per_right;
273 
274 	per_left  = ev_percent_time(left);
275 	per_right = ev_percent_time(right);
276 
277 	return per_left - per_right;
278 }
279 
280 static struct kvm_dimension dim_time_percent = {
281 	.header		= "Time%",
282 	.name		= "percent_time",
283 	.cmp		= ev_cmp_time_precent,
284 	.entry		= ev_entry_time_precent,
285 	.width		= 12,
286 };
287 
288 static int ev_entry_count_precent(struct perf_hpp_fmt *fmt,
289 				  struct perf_hpp *hpp,
290 				  struct hist_entry *he)
291 {
292 	int width = fmt_width(fmt, hpp, he->hists);
293 	double per;
294 	char buf[10];
295 
296 	per = ev_percent_count(he);
297 	return scnprintf(hpp->buf, hpp->size, "%*s", width, PERC_STR(buf, per));
298 }
299 
300 static int64_t
301 ev_cmp_count_precent(struct perf_hpp_fmt *fmt __maybe_unused,
302 		     struct hist_entry *left, struct hist_entry *right)
303 {
304 	double per_left;
305 	double per_right;
306 
307 	per_left  = ev_percent_count(left);
308 	per_right = ev_percent_count(right);
309 
310 	return per_left - per_right;
311 }
312 
313 static struct kvm_dimension dim_count_percent = {
314 	.header		= "Sample%",
315 	.name		= "percent_sample",
316 	.cmp		= ev_cmp_count_precent,
317 	.entry		= ev_entry_count_precent,
318 	.width		= 12,
319 };
320 
321 static struct kvm_dimension *dimensions[] = {
322 	&dim_event,
323 	&dim_time,
324 	&dim_time_percent,
325 	&dim_count,
326 	&dim_count_percent,
327 	&dim_max_time,
328 	&dim_min_time,
329 	&dim_mean_time,
330 	NULL,
331 };
332 
333 static int fmt_width(struct perf_hpp_fmt *fmt,
334 		     struct perf_hpp *hpp __maybe_unused,
335 		     struct hists *hists __maybe_unused)
336 {
337 	struct kvm_fmt *kvm_fmt;
338 
339 	kvm_fmt = container_of(fmt, struct kvm_fmt, fmt);
340 	return kvm_fmt->dim->width;
341 }
342 
343 static int fmt_header(struct perf_hpp_fmt *fmt, struct perf_hpp *hpp,
344 		      struct hists *hists, int line __maybe_unused,
345 		      int *span __maybe_unused)
346 {
347 	struct kvm_fmt *kvm_fmt;
348 	struct kvm_dimension *dim;
349 	int width = fmt_width(fmt, hpp, hists);
350 
351 	kvm_fmt = container_of(fmt, struct kvm_fmt, fmt);
352 	dim = kvm_fmt->dim;
353 
354 	return scnprintf(hpp->buf, hpp->size, "%*s", width, dim->header);
355 }
356 
357 static bool fmt_equal(struct perf_hpp_fmt *a, struct perf_hpp_fmt *b)
358 {
359 	struct kvm_fmt *kvm_fmt_a = container_of(a, struct kvm_fmt, fmt);
360 	struct kvm_fmt *kvm_fmt_b = container_of(b, struct kvm_fmt, fmt);
361 
362 	return kvm_fmt_a->dim == kvm_fmt_b->dim;
363 }
364 
365 static void fmt_free(struct perf_hpp_fmt *fmt)
366 {
367 	struct kvm_fmt *kvm_fmt;
368 
369 	kvm_fmt = container_of(fmt, struct kvm_fmt, fmt);
370 	free(kvm_fmt);
371 }
372 
373 static struct kvm_dimension *get_dimension(const char *name)
374 {
375 	unsigned int i;
376 
377 	for (i = 0; dimensions[i] != NULL; i++) {
378 		if (!strcmp(dimensions[i]->name, name))
379 			return dimensions[i];
380 	}
381 
382 	return NULL;
383 }
384 
385 static struct kvm_fmt *get_format(const char *name)
386 {
387 	struct kvm_dimension *dim = get_dimension(name);
388 	struct kvm_fmt *kvm_fmt;
389 	struct perf_hpp_fmt *fmt;
390 
391 	if (!dim)
392 		return NULL;
393 
394 	kvm_fmt = zalloc(sizeof(*kvm_fmt));
395 	if (!kvm_fmt)
396 		return NULL;
397 
398 	kvm_fmt->dim = dim;
399 
400 	fmt = &kvm_fmt->fmt;
401 	INIT_LIST_HEAD(&fmt->list);
402 	INIT_LIST_HEAD(&fmt->sort_list);
403 	fmt->cmp	= dim->cmp;
404 	fmt->sort	= dim->cmp;
405 	fmt->color	= NULL;
406 	fmt->entry	= dim->entry;
407 	fmt->header	= fmt_header;
408 	fmt->width	= fmt_width;
409 	fmt->collapse	= dim->cmp;
410 	fmt->equal	= fmt_equal;
411 	fmt->free	= fmt_free;
412 
413 	return kvm_fmt;
414 }
415 
416 static int kvm_hists__init_output(struct perf_hpp_list *hpp_list, char *name)
417 {
418 	struct kvm_fmt *kvm_fmt = get_format(name);
419 
420 	if (!kvm_fmt) {
421 		pr_warning("Fail to find format for output field %s.\n", name);
422 		return -EINVAL;
423 	}
424 
425 	perf_hpp_list__column_register(hpp_list, &kvm_fmt->fmt);
426 	return 0;
427 }
428 
429 static int kvm_hists__init_sort(struct perf_hpp_list *hpp_list, char *name)
430 {
431 	struct kvm_fmt *kvm_fmt = get_format(name);
432 
433 	if (!kvm_fmt) {
434 		pr_warning("Fail to find format for sorting %s.\n", name);
435 		return -EINVAL;
436 	}
437 
438 	perf_hpp_list__register_sort_field(hpp_list, &kvm_fmt->fmt);
439 	return 0;
440 }
441 
442 static int kvm_hpp_list__init(char *list,
443 			      struct perf_hpp_list *hpp_list,
444 			      int (*fn)(struct perf_hpp_list *hpp_list,
445 					char *name))
446 {
447 	char *tmp, *tok;
448 	int ret;
449 
450 	if (!list || !fn)
451 		return 0;
452 
453 	for (tok = strtok_r(list, ", ", &tmp); tok;
454 	     tok = strtok_r(NULL, ", ", &tmp)) {
455 		ret = fn(hpp_list, tok);
456 		if (!ret)
457 			continue;
458 
459 		/* Handle errors */
460 		if (ret == -EINVAL)
461 			pr_err("Invalid field key: '%s'", tok);
462 		else if (ret == -ESRCH)
463 			pr_err("Unknown field key: '%s'", tok);
464 		else
465 			pr_err("Fail to initialize for field key: '%s'", tok);
466 
467 		break;
468 	}
469 
470 	return ret;
471 }
472 
473 static int kvm_hpp_list__parse(struct perf_hpp_list *hpp_list,
474 			       const char *output_, const char *sort_)
475 {
476 	char *output = output_ ? strdup(output_) : NULL;
477 	char *sort = sort_ ? strdup(sort_) : NULL;
478 	int ret;
479 
480 	ret = kvm_hpp_list__init(output, hpp_list, kvm_hists__init_output);
481 	if (ret)
482 		goto out;
483 
484 	ret = kvm_hpp_list__init(sort, hpp_list, kvm_hists__init_sort);
485 	if (ret)
486 		goto out;
487 
488 	/* Copy sort keys to output fields */
489 	perf_hpp__setup_output_field(hpp_list);
490 
491 	/* and then copy output fields to sort keys */
492 	perf_hpp__append_sort_keys(hpp_list);
493 out:
494 	free(output);
495 	free(sort);
496 	return ret;
497 }
498 
499 static int kvm_hists__init(void)
500 {
501 	kvm_hists.list.nr_header_lines = 1;
502 	__hists__init(&kvm_hists.hists, &kvm_hists.list);
503 	perf_hpp_list__init(&kvm_hists.list);
504 	return kvm_hpp_list__parse(&kvm_hists.list, NULL, "ev_name");
505 }
506 
507 static int kvm_hists__reinit(const char *output, const char *sort)
508 {
509 	perf_hpp__reset_output_field(&kvm_hists.list);
510 	return kvm_hpp_list__parse(&kvm_hists.list, output, sort);
511 }
512 static void print_result(struct perf_kvm_stat *kvm);
513 
514 #ifdef HAVE_SLANG_SUPPORT
515 static void kvm_browser__update_nr_entries(struct hist_browser *hb)
516 {
517 	struct rb_node *nd = rb_first_cached(&hb->hists->entries);
518 	u64 nr_entries = 0;
519 
520 	for (; nd; nd = rb_next(nd)) {
521 		struct hist_entry *he = rb_entry(nd, struct hist_entry,
522 						 rb_node);
523 
524 		if (!he->filtered)
525 			nr_entries++;
526 	}
527 
528 	hb->nr_non_filtered_entries = nr_entries;
529 }
530 
531 static int kvm_browser__title(struct hist_browser *browser,
532 			      char *buf, size_t size)
533 {
534 	scnprintf(buf, size, "KVM event statistics (%lu entries)",
535 		  browser->nr_non_filtered_entries);
536 	return 0;
537 }
538 
539 static struct hist_browser*
540 perf_kvm_browser__new(struct hists *hists)
541 {
542 	struct hist_browser *browser = hist_browser__new(hists);
543 
544 	if (browser)
545 		browser->title = kvm_browser__title;
546 
547 	return browser;
548 }
549 
550 static int kvm__hists_browse(struct hists *hists)
551 {
552 	struct hist_browser *browser;
553 	int key = -1;
554 
555 	browser = perf_kvm_browser__new(hists);
556 	if (browser == NULL)
557 		return -1;
558 
559 	/* reset abort key so that it can get Ctrl-C as a key */
560 	SLang_reset_tty();
561 	SLang_init_tty(0, 0, 0);
562 
563 	kvm_browser__update_nr_entries(browser);
564 
565 	while (1) {
566 		key = hist_browser__run(browser, "? - help", true, 0);
567 
568 		switch (key) {
569 		case 'q':
570 			goto out;
571 		default:
572 			break;
573 		}
574 	}
575 
576 out:
577 	hist_browser__delete(browser);
578 	return 0;
579 }
580 
581 static void kvm_display(struct perf_kvm_stat *kvm)
582 {
583 	if (!use_browser)
584 		print_result(kvm);
585 	else
586 		kvm__hists_browse(&kvm_hists.hists);
587 }
588 
589 #else
590 
591 static void kvm_display(struct perf_kvm_stat *kvm)
592 {
593 	use_browser = 0;
594 	print_result(kvm);
595 }
596 
597 #endif /* HAVE_SLANG_SUPPORT */
598 
599 #endif // defined(HAVE_KVM_STAT_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
600 
601 static const char *get_filename_for_perf_kvm(void)
602 {
603 	const char *filename;
604 
605 	if (perf_host && !perf_guest)
606 		filename = strdup("perf.data.host");
607 	else if (!perf_host && perf_guest)
608 		filename = strdup("perf.data.guest");
609 	else
610 		filename = strdup("perf.data.kvm");
611 
612 	return filename;
613 }
614 
615 #if defined(HAVE_KVM_STAT_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
616 
617 void exit_event_get_key(struct evsel *evsel,
618 			struct perf_sample *sample,
619 			struct event_key *key)
620 {
621 	key->info = 0;
622 	key->key  = evsel__intval(evsel, sample, kvm_exit_reason);
623 }
624 
625 bool kvm_exit_event(struct evsel *evsel)
626 {
627 	return !strcmp(evsel->name, kvm_exit_trace);
628 }
629 
630 bool exit_event_begin(struct evsel *evsel,
631 		      struct perf_sample *sample, struct event_key *key)
632 {
633 	if (kvm_exit_event(evsel)) {
634 		exit_event_get_key(evsel, sample, key);
635 		return true;
636 	}
637 
638 	return false;
639 }
640 
641 bool kvm_entry_event(struct evsel *evsel)
642 {
643 	return !strcmp(evsel->name, kvm_entry_trace);
644 }
645 
646 bool exit_event_end(struct evsel *evsel,
647 		    struct perf_sample *sample __maybe_unused,
648 		    struct event_key *key __maybe_unused)
649 {
650 	return kvm_entry_event(evsel);
651 }
652 
653 static const char *get_exit_reason(struct perf_kvm_stat *kvm,
654 				   struct exit_reasons_table *tbl,
655 				   u64 exit_code)
656 {
657 	while (tbl->reason != NULL) {
658 		if (tbl->exit_code == exit_code)
659 			return tbl->reason;
660 		tbl++;
661 	}
662 
663 	pr_err("unknown kvm exit code:%lld on %s\n",
664 		(unsigned long long)exit_code, kvm->exit_reasons_isa);
665 	return "UNKNOWN";
666 }
667 
668 void exit_event_decode_key(struct perf_kvm_stat *kvm,
669 			   struct event_key *key,
670 			   char *decode)
671 {
672 	const char *exit_reason = get_exit_reason(kvm, key->exit_reasons,
673 						  key->key);
674 
675 	scnprintf(decode, KVM_EVENT_NAME_LEN, "%s", exit_reason);
676 }
677 
678 static bool register_kvm_events_ops(struct perf_kvm_stat *kvm)
679 {
680 	struct kvm_reg_events_ops *events_ops = kvm_reg_events_ops;
681 
682 	for (events_ops = kvm_reg_events_ops; events_ops->name; events_ops++) {
683 		if (!strcmp(events_ops->name, kvm->report_event)) {
684 			kvm->events_ops = events_ops->ops;
685 			return true;
686 		}
687 	}
688 
689 	return false;
690 }
691 
692 struct vcpu_event_record {
693 	int vcpu_id;
694 	u64 start_time;
695 	struct kvm_event *last_event;
696 };
697 
698 #ifdef HAVE_TIMERFD_SUPPORT
699 static void clear_events_cache_stats(void)
700 {
701 	struct rb_root_cached *root;
702 	struct rb_node *nd;
703 	struct kvm_event *event;
704 	int i;
705 
706 	if (hists__has(&kvm_hists.hists, need_collapse))
707 		root = &kvm_hists.hists.entries_collapsed;
708 	else
709 		root = kvm_hists.hists.entries_in;
710 
711 	for (nd = rb_first_cached(root); nd; nd = rb_next(nd)) {
712 		struct hist_entry *he;
713 
714 		he = rb_entry(nd, struct hist_entry, rb_node_in);
715 		event = container_of(he, struct kvm_event, he);
716 
717 		/* reset stats for event */
718 		event->total.time = 0;
719 		init_stats(&event->total.stats);
720 
721 		for (i = 0; i < event->max_vcpu; ++i) {
722 			event->vcpu[i].time = 0;
723 			init_stats(&event->vcpu[i].stats);
724 		}
725 	}
726 }
727 #endif
728 
729 static bool kvm_event_expand(struct kvm_event *event, int vcpu_id)
730 {
731 	int old_max_vcpu = event->max_vcpu;
732 	void *prev;
733 
734 	if (vcpu_id < event->max_vcpu)
735 		return true;
736 
737 	while (event->max_vcpu <= vcpu_id)
738 		event->max_vcpu += DEFAULT_VCPU_NUM;
739 
740 	prev = event->vcpu;
741 	event->vcpu = realloc(event->vcpu,
742 			      event->max_vcpu * sizeof(*event->vcpu));
743 	if (!event->vcpu) {
744 		free(prev);
745 		pr_err("Not enough memory\n");
746 		return false;
747 	}
748 
749 	memset(event->vcpu + old_max_vcpu, 0,
750 	       (event->max_vcpu - old_max_vcpu) * sizeof(*event->vcpu));
751 	return true;
752 }
753 
754 static void *kvm_he_zalloc(size_t size)
755 {
756 	struct kvm_event *kvm_ev;
757 
758 	kvm_ev = zalloc(size + sizeof(*kvm_ev));
759 	if (!kvm_ev)
760 		return NULL;
761 
762 	init_stats(&kvm_ev->total.stats);
763 	hists__inc_nr_samples(&kvm_hists.hists, 0);
764 	return &kvm_ev->he;
765 }
766 
767 static void kvm_he_free(void *he)
768 {
769 	struct kvm_event *kvm_ev;
770 
771 	kvm_ev = container_of(he, struct kvm_event, he);
772 	free(kvm_ev);
773 }
774 
775 static struct hist_entry_ops kvm_ev_entry_ops = {
776 	.new	= kvm_he_zalloc,
777 	.free	= kvm_he_free,
778 };
779 
780 static struct kvm_event *find_create_kvm_event(struct perf_kvm_stat *kvm,
781 					       struct event_key *key,
782 					       struct perf_sample *sample)
783 {
784 	struct kvm_event *event;
785 	struct hist_entry *he;
786 	struct kvm_info *ki;
787 
788 	BUG_ON(key->key == INVALID_KEY);
789 
790 	ki = kvm_info__new();
791 	if (!ki) {
792 		pr_err("Failed to allocate kvm info\n");
793 		return NULL;
794 	}
795 
796 	kvm->events_ops->decode_key(kvm, key, ki->name);
797 	he = hists__add_entry_ops(&kvm_hists.hists, &kvm_ev_entry_ops,
798 				  &kvm->al, NULL, NULL, NULL, ki, sample, true);
799 	if (he == NULL) {
800 		pr_err("Failed to allocate hist entry\n");
801 		free(ki);
802 		return NULL;
803 	}
804 
805 	event = container_of(he, struct kvm_event, he);
806 	if (!event->perf_kvm) {
807 		event->perf_kvm = kvm;
808 		event->key = *key;
809 	}
810 
811 	return event;
812 }
813 
814 static bool handle_begin_event(struct perf_kvm_stat *kvm,
815 			       struct vcpu_event_record *vcpu_record,
816 			       struct event_key *key,
817 			       struct perf_sample *sample)
818 {
819 	struct kvm_event *event = NULL;
820 
821 	if (key->key != INVALID_KEY)
822 		event = find_create_kvm_event(kvm, key, sample);
823 
824 	vcpu_record->last_event = event;
825 	vcpu_record->start_time = sample->time;
826 	return true;
827 }
828 
829 static void
830 kvm_update_event_stats(struct kvm_event_stats *kvm_stats, u64 time_diff)
831 {
832 	kvm_stats->time += time_diff;
833 	update_stats(&kvm_stats->stats, time_diff);
834 }
835 
836 static double kvm_event_rel_stddev(int vcpu_id, struct kvm_event *event)
837 {
838 	struct kvm_event_stats *kvm_stats = &event->total;
839 
840 	if (vcpu_id != -1)
841 		kvm_stats = &event->vcpu[vcpu_id];
842 
843 	return rel_stddev_stats(stddev_stats(&kvm_stats->stats),
844 				avg_stats(&kvm_stats->stats));
845 }
846 
847 static bool update_kvm_event(struct perf_kvm_stat *kvm,
848 			     struct kvm_event *event, int vcpu_id,
849 			     u64 time_diff)
850 {
851 	/* Update overall statistics */
852 	kvm->total_count++;
853 	kvm->total_time += time_diff;
854 
855 	if (vcpu_id == -1) {
856 		kvm_update_event_stats(&event->total, time_diff);
857 		return true;
858 	}
859 
860 	if (!kvm_event_expand(event, vcpu_id))
861 		return false;
862 
863 	kvm_update_event_stats(&event->vcpu[vcpu_id], time_diff);
864 	return true;
865 }
866 
867 static bool is_child_event(struct perf_kvm_stat *kvm,
868 			   struct evsel *evsel,
869 			   struct perf_sample *sample,
870 			   struct event_key *key)
871 {
872 	struct child_event_ops *child_ops;
873 
874 	child_ops = kvm->events_ops->child_ops;
875 
876 	if (!child_ops)
877 		return false;
878 
879 	for (; child_ops->name; child_ops++) {
880 		if (!strcmp(evsel->name, child_ops->name)) {
881 			child_ops->get_key(evsel, sample, key);
882 			return true;
883 		}
884 	}
885 
886 	return false;
887 }
888 
889 static bool handle_child_event(struct perf_kvm_stat *kvm,
890 			       struct vcpu_event_record *vcpu_record,
891 			       struct event_key *key,
892 			       struct perf_sample *sample)
893 {
894 	struct kvm_event *event = NULL;
895 
896 	if (key->key != INVALID_KEY)
897 		event = find_create_kvm_event(kvm, key, sample);
898 
899 	vcpu_record->last_event = event;
900 
901 	return true;
902 }
903 
904 static bool skip_event(const char *event)
905 {
906 	const char * const *skip_events;
907 
908 	for (skip_events = kvm_skip_events; *skip_events; skip_events++)
909 		if (!strcmp(event, *skip_events))
910 			return true;
911 
912 	return false;
913 }
914 
915 static bool handle_end_event(struct perf_kvm_stat *kvm,
916 			     struct vcpu_event_record *vcpu_record,
917 			     struct event_key *key,
918 			     struct perf_sample *sample)
919 {
920 	struct kvm_event *event;
921 	u64 time_begin, time_diff;
922 	int vcpu;
923 
924 	if (kvm->trace_vcpu == -1)
925 		vcpu = -1;
926 	else
927 		vcpu = vcpu_record->vcpu_id;
928 
929 	event = vcpu_record->last_event;
930 	time_begin = vcpu_record->start_time;
931 
932 	/* The begin event is not caught. */
933 	if (!time_begin)
934 		return true;
935 
936 	/*
937 	 * In some case, the 'begin event' only records the start timestamp,
938 	 * the actual event is recognized in the 'end event' (e.g. mmio-event).
939 	 */
940 
941 	/* Both begin and end events did not get the key. */
942 	if (!event && key->key == INVALID_KEY)
943 		return true;
944 
945 	if (!event)
946 		event = find_create_kvm_event(kvm, key, sample);
947 
948 	if (!event)
949 		return false;
950 
951 	vcpu_record->last_event = NULL;
952 	vcpu_record->start_time = 0;
953 
954 	/* seems to happen once in a while during live mode */
955 	if (sample->time < time_begin) {
956 		pr_debug("End time before begin time; skipping event.\n");
957 		return true;
958 	}
959 
960 	time_diff = sample->time - time_begin;
961 
962 	if (kvm->duration && time_diff > kvm->duration) {
963 		char decode[KVM_EVENT_NAME_LEN];
964 
965 		kvm->events_ops->decode_key(kvm, &event->key, decode);
966 		if (!skip_event(decode)) {
967 			pr_info("%" PRIu64 " VM %d, vcpu %d: %s event took %" PRIu64 "usec\n",
968 				 sample->time, sample->pid, vcpu_record->vcpu_id,
969 				 decode, time_diff / NSEC_PER_USEC);
970 		}
971 	}
972 
973 	return update_kvm_event(kvm, event, vcpu, time_diff);
974 }
975 
976 static
977 struct vcpu_event_record *per_vcpu_record(struct thread *thread,
978 					  struct evsel *evsel,
979 					  struct perf_sample *sample)
980 {
981 	/* Only kvm_entry records vcpu id. */
982 	if (!thread__priv(thread) && kvm_entry_event(evsel)) {
983 		struct vcpu_event_record *vcpu_record;
984 
985 		vcpu_record = zalloc(sizeof(*vcpu_record));
986 		if (!vcpu_record) {
987 			pr_err("%s: Not enough memory\n", __func__);
988 			return NULL;
989 		}
990 
991 		vcpu_record->vcpu_id = evsel__intval(evsel, sample, vcpu_id_str);
992 		thread__set_priv(thread, vcpu_record);
993 	}
994 
995 	return thread__priv(thread);
996 }
997 
998 static bool handle_kvm_event(struct perf_kvm_stat *kvm,
999 			     struct thread *thread,
1000 			     struct evsel *evsel,
1001 			     struct perf_sample *sample)
1002 {
1003 	struct vcpu_event_record *vcpu_record;
1004 	struct event_key key = { .key = INVALID_KEY,
1005 				 .exit_reasons = kvm->exit_reasons };
1006 
1007 	vcpu_record = per_vcpu_record(thread, evsel, sample);
1008 	if (!vcpu_record)
1009 		return true;
1010 
1011 	/* only process events for vcpus user cares about */
1012 	if ((kvm->trace_vcpu != -1) &&
1013 	    (kvm->trace_vcpu != vcpu_record->vcpu_id))
1014 		return true;
1015 
1016 	if (kvm->events_ops->is_begin_event(evsel, sample, &key))
1017 		return handle_begin_event(kvm, vcpu_record, &key, sample);
1018 
1019 	if (is_child_event(kvm, evsel, sample, &key))
1020 		return handle_child_event(kvm, vcpu_record, &key, sample);
1021 
1022 	if (kvm->events_ops->is_end_event(evsel, sample, &key))
1023 		return handle_end_event(kvm, vcpu_record, &key, sample);
1024 
1025 	return true;
1026 }
1027 
1028 static bool is_valid_key(struct perf_kvm_stat *kvm)
1029 {
1030 	static const char *key_array[] = {
1031 		"ev_name", "sample", "time", "max_t", "min_t", "mean_t",
1032 	};
1033 	unsigned int i;
1034 
1035 	for (i = 0; i < ARRAY_SIZE(key_array); i++)
1036 		if (!strcmp(key_array[i], kvm->sort_key))
1037 			return true;
1038 
1039 	pr_err("Unsupported sort key: %s\n", kvm->sort_key);
1040 	return false;
1041 }
1042 
1043 static bool event_is_valid(struct kvm_event *event, int vcpu)
1044 {
1045 	return !!get_event_count(event, vcpu);
1046 }
1047 
1048 static int filter_cb(struct hist_entry *he, void *arg __maybe_unused)
1049 {
1050 	struct kvm_event *event;
1051 	struct perf_kvm_stat *perf_kvm;
1052 
1053 	event = container_of(he, struct kvm_event, he);
1054 	perf_kvm = event->perf_kvm;
1055 	if (!event_is_valid(event, perf_kvm->trace_vcpu))
1056 		he->filtered = 1;
1057 	else
1058 		he->filtered = 0;
1059 	return 0;
1060 }
1061 
1062 static void sort_result(struct perf_kvm_stat *kvm)
1063 {
1064 	struct ui_progress prog;
1065 	const char *output_columns = "ev_name,sample,percent_sample,"
1066 				     "time,percent_time,max_t,min_t,mean_t";
1067 
1068 	kvm_hists__reinit(output_columns, kvm->sort_key);
1069 	ui_progress__init(&prog, kvm_hists.hists.nr_entries, "Sorting...");
1070 	hists__collapse_resort(&kvm_hists.hists, NULL);
1071 	hists__output_resort_cb(&kvm_hists.hists, NULL, filter_cb);
1072 	ui_progress__finish();
1073 }
1074 
1075 static void print_vcpu_info(struct perf_kvm_stat *kvm)
1076 {
1077 	int vcpu = kvm->trace_vcpu;
1078 
1079 	pr_info("Analyze events for ");
1080 
1081 	if (kvm->opts.target.system_wide)
1082 		pr_info("all VMs, ");
1083 	else if (kvm->opts.target.pid)
1084 		pr_info("pid(s) %s, ", kvm->opts.target.pid);
1085 	else
1086 		pr_info("dazed and confused on what is monitored, ");
1087 
1088 	if (vcpu == -1)
1089 		pr_info("all VCPUs:\n\n");
1090 	else
1091 		pr_info("VCPU %d:\n\n", vcpu);
1092 }
1093 
1094 static void show_timeofday(void)
1095 {
1096 	char date[64];
1097 	struct timeval tv;
1098 	struct tm ltime;
1099 
1100 	gettimeofday(&tv, NULL);
1101 	if (localtime_r(&tv.tv_sec, &ltime)) {
1102 		strftime(date, sizeof(date), "%H:%M:%S", &ltime);
1103 		pr_info("%s.%06ld", date, tv.tv_usec);
1104 	} else
1105 		pr_info("00:00:00.000000");
1106 
1107 	return;
1108 }
1109 
1110 static void print_result(struct perf_kvm_stat *kvm)
1111 {
1112 	char decode[KVM_EVENT_NAME_LEN];
1113 	struct kvm_event *event;
1114 	int vcpu = kvm->trace_vcpu;
1115 	struct rb_node *nd;
1116 
1117 	if (kvm->live) {
1118 		puts(CONSOLE_CLEAR);
1119 		show_timeofday();
1120 	}
1121 
1122 	pr_info("\n\n");
1123 	print_vcpu_info(kvm);
1124 	pr_info("%*s ", KVM_EVENT_NAME_LEN, kvm->events_ops->name);
1125 	pr_info("%10s ", "Samples");
1126 	pr_info("%9s ", "Samples%");
1127 
1128 	pr_info("%9s ", "Time%");
1129 	pr_info("%11s ", "Min Time");
1130 	pr_info("%11s ", "Max Time");
1131 	pr_info("%16s ", "Avg time");
1132 	pr_info("\n\n");
1133 
1134 	for (nd = rb_first_cached(&kvm_hists.hists.entries); nd; nd = rb_next(nd)) {
1135 		struct hist_entry *he;
1136 		u64 ecount, etime, max, min;
1137 
1138 		he = rb_entry(nd, struct hist_entry, rb_node);
1139 		if (he->filtered)
1140 			continue;
1141 
1142 		event = container_of(he, struct kvm_event, he);
1143 		ecount = get_event_count(event, vcpu);
1144 		etime = get_event_time(event, vcpu);
1145 		max = get_event_max(event, vcpu);
1146 		min = get_event_min(event, vcpu);
1147 
1148 		kvm->events_ops->decode_key(kvm, &event->key, decode);
1149 		pr_info("%*s ", KVM_EVENT_NAME_LEN, decode);
1150 		pr_info("%10llu ", (unsigned long long)ecount);
1151 		pr_info("%8.2f%% ", (double)ecount / kvm->total_count * 100);
1152 		pr_info("%8.2f%% ", (double)etime / kvm->total_time * 100);
1153 		pr_info("%9.2fus ", (double)min / NSEC_PER_USEC);
1154 		pr_info("%9.2fus ", (double)max / NSEC_PER_USEC);
1155 		pr_info("%9.2fus ( +-%7.2f%% )", (double)etime / ecount / NSEC_PER_USEC,
1156 			kvm_event_rel_stddev(vcpu, event));
1157 		pr_info("\n");
1158 	}
1159 
1160 	pr_info("\nTotal Samples:%" PRIu64 ", Total events handled time:%.2fus.\n\n",
1161 		kvm->total_count, kvm->total_time / (double)NSEC_PER_USEC);
1162 
1163 	if (kvm->lost_events)
1164 		pr_info("\nLost events: %" PRIu64 "\n\n", kvm->lost_events);
1165 }
1166 
1167 #if defined(HAVE_TIMERFD_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
1168 static int process_lost_event(struct perf_tool *tool,
1169 			      union perf_event *event __maybe_unused,
1170 			      struct perf_sample *sample __maybe_unused,
1171 			      struct machine *machine __maybe_unused)
1172 {
1173 	struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat, tool);
1174 
1175 	kvm->lost_events++;
1176 	return 0;
1177 }
1178 #endif
1179 
1180 static bool skip_sample(struct perf_kvm_stat *kvm,
1181 			struct perf_sample *sample)
1182 {
1183 	if (kvm->pid_list && intlist__find(kvm->pid_list, sample->pid) == NULL)
1184 		return true;
1185 
1186 	return false;
1187 }
1188 
1189 static int process_sample_event(struct perf_tool *tool,
1190 				union perf_event *event,
1191 				struct perf_sample *sample,
1192 				struct evsel *evsel,
1193 				struct machine *machine)
1194 {
1195 	int err = 0;
1196 	struct thread *thread;
1197 	struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat,
1198 						 tool);
1199 
1200 	if (skip_sample(kvm, sample))
1201 		return 0;
1202 
1203 	if (machine__resolve(machine, &kvm->al, sample) < 0) {
1204 		pr_warning("Fail to resolve address location, skip sample.\n");
1205 		return 0;
1206 	}
1207 
1208 	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
1209 	if (thread == NULL) {
1210 		pr_debug("problem processing %d event, skipping it.\n",
1211 			event->header.type);
1212 		return -1;
1213 	}
1214 
1215 	if (!handle_kvm_event(kvm, thread, evsel, sample))
1216 		err = -1;
1217 
1218 	thread__put(thread);
1219 	return err;
1220 }
1221 
1222 static int cpu_isa_config(struct perf_kvm_stat *kvm)
1223 {
1224 	char buf[128], *cpuid;
1225 	int err;
1226 
1227 	if (kvm->live) {
1228 		err = get_cpuid(buf, sizeof(buf));
1229 		if (err != 0) {
1230 			pr_err("Failed to look up CPU type: %s\n",
1231 			       str_error_r(err, buf, sizeof(buf)));
1232 			return -err;
1233 		}
1234 		cpuid = buf;
1235 	} else
1236 		cpuid = kvm->session->header.env.cpuid;
1237 
1238 	if (!cpuid) {
1239 		pr_err("Failed to look up CPU type\n");
1240 		return -EINVAL;
1241 	}
1242 
1243 	err = cpu_isa_init(kvm, cpuid);
1244 	if (err == -ENOTSUP)
1245 		pr_err("CPU %s is not supported.\n", cpuid);
1246 
1247 	return err;
1248 }
1249 
1250 static bool verify_vcpu(int vcpu)
1251 {
1252 	if (vcpu != -1 && vcpu < 0) {
1253 		pr_err("Invalid vcpu:%d.\n", vcpu);
1254 		return false;
1255 	}
1256 
1257 	return true;
1258 }
1259 
1260 #if defined(HAVE_TIMERFD_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
1261 /* keeping the max events to a modest level to keep
1262  * the processing of samples per mmap smooth.
1263  */
1264 #define PERF_KVM__MAX_EVENTS_PER_MMAP  25
1265 
1266 static s64 perf_kvm__mmap_read_idx(struct perf_kvm_stat *kvm, int idx,
1267 				   u64 *mmap_time)
1268 {
1269 	struct evlist *evlist = kvm->evlist;
1270 	union perf_event *event;
1271 	struct mmap *md;
1272 	u64 timestamp;
1273 	s64 n = 0;
1274 	int err;
1275 
1276 	*mmap_time = ULLONG_MAX;
1277 	md = &evlist->mmap[idx];
1278 	err = perf_mmap__read_init(&md->core);
1279 	if (err < 0)
1280 		return (err == -EAGAIN) ? 0 : -1;
1281 
1282 	while ((event = perf_mmap__read_event(&md->core)) != NULL) {
1283 		err = evlist__parse_sample_timestamp(evlist, event, &timestamp);
1284 		if (err) {
1285 			perf_mmap__consume(&md->core);
1286 			pr_err("Failed to parse sample\n");
1287 			return -1;
1288 		}
1289 
1290 		err = perf_session__queue_event(kvm->session, event, timestamp, 0, NULL);
1291 		/*
1292 		 * FIXME: Here we can't consume the event, as perf_session__queue_event will
1293 		 *        point to it, and it'll get possibly overwritten by the kernel.
1294 		 */
1295 		perf_mmap__consume(&md->core);
1296 
1297 		if (err) {
1298 			pr_err("Failed to enqueue sample: %d\n", err);
1299 			return -1;
1300 		}
1301 
1302 		/* save time stamp of our first sample for this mmap */
1303 		if (n == 0)
1304 			*mmap_time = timestamp;
1305 
1306 		/* limit events per mmap handled all at once */
1307 		n++;
1308 		if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
1309 			break;
1310 	}
1311 
1312 	perf_mmap__read_done(&md->core);
1313 	return n;
1314 }
1315 
1316 static int perf_kvm__mmap_read(struct perf_kvm_stat *kvm)
1317 {
1318 	int i, err, throttled = 0;
1319 	s64 n, ntotal = 0;
1320 	u64 flush_time = ULLONG_MAX, mmap_time;
1321 
1322 	for (i = 0; i < kvm->evlist->core.nr_mmaps; i++) {
1323 		n = perf_kvm__mmap_read_idx(kvm, i, &mmap_time);
1324 		if (n < 0)
1325 			return -1;
1326 
1327 		/* flush time is going to be the minimum of all the individual
1328 		 * mmap times. Essentially, we flush all the samples queued up
1329 		 * from the last pass under our minimal start time -- that leaves
1330 		 * a very small race for samples to come in with a lower timestamp.
1331 		 * The ioctl to return the perf_clock timestamp should close the
1332 		 * race entirely.
1333 		 */
1334 		if (mmap_time < flush_time)
1335 			flush_time = mmap_time;
1336 
1337 		ntotal += n;
1338 		if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
1339 			throttled = 1;
1340 	}
1341 
1342 	/* flush queue after each round in which we processed events */
1343 	if (ntotal) {
1344 		struct ordered_events *oe = &kvm->session->ordered_events;
1345 
1346 		oe->next_flush = flush_time;
1347 		err = ordered_events__flush(oe, OE_FLUSH__ROUND);
1348 		if (err) {
1349 			if (kvm->lost_events)
1350 				pr_info("\nLost events: %" PRIu64 "\n\n",
1351 					kvm->lost_events);
1352 			return err;
1353 		}
1354 	}
1355 
1356 	return throttled;
1357 }
1358 
1359 static volatile int done;
1360 
1361 static void sig_handler(int sig __maybe_unused)
1362 {
1363 	done = 1;
1364 }
1365 
1366 static int perf_kvm__timerfd_create(struct perf_kvm_stat *kvm)
1367 {
1368 	struct itimerspec new_value;
1369 	int rc = -1;
1370 
1371 	kvm->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
1372 	if (kvm->timerfd < 0) {
1373 		pr_err("timerfd_create failed\n");
1374 		goto out;
1375 	}
1376 
1377 	new_value.it_value.tv_sec = kvm->display_time;
1378 	new_value.it_value.tv_nsec = 0;
1379 	new_value.it_interval.tv_sec = kvm->display_time;
1380 	new_value.it_interval.tv_nsec = 0;
1381 
1382 	if (timerfd_settime(kvm->timerfd, 0, &new_value, NULL) != 0) {
1383 		pr_err("timerfd_settime failed: %d\n", errno);
1384 		close(kvm->timerfd);
1385 		goto out;
1386 	}
1387 
1388 	rc = 0;
1389 out:
1390 	return rc;
1391 }
1392 
1393 static int perf_kvm__handle_timerfd(struct perf_kvm_stat *kvm)
1394 {
1395 	uint64_t c;
1396 	int rc;
1397 
1398 	rc = read(kvm->timerfd, &c, sizeof(uint64_t));
1399 	if (rc < 0) {
1400 		if (errno == EAGAIN)
1401 			return 0;
1402 
1403 		pr_err("Failed to read timer fd: %d\n", errno);
1404 		return -1;
1405 	}
1406 
1407 	if (rc != sizeof(uint64_t)) {
1408 		pr_err("Error reading timer fd - invalid size returned\n");
1409 		return -1;
1410 	}
1411 
1412 	if (c != 1)
1413 		pr_debug("Missed timer beats: %" PRIu64 "\n", c-1);
1414 
1415 	/* update display */
1416 	sort_result(kvm);
1417 	print_result(kvm);
1418 
1419 	/* Reset sort list to "ev_name" */
1420 	kvm_hists__reinit(NULL, "ev_name");
1421 
1422 	/* reset counts */
1423 	clear_events_cache_stats();
1424 	kvm->total_count = 0;
1425 	kvm->total_time = 0;
1426 	kvm->lost_events = 0;
1427 
1428 	return 0;
1429 }
1430 
1431 static int fd_set_nonblock(int fd)
1432 {
1433 	long arg = 0;
1434 
1435 	arg = fcntl(fd, F_GETFL);
1436 	if (arg < 0) {
1437 		pr_err("Failed to get current flags for fd %d\n", fd);
1438 		return -1;
1439 	}
1440 
1441 	if (fcntl(fd, F_SETFL, arg | O_NONBLOCK) < 0) {
1442 		pr_err("Failed to set non-block option on fd %d\n", fd);
1443 		return -1;
1444 	}
1445 
1446 	return 0;
1447 }
1448 
1449 static int perf_kvm__handle_stdin(void)
1450 {
1451 	int c;
1452 
1453 	c = getc(stdin);
1454 	if (c == 'q')
1455 		return 1;
1456 
1457 	return 0;
1458 }
1459 
1460 static int kvm_events_live_report(struct perf_kvm_stat *kvm)
1461 {
1462 	int nr_stdin, ret, err = -EINVAL;
1463 	struct termios save;
1464 
1465 	/* live flag must be set first */
1466 	kvm->live = true;
1467 
1468 	ret = cpu_isa_config(kvm);
1469 	if (ret < 0)
1470 		return ret;
1471 
1472 	if (!verify_vcpu(kvm->trace_vcpu) ||
1473 	    !is_valid_key(kvm) ||
1474 	    !register_kvm_events_ops(kvm)) {
1475 		goto out;
1476 	}
1477 
1478 	set_term_quiet_input(&save);
1479 
1480 	kvm_hists__init();
1481 
1482 	signal(SIGINT, sig_handler);
1483 	signal(SIGTERM, sig_handler);
1484 
1485 	/* add timer fd */
1486 	if (perf_kvm__timerfd_create(kvm) < 0) {
1487 		err = -1;
1488 		goto out;
1489 	}
1490 
1491 	if (evlist__add_pollfd(kvm->evlist, kvm->timerfd) < 0)
1492 		goto out;
1493 
1494 	nr_stdin = evlist__add_pollfd(kvm->evlist, fileno(stdin));
1495 	if (nr_stdin < 0)
1496 		goto out;
1497 
1498 	if (fd_set_nonblock(fileno(stdin)) != 0)
1499 		goto out;
1500 
1501 	/* everything is good - enable the events and process */
1502 	evlist__enable(kvm->evlist);
1503 
1504 	while (!done) {
1505 		struct fdarray *fda = &kvm->evlist->core.pollfd;
1506 		int rc;
1507 
1508 		rc = perf_kvm__mmap_read(kvm);
1509 		if (rc < 0)
1510 			break;
1511 
1512 		err = perf_kvm__handle_timerfd(kvm);
1513 		if (err)
1514 			goto out;
1515 
1516 		if (fda->entries[nr_stdin].revents & POLLIN)
1517 			done = perf_kvm__handle_stdin();
1518 
1519 		if (!rc && !done)
1520 			err = evlist__poll(kvm->evlist, 100);
1521 	}
1522 
1523 	evlist__disable(kvm->evlist);
1524 
1525 	if (err == 0) {
1526 		sort_result(kvm);
1527 		print_result(kvm);
1528 	}
1529 
1530 out:
1531 	hists__delete_entries(&kvm_hists.hists);
1532 
1533 	if (kvm->timerfd >= 0)
1534 		close(kvm->timerfd);
1535 
1536 	tcsetattr(0, TCSAFLUSH, &save);
1537 	return err;
1538 }
1539 
1540 static int kvm_live_open_events(struct perf_kvm_stat *kvm)
1541 {
1542 	int err, rc = -1;
1543 	struct evsel *pos;
1544 	struct evlist *evlist = kvm->evlist;
1545 	char sbuf[STRERR_BUFSIZE];
1546 
1547 	evlist__config(evlist, &kvm->opts, NULL);
1548 
1549 	/*
1550 	 * Note: exclude_{guest,host} do not apply here.
1551 	 *       This command processes KVM tracepoints from host only
1552 	 */
1553 	evlist__for_each_entry(evlist, pos) {
1554 		struct perf_event_attr *attr = &pos->core.attr;
1555 
1556 		/* make sure these *are* set */
1557 		evsel__set_sample_bit(pos, TID);
1558 		evsel__set_sample_bit(pos, TIME);
1559 		evsel__set_sample_bit(pos, CPU);
1560 		evsel__set_sample_bit(pos, RAW);
1561 		/* make sure these are *not*; want as small a sample as possible */
1562 		evsel__reset_sample_bit(pos, PERIOD);
1563 		evsel__reset_sample_bit(pos, IP);
1564 		evsel__reset_sample_bit(pos, CALLCHAIN);
1565 		evsel__reset_sample_bit(pos, ADDR);
1566 		evsel__reset_sample_bit(pos, READ);
1567 		attr->mmap = 0;
1568 		attr->comm = 0;
1569 		attr->task = 0;
1570 
1571 		attr->sample_period = 1;
1572 
1573 		attr->watermark = 0;
1574 		attr->wakeup_events = 1000;
1575 
1576 		/* will enable all once we are ready */
1577 		attr->disabled = 1;
1578 	}
1579 
1580 	err = evlist__open(evlist);
1581 	if (err < 0) {
1582 		printf("Couldn't create the events: %s\n",
1583 		       str_error_r(errno, sbuf, sizeof(sbuf)));
1584 		goto out;
1585 	}
1586 
1587 	if (evlist__mmap(evlist, kvm->opts.mmap_pages) < 0) {
1588 		ui__error("Failed to mmap the events: %s\n",
1589 			  str_error_r(errno, sbuf, sizeof(sbuf)));
1590 		evlist__close(evlist);
1591 		goto out;
1592 	}
1593 
1594 	rc = 0;
1595 
1596 out:
1597 	return rc;
1598 }
1599 #endif
1600 
1601 static int read_events(struct perf_kvm_stat *kvm)
1602 {
1603 	int ret;
1604 
1605 	struct perf_tool eops = {
1606 		.sample			= process_sample_event,
1607 		.comm			= perf_event__process_comm,
1608 		.namespaces		= perf_event__process_namespaces,
1609 		.ordered_events		= true,
1610 	};
1611 	struct perf_data file = {
1612 		.path  = kvm->file_name,
1613 		.mode  = PERF_DATA_MODE_READ,
1614 		.force = kvm->force,
1615 	};
1616 
1617 	kvm->tool = eops;
1618 	kvm->session = perf_session__new(&file, &kvm->tool);
1619 	if (IS_ERR(kvm->session)) {
1620 		pr_err("Initializing perf session failed\n");
1621 		return PTR_ERR(kvm->session);
1622 	}
1623 
1624 	symbol__init(&kvm->session->header.env);
1625 
1626 	if (!perf_session__has_traces(kvm->session, "kvm record")) {
1627 		ret = -EINVAL;
1628 		goto out_delete;
1629 	}
1630 
1631 	/*
1632 	 * Do not use 'isa' recorded in kvm_exit tracepoint since it is not
1633 	 * traced in the old kernel.
1634 	 */
1635 	ret = cpu_isa_config(kvm);
1636 	if (ret < 0)
1637 		goto out_delete;
1638 
1639 	ret = perf_session__process_events(kvm->session);
1640 
1641 out_delete:
1642 	perf_session__delete(kvm->session);
1643 	return ret;
1644 }
1645 
1646 static int parse_target_str(struct perf_kvm_stat *kvm)
1647 {
1648 	if (kvm->opts.target.pid) {
1649 		kvm->pid_list = intlist__new(kvm->opts.target.pid);
1650 		if (kvm->pid_list == NULL) {
1651 			pr_err("Error parsing process id string\n");
1652 			return -EINVAL;
1653 		}
1654 	}
1655 
1656 	return 0;
1657 }
1658 
1659 static int kvm_events_report_vcpu(struct perf_kvm_stat *kvm)
1660 {
1661 	int ret = -EINVAL;
1662 	int vcpu = kvm->trace_vcpu;
1663 
1664 	if (parse_target_str(kvm) != 0)
1665 		goto exit;
1666 
1667 	if (!verify_vcpu(vcpu))
1668 		goto exit;
1669 
1670 	if (!is_valid_key(kvm))
1671 		goto exit;
1672 
1673 	if (!register_kvm_events_ops(kvm))
1674 		goto exit;
1675 
1676 	if (kvm->use_stdio) {
1677 		use_browser = 0;
1678 		setup_pager();
1679 	} else {
1680 		use_browser = 1;
1681 	}
1682 
1683 	setup_browser(false);
1684 
1685 	kvm_hists__init();
1686 
1687 	ret = read_events(kvm);
1688 	if (ret)
1689 		goto exit;
1690 
1691 	sort_result(kvm);
1692 	kvm_display(kvm);
1693 
1694 exit:
1695 	hists__delete_entries(&kvm_hists.hists);
1696 	return ret;
1697 }
1698 
1699 #define STRDUP_FAIL_EXIT(s)		\
1700 	({	char *_p;		\
1701 	_p = strdup(s);		\
1702 		if (!_p)		\
1703 			return -ENOMEM;	\
1704 		_p;			\
1705 	})
1706 
1707 int __weak setup_kvm_events_tp(struct perf_kvm_stat *kvm __maybe_unused)
1708 {
1709 	return 0;
1710 }
1711 
1712 static int
1713 kvm_events_record(struct perf_kvm_stat *kvm, int argc, const char **argv)
1714 {
1715 	unsigned int rec_argc, i, j, events_tp_size;
1716 	const char **rec_argv;
1717 	const char * const record_args[] = {
1718 		"record",
1719 		"-R",
1720 		"-m", "1024",
1721 		"-c", "1",
1722 	};
1723 	const char * const kvm_stat_record_usage[] = {
1724 		"perf kvm stat record [<options>]",
1725 		NULL
1726 	};
1727 	const char * const *events_tp;
1728 	int ret;
1729 
1730 	events_tp_size = 0;
1731 	ret = setup_kvm_events_tp(kvm);
1732 	if (ret < 0) {
1733 		pr_err("Unable to setup the kvm tracepoints\n");
1734 		return ret;
1735 	}
1736 
1737 	for (events_tp = kvm_events_tp; *events_tp; events_tp++)
1738 		events_tp_size++;
1739 
1740 	rec_argc = ARRAY_SIZE(record_args) + argc + 2 +
1741 		   2 * events_tp_size;
1742 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
1743 
1744 	if (rec_argv == NULL)
1745 		return -ENOMEM;
1746 
1747 	for (i = 0; i < ARRAY_SIZE(record_args); i++)
1748 		rec_argv[i] = STRDUP_FAIL_EXIT(record_args[i]);
1749 
1750 	for (j = 0; j < events_tp_size; j++) {
1751 		rec_argv[i++] = "-e";
1752 		rec_argv[i++] = STRDUP_FAIL_EXIT(kvm_events_tp[j]);
1753 	}
1754 
1755 	rec_argv[i++] = STRDUP_FAIL_EXIT("-o");
1756 	rec_argv[i++] = STRDUP_FAIL_EXIT(kvm->file_name);
1757 
1758 	for (j = 1; j < (unsigned int)argc; j++, i++)
1759 		rec_argv[i] = argv[j];
1760 
1761 	set_option_flag(record_options, 'e', "event", PARSE_OPT_HIDDEN);
1762 	set_option_flag(record_options, 0, "filter", PARSE_OPT_HIDDEN);
1763 	set_option_flag(record_options, 'R', "raw-samples", PARSE_OPT_HIDDEN);
1764 
1765 	set_option_flag(record_options, 'F', "freq", PARSE_OPT_DISABLED);
1766 	set_option_flag(record_options, 0, "group", PARSE_OPT_DISABLED);
1767 	set_option_flag(record_options, 'g', NULL, PARSE_OPT_DISABLED);
1768 	set_option_flag(record_options, 0, "call-graph", PARSE_OPT_DISABLED);
1769 	set_option_flag(record_options, 'd', "data", PARSE_OPT_DISABLED);
1770 	set_option_flag(record_options, 'T', "timestamp", PARSE_OPT_DISABLED);
1771 	set_option_flag(record_options, 'P', "period", PARSE_OPT_DISABLED);
1772 	set_option_flag(record_options, 'n', "no-samples", PARSE_OPT_DISABLED);
1773 	set_option_flag(record_options, 'N', "no-buildid-cache", PARSE_OPT_DISABLED);
1774 	set_option_flag(record_options, 'B', "no-buildid", PARSE_OPT_DISABLED);
1775 	set_option_flag(record_options, 'G', "cgroup", PARSE_OPT_DISABLED);
1776 	set_option_flag(record_options, 'b', "branch-any", PARSE_OPT_DISABLED);
1777 	set_option_flag(record_options, 'j', "branch-filter", PARSE_OPT_DISABLED);
1778 	set_option_flag(record_options, 'W', "weight", PARSE_OPT_DISABLED);
1779 	set_option_flag(record_options, 0, "transaction", PARSE_OPT_DISABLED);
1780 
1781 	record_usage = kvm_stat_record_usage;
1782 	return cmd_record(i, rec_argv);
1783 }
1784 
1785 static int
1786 kvm_events_report(struct perf_kvm_stat *kvm, int argc, const char **argv)
1787 {
1788 	const struct option kvm_events_report_options[] = {
1789 		OPT_STRING(0, "event", &kvm->report_event, "report event",
1790 			   "event for reporting: vmexit, "
1791 			   "mmio (x86 only), ioport (x86 only)"),
1792 		OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1793 			    "vcpu id to report"),
1794 		OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1795 			    "key for sorting: sample(sort by samples number)"
1796 			    " time (sort by avg time)"),
1797 		OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1798 			   "analyze events only for given process id(s)"),
1799 		OPT_BOOLEAN('f', "force", &kvm->force, "don't complain, do it"),
1800 		OPT_BOOLEAN(0, "stdio", &kvm->use_stdio, "use the stdio interface"),
1801 		OPT_END()
1802 	};
1803 
1804 	const char * const kvm_events_report_usage[] = {
1805 		"perf kvm stat report [<options>]",
1806 		NULL
1807 	};
1808 
1809 	if (argc) {
1810 		argc = parse_options(argc, argv,
1811 				     kvm_events_report_options,
1812 				     kvm_events_report_usage, 0);
1813 		if (argc)
1814 			usage_with_options(kvm_events_report_usage,
1815 					   kvm_events_report_options);
1816 	}
1817 
1818 #ifndef HAVE_SLANG_SUPPORT
1819 	kvm->use_stdio = true;
1820 #endif
1821 
1822 	if (!kvm->opts.target.pid)
1823 		kvm->opts.target.system_wide = true;
1824 
1825 	return kvm_events_report_vcpu(kvm);
1826 }
1827 
1828 #if defined(HAVE_TIMERFD_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
1829 static struct evlist *kvm_live_event_list(void)
1830 {
1831 	struct evlist *evlist;
1832 	char *tp, *name, *sys;
1833 	int err = -1;
1834 	const char * const *events_tp;
1835 
1836 	evlist = evlist__new();
1837 	if (evlist == NULL)
1838 		return NULL;
1839 
1840 	for (events_tp = kvm_events_tp; *events_tp; events_tp++) {
1841 
1842 		tp = strdup(*events_tp);
1843 		if (tp == NULL)
1844 			goto out;
1845 
1846 		/* split tracepoint into subsystem and name */
1847 		sys = tp;
1848 		name = strchr(tp, ':');
1849 		if (name == NULL) {
1850 			pr_err("Error parsing %s tracepoint: subsystem delimiter not found\n",
1851 			       *events_tp);
1852 			free(tp);
1853 			goto out;
1854 		}
1855 		*name = '\0';
1856 		name++;
1857 
1858 		if (evlist__add_newtp(evlist, sys, name, NULL)) {
1859 			pr_err("Failed to add %s tracepoint to the list\n", *events_tp);
1860 			free(tp);
1861 			goto out;
1862 		}
1863 
1864 		free(tp);
1865 	}
1866 
1867 	err = 0;
1868 
1869 out:
1870 	if (err) {
1871 		evlist__delete(evlist);
1872 		evlist = NULL;
1873 	}
1874 
1875 	return evlist;
1876 }
1877 
1878 static int kvm_events_live(struct perf_kvm_stat *kvm,
1879 			   int argc, const char **argv)
1880 {
1881 	char errbuf[BUFSIZ];
1882 	int err;
1883 
1884 	const struct option live_options[] = {
1885 		OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1886 			"record events on existing process id"),
1887 		OPT_CALLBACK('m', "mmap-pages", &kvm->opts.mmap_pages, "pages",
1888 			"number of mmap data pages", evlist__parse_mmap_pages),
1889 		OPT_INCR('v', "verbose", &verbose,
1890 			"be more verbose (show counter open errors, etc)"),
1891 		OPT_BOOLEAN('a', "all-cpus", &kvm->opts.target.system_wide,
1892 			"system-wide collection from all CPUs"),
1893 		OPT_UINTEGER('d', "display", &kvm->display_time,
1894 			"time in seconds between display updates"),
1895 		OPT_STRING(0, "event", &kvm->report_event, "report event",
1896 			"event for reporting: "
1897 			"vmexit, mmio (x86 only), ioport (x86 only)"),
1898 		OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1899 			"vcpu id to report"),
1900 		OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1901 			"key for sorting: sample(sort by samples number)"
1902 			" time (sort by avg time)"),
1903 		OPT_U64(0, "duration", &kvm->duration,
1904 			"show events other than"
1905 			" HLT (x86 only) or Wait state (s390 only)"
1906 			" that take longer than duration usecs"),
1907 		OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
1908 				"per thread proc mmap processing timeout in ms"),
1909 		OPT_END()
1910 	};
1911 	const char * const live_usage[] = {
1912 		"perf kvm stat live [<options>]",
1913 		NULL
1914 	};
1915 	struct perf_data data = {
1916 		.mode = PERF_DATA_MODE_WRITE,
1917 	};
1918 
1919 
1920 	/* event handling */
1921 	kvm->tool.sample = process_sample_event;
1922 	kvm->tool.comm   = perf_event__process_comm;
1923 	kvm->tool.exit   = perf_event__process_exit;
1924 	kvm->tool.fork   = perf_event__process_fork;
1925 	kvm->tool.lost   = process_lost_event;
1926 	kvm->tool.namespaces  = perf_event__process_namespaces;
1927 	kvm->tool.ordered_events = true;
1928 	perf_tool__fill_defaults(&kvm->tool);
1929 
1930 	/* set defaults */
1931 	kvm->display_time = 1;
1932 	kvm->opts.user_interval = 1;
1933 	kvm->opts.mmap_pages = 512;
1934 	kvm->opts.target.uses_mmap = false;
1935 	kvm->opts.target.uid_str = NULL;
1936 	kvm->opts.target.uid = UINT_MAX;
1937 
1938 	symbol__init(NULL);
1939 	disable_buildid_cache();
1940 
1941 	use_browser = 0;
1942 
1943 	if (argc) {
1944 		argc = parse_options(argc, argv, live_options,
1945 				     live_usage, 0);
1946 		if (argc)
1947 			usage_with_options(live_usage, live_options);
1948 	}
1949 
1950 	kvm->duration *= NSEC_PER_USEC;   /* convert usec to nsec */
1951 
1952 	/*
1953 	 * target related setups
1954 	 */
1955 	err = target__validate(&kvm->opts.target);
1956 	if (err) {
1957 		target__strerror(&kvm->opts.target, err, errbuf, BUFSIZ);
1958 		ui__warning("%s", errbuf);
1959 	}
1960 
1961 	if (target__none(&kvm->opts.target))
1962 		kvm->opts.target.system_wide = true;
1963 
1964 
1965 	/*
1966 	 * generate the event list
1967 	 */
1968 	err = setup_kvm_events_tp(kvm);
1969 	if (err < 0) {
1970 		pr_err("Unable to setup the kvm tracepoints\n");
1971 		return err;
1972 	}
1973 
1974 	kvm->evlist = kvm_live_event_list();
1975 	if (kvm->evlist == NULL) {
1976 		err = -1;
1977 		goto out;
1978 	}
1979 
1980 	if (evlist__create_maps(kvm->evlist, &kvm->opts.target) < 0)
1981 		usage_with_options(live_usage, live_options);
1982 
1983 	/*
1984 	 * perf session
1985 	 */
1986 	kvm->session = perf_session__new(&data, &kvm->tool);
1987 	if (IS_ERR(kvm->session)) {
1988 		err = PTR_ERR(kvm->session);
1989 		goto out;
1990 	}
1991 	kvm->session->evlist = kvm->evlist;
1992 	perf_session__set_id_hdr_size(kvm->session);
1993 	ordered_events__set_copy_on_queue(&kvm->session->ordered_events, true);
1994 	machine__synthesize_threads(&kvm->session->machines.host, &kvm->opts.target,
1995 				    kvm->evlist->core.threads, true, false, 1);
1996 	err = kvm_live_open_events(kvm);
1997 	if (err)
1998 		goto out;
1999 
2000 	err = kvm_events_live_report(kvm);
2001 
2002 out:
2003 	perf_session__delete(kvm->session);
2004 	kvm->session = NULL;
2005 	evlist__delete(kvm->evlist);
2006 
2007 	return err;
2008 }
2009 #endif
2010 
2011 static void print_kvm_stat_usage(void)
2012 {
2013 	printf("Usage: perf kvm stat <command>\n\n");
2014 
2015 	printf("# Available commands:\n");
2016 	printf("\trecord: record kvm events\n");
2017 	printf("\treport: report statistical data of kvm events\n");
2018 	printf("\tlive:   live reporting of statistical data of kvm events\n");
2019 
2020 	printf("\nOtherwise, it is the alias of 'perf stat':\n");
2021 }
2022 
2023 static int kvm_cmd_stat(const char *file_name, int argc, const char **argv)
2024 {
2025 	struct perf_kvm_stat kvm = {
2026 		.file_name = file_name,
2027 
2028 		.trace_vcpu	= -1,
2029 		.report_event	= "vmexit",
2030 		.sort_key	= "sample",
2031 
2032 	};
2033 
2034 	if (argc == 1) {
2035 		print_kvm_stat_usage();
2036 		goto perf_stat;
2037 	}
2038 
2039 	if (strlen(argv[1]) > 2 && strstarts("record", argv[1]))
2040 		return kvm_events_record(&kvm, argc - 1, argv + 1);
2041 
2042 	if (strlen(argv[1]) > 2 && strstarts("report", argv[1]))
2043 		return kvm_events_report(&kvm, argc - 1 , argv + 1);
2044 
2045 #if defined(HAVE_TIMERFD_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
2046 	if (!strncmp(argv[1], "live", 4))
2047 		return kvm_events_live(&kvm, argc - 1 , argv + 1);
2048 #endif
2049 
2050 perf_stat:
2051 	return cmd_stat(argc, argv);
2052 }
2053 #endif /* HAVE_KVM_STAT_SUPPORT */
2054 
2055 int __weak kvm_add_default_arch_event(int *argc __maybe_unused,
2056 					const char **argv __maybe_unused)
2057 {
2058 	return 0;
2059 }
2060 
2061 static int __cmd_record(const char *file_name, int argc, const char **argv)
2062 {
2063 	int rec_argc, i = 0, j, ret;
2064 	const char **rec_argv;
2065 
2066 	ret = kvm_add_default_arch_event(&argc, argv);
2067 	if (ret)
2068 		return -EINVAL;
2069 
2070 	rec_argc = argc + 2;
2071 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
2072 	rec_argv[i++] = strdup("record");
2073 	rec_argv[i++] = strdup("-o");
2074 	rec_argv[i++] = strdup(file_name);
2075 	for (j = 1; j < argc; j++, i++)
2076 		rec_argv[i] = argv[j];
2077 
2078 	BUG_ON(i != rec_argc);
2079 
2080 	return cmd_record(i, rec_argv);
2081 }
2082 
2083 static int __cmd_report(const char *file_name, int argc, const char **argv)
2084 {
2085 	int rec_argc, i = 0, j;
2086 	const char **rec_argv;
2087 
2088 	rec_argc = argc + 2;
2089 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
2090 	rec_argv[i++] = strdup("report");
2091 	rec_argv[i++] = strdup("-i");
2092 	rec_argv[i++] = strdup(file_name);
2093 	for (j = 1; j < argc; j++, i++)
2094 		rec_argv[i] = argv[j];
2095 
2096 	BUG_ON(i != rec_argc);
2097 
2098 	return cmd_report(i, rec_argv);
2099 }
2100 
2101 static int
2102 __cmd_buildid_list(const char *file_name, int argc, const char **argv)
2103 {
2104 	int rec_argc, i = 0, j;
2105 	const char **rec_argv;
2106 
2107 	rec_argc = argc + 2;
2108 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
2109 	rec_argv[i++] = strdup("buildid-list");
2110 	rec_argv[i++] = strdup("-i");
2111 	rec_argv[i++] = strdup(file_name);
2112 	for (j = 1; j < argc; j++, i++)
2113 		rec_argv[i] = argv[j];
2114 
2115 	BUG_ON(i != rec_argc);
2116 
2117 	return cmd_buildid_list(i, rec_argv);
2118 }
2119 
2120 int cmd_kvm(int argc, const char **argv)
2121 {
2122 	const char *file_name = NULL;
2123 	const struct option kvm_options[] = {
2124 		OPT_STRING('i', "input", &file_name, "file",
2125 			   "Input file name"),
2126 		OPT_STRING('o', "output", &file_name, "file",
2127 			   "Output file name"),
2128 		OPT_BOOLEAN(0, "guest", &perf_guest,
2129 			    "Collect guest os data"),
2130 		OPT_BOOLEAN(0, "host", &perf_host,
2131 			    "Collect host os data"),
2132 		OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
2133 			   "guest mount directory under which every guest os"
2134 			   " instance has a subdir"),
2135 		OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
2136 			   "file", "file saving guest os vmlinux"),
2137 		OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
2138 			   "file", "file saving guest os /proc/kallsyms"),
2139 		OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
2140 			   "file", "file saving guest os /proc/modules"),
2141 		OPT_BOOLEAN(0, "guest-code", &symbol_conf.guest_code,
2142 			    "Guest code can be found in hypervisor process"),
2143 		OPT_INCR('v', "verbose", &verbose,
2144 			    "be more verbose (show counter open errors, etc)"),
2145 		OPT_END()
2146 	};
2147 
2148 	const char *const kvm_subcommands[] = { "top", "record", "report", "diff",
2149 						"buildid-list", "stat", NULL };
2150 	const char *kvm_usage[] = { NULL, NULL };
2151 
2152 	perf_host  = 0;
2153 	perf_guest = 1;
2154 
2155 	argc = parse_options_subcommand(argc, argv, kvm_options, kvm_subcommands, kvm_usage,
2156 					PARSE_OPT_STOP_AT_NON_OPTION);
2157 	if (!argc)
2158 		usage_with_options(kvm_usage, kvm_options);
2159 
2160 	if (!perf_host)
2161 		perf_guest = 1;
2162 
2163 	if (!file_name) {
2164 		file_name = get_filename_for_perf_kvm();
2165 
2166 		if (!file_name) {
2167 			pr_err("Failed to allocate memory for filename\n");
2168 			return -ENOMEM;
2169 		}
2170 	}
2171 
2172 	if (strlen(argv[0]) > 2 && strstarts("record", argv[0]))
2173 		return __cmd_record(file_name, argc, argv);
2174 	else if (strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2175 		return __cmd_report(file_name, argc, argv);
2176 	else if (strlen(argv[0]) > 2 && strstarts("diff", argv[0]))
2177 		return cmd_diff(argc, argv);
2178 	else if (!strcmp(argv[0], "top"))
2179 		return cmd_top(argc, argv);
2180 	else if (strlen(argv[0]) > 2 && strstarts("buildid-list", argv[0]))
2181 		return __cmd_buildid_list(file_name, argc, argv);
2182 #if defined(HAVE_KVM_STAT_SUPPORT) && defined(HAVE_LIBTRACEEVENT)
2183 	else if (strlen(argv[0]) > 2 && strstarts("stat", argv[0]))
2184 		return kvm_cmd_stat(file_name, argc, argv);
2185 #endif
2186 	else
2187 		usage_with_options(kvm_usage, kvm_options);
2188 
2189 	return 0;
2190 }
2191