xref: /openbmc/linux/tools/perf/builtin-kvm.c (revision 6cc23ed2)
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/ui.h"
27 
28 #include <sys/prctl.h>
29 #ifdef HAVE_TIMERFD_SUPPORT
30 #include <sys/timerfd.h>
31 #endif
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 
37 #include <linux/err.h>
38 #include <linux/kernel.h>
39 #include <linux/string.h>
40 #include <linux/time64.h>
41 #include <linux/zalloc.h>
42 #include <errno.h>
43 #include <inttypes.h>
44 #include <poll.h>
45 #include <termios.h>
46 #include <semaphore.h>
47 #include <signal.h>
48 #include <math.h>
49 
50 static const char *get_filename_for_perf_kvm(void)
51 {
52 	const char *filename;
53 
54 	if (perf_host && !perf_guest)
55 		filename = strdup("perf.data.host");
56 	else if (!perf_host && perf_guest)
57 		filename = strdup("perf.data.guest");
58 	else
59 		filename = strdup("perf.data.kvm");
60 
61 	return filename;
62 }
63 
64 #ifdef HAVE_KVM_STAT_SUPPORT
65 
66 void exit_event_get_key(struct evsel *evsel,
67 			struct perf_sample *sample,
68 			struct event_key *key)
69 {
70 	key->info = 0;
71 	key->key = perf_evsel__intval(evsel, sample, kvm_exit_reason);
72 }
73 
74 bool kvm_exit_event(struct evsel *evsel)
75 {
76 	return !strcmp(evsel->name, kvm_exit_trace);
77 }
78 
79 bool exit_event_begin(struct evsel *evsel,
80 		      struct perf_sample *sample, struct event_key *key)
81 {
82 	if (kvm_exit_event(evsel)) {
83 		exit_event_get_key(evsel, sample, key);
84 		return true;
85 	}
86 
87 	return false;
88 }
89 
90 bool kvm_entry_event(struct evsel *evsel)
91 {
92 	return !strcmp(evsel->name, kvm_entry_trace);
93 }
94 
95 bool exit_event_end(struct evsel *evsel,
96 		    struct perf_sample *sample __maybe_unused,
97 		    struct event_key *key __maybe_unused)
98 {
99 	return kvm_entry_event(evsel);
100 }
101 
102 static const char *get_exit_reason(struct perf_kvm_stat *kvm,
103 				   struct exit_reasons_table *tbl,
104 				   u64 exit_code)
105 {
106 	while (tbl->reason != NULL) {
107 		if (tbl->exit_code == exit_code)
108 			return tbl->reason;
109 		tbl++;
110 	}
111 
112 	pr_err("unknown kvm exit code:%lld on %s\n",
113 		(unsigned long long)exit_code, kvm->exit_reasons_isa);
114 	return "UNKNOWN";
115 }
116 
117 void exit_event_decode_key(struct perf_kvm_stat *kvm,
118 			   struct event_key *key,
119 			   char *decode)
120 {
121 	const char *exit_reason = get_exit_reason(kvm, key->exit_reasons,
122 						  key->key);
123 
124 	scnprintf(decode, decode_str_len, "%s", exit_reason);
125 }
126 
127 static bool register_kvm_events_ops(struct perf_kvm_stat *kvm)
128 {
129 	struct kvm_reg_events_ops *events_ops = kvm_reg_events_ops;
130 
131 	for (events_ops = kvm_reg_events_ops; events_ops->name; events_ops++) {
132 		if (!strcmp(events_ops->name, kvm->report_event)) {
133 			kvm->events_ops = events_ops->ops;
134 			return true;
135 		}
136 	}
137 
138 	return false;
139 }
140 
141 struct vcpu_event_record {
142 	int vcpu_id;
143 	u64 start_time;
144 	struct kvm_event *last_event;
145 };
146 
147 
148 static void init_kvm_event_record(struct perf_kvm_stat *kvm)
149 {
150 	unsigned int i;
151 
152 	for (i = 0; i < EVENTS_CACHE_SIZE; i++)
153 		INIT_LIST_HEAD(&kvm->kvm_events_cache[i]);
154 }
155 
156 #ifdef HAVE_TIMERFD_SUPPORT
157 static void clear_events_cache_stats(struct list_head *kvm_events_cache)
158 {
159 	struct list_head *head;
160 	struct kvm_event *event;
161 	unsigned int i;
162 	int j;
163 
164 	for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
165 		head = &kvm_events_cache[i];
166 		list_for_each_entry(event, head, hash_entry) {
167 			/* reset stats for event */
168 			event->total.time = 0;
169 			init_stats(&event->total.stats);
170 
171 			for (j = 0; j < event->max_vcpu; ++j) {
172 				event->vcpu[j].time = 0;
173 				init_stats(&event->vcpu[j].stats);
174 			}
175 		}
176 	}
177 }
178 #endif
179 
180 static int kvm_events_hash_fn(u64 key)
181 {
182 	return key & (EVENTS_CACHE_SIZE - 1);
183 }
184 
185 static bool kvm_event_expand(struct kvm_event *event, int vcpu_id)
186 {
187 	int old_max_vcpu = event->max_vcpu;
188 	void *prev;
189 
190 	if (vcpu_id < event->max_vcpu)
191 		return true;
192 
193 	while (event->max_vcpu <= vcpu_id)
194 		event->max_vcpu += DEFAULT_VCPU_NUM;
195 
196 	prev = event->vcpu;
197 	event->vcpu = realloc(event->vcpu,
198 			      event->max_vcpu * sizeof(*event->vcpu));
199 	if (!event->vcpu) {
200 		free(prev);
201 		pr_err("Not enough memory\n");
202 		return false;
203 	}
204 
205 	memset(event->vcpu + old_max_vcpu, 0,
206 	       (event->max_vcpu - old_max_vcpu) * sizeof(*event->vcpu));
207 	return true;
208 }
209 
210 static struct kvm_event *kvm_alloc_init_event(struct event_key *key)
211 {
212 	struct kvm_event *event;
213 
214 	event = zalloc(sizeof(*event));
215 	if (!event) {
216 		pr_err("Not enough memory\n");
217 		return NULL;
218 	}
219 
220 	event->key = *key;
221 	init_stats(&event->total.stats);
222 	return event;
223 }
224 
225 static struct kvm_event *find_create_kvm_event(struct perf_kvm_stat *kvm,
226 					       struct event_key *key)
227 {
228 	struct kvm_event *event;
229 	struct list_head *head;
230 
231 	BUG_ON(key->key == INVALID_KEY);
232 
233 	head = &kvm->kvm_events_cache[kvm_events_hash_fn(key->key)];
234 	list_for_each_entry(event, head, hash_entry) {
235 		if (event->key.key == key->key && event->key.info == key->info)
236 			return event;
237 	}
238 
239 	event = kvm_alloc_init_event(key);
240 	if (!event)
241 		return NULL;
242 
243 	list_add(&event->hash_entry, head);
244 	return event;
245 }
246 
247 static bool handle_begin_event(struct perf_kvm_stat *kvm,
248 			       struct vcpu_event_record *vcpu_record,
249 			       struct event_key *key, u64 timestamp)
250 {
251 	struct kvm_event *event = NULL;
252 
253 	if (key->key != INVALID_KEY)
254 		event = find_create_kvm_event(kvm, key);
255 
256 	vcpu_record->last_event = event;
257 	vcpu_record->start_time = timestamp;
258 	return true;
259 }
260 
261 static void
262 kvm_update_event_stats(struct kvm_event_stats *kvm_stats, u64 time_diff)
263 {
264 	kvm_stats->time += time_diff;
265 	update_stats(&kvm_stats->stats, time_diff);
266 }
267 
268 static double kvm_event_rel_stddev(int vcpu_id, struct kvm_event *event)
269 {
270 	struct kvm_event_stats *kvm_stats = &event->total;
271 
272 	if (vcpu_id != -1)
273 		kvm_stats = &event->vcpu[vcpu_id];
274 
275 	return rel_stddev_stats(stddev_stats(&kvm_stats->stats),
276 				avg_stats(&kvm_stats->stats));
277 }
278 
279 static bool update_kvm_event(struct kvm_event *event, int vcpu_id,
280 			     u64 time_diff)
281 {
282 	if (vcpu_id == -1) {
283 		kvm_update_event_stats(&event->total, time_diff);
284 		return true;
285 	}
286 
287 	if (!kvm_event_expand(event, vcpu_id))
288 		return false;
289 
290 	kvm_update_event_stats(&event->vcpu[vcpu_id], time_diff);
291 	return true;
292 }
293 
294 static bool is_child_event(struct perf_kvm_stat *kvm,
295 			   struct evsel *evsel,
296 			   struct perf_sample *sample,
297 			   struct event_key *key)
298 {
299 	struct child_event_ops *child_ops;
300 
301 	child_ops = kvm->events_ops->child_ops;
302 
303 	if (!child_ops)
304 		return false;
305 
306 	for (; child_ops->name; child_ops++) {
307 		if (!strcmp(evsel->name, child_ops->name)) {
308 			child_ops->get_key(evsel, sample, key);
309 			return true;
310 		}
311 	}
312 
313 	return false;
314 }
315 
316 static bool handle_child_event(struct perf_kvm_stat *kvm,
317 			       struct vcpu_event_record *vcpu_record,
318 			       struct event_key *key,
319 			       struct perf_sample *sample __maybe_unused)
320 {
321 	struct kvm_event *event = NULL;
322 
323 	if (key->key != INVALID_KEY)
324 		event = find_create_kvm_event(kvm, key);
325 
326 	vcpu_record->last_event = event;
327 
328 	return true;
329 }
330 
331 static bool skip_event(const char *event)
332 {
333 	const char * const *skip_events;
334 
335 	for (skip_events = kvm_skip_events; *skip_events; skip_events++)
336 		if (!strcmp(event, *skip_events))
337 			return true;
338 
339 	return false;
340 }
341 
342 static bool handle_end_event(struct perf_kvm_stat *kvm,
343 			     struct vcpu_event_record *vcpu_record,
344 			     struct event_key *key,
345 			     struct perf_sample *sample)
346 {
347 	struct kvm_event *event;
348 	u64 time_begin, time_diff;
349 	int vcpu;
350 
351 	if (kvm->trace_vcpu == -1)
352 		vcpu = -1;
353 	else
354 		vcpu = vcpu_record->vcpu_id;
355 
356 	event = vcpu_record->last_event;
357 	time_begin = vcpu_record->start_time;
358 
359 	/* The begin event is not caught. */
360 	if (!time_begin)
361 		return true;
362 
363 	/*
364 	 * In some case, the 'begin event' only records the start timestamp,
365 	 * the actual event is recognized in the 'end event' (e.g. mmio-event).
366 	 */
367 
368 	/* Both begin and end events did not get the key. */
369 	if (!event && key->key == INVALID_KEY)
370 		return true;
371 
372 	if (!event)
373 		event = find_create_kvm_event(kvm, key);
374 
375 	if (!event)
376 		return false;
377 
378 	vcpu_record->last_event = NULL;
379 	vcpu_record->start_time = 0;
380 
381 	/* seems to happen once in a while during live mode */
382 	if (sample->time < time_begin) {
383 		pr_debug("End time before begin time; skipping event.\n");
384 		return true;
385 	}
386 
387 	time_diff = sample->time - time_begin;
388 
389 	if (kvm->duration && time_diff > kvm->duration) {
390 		char decode[decode_str_len];
391 
392 		kvm->events_ops->decode_key(kvm, &event->key, decode);
393 		if (!skip_event(decode)) {
394 			pr_info("%" PRIu64 " VM %d, vcpu %d: %s event took %" PRIu64 "usec\n",
395 				 sample->time, sample->pid, vcpu_record->vcpu_id,
396 				 decode, time_diff / NSEC_PER_USEC);
397 		}
398 	}
399 
400 	return update_kvm_event(event, vcpu, time_diff);
401 }
402 
403 static
404 struct vcpu_event_record *per_vcpu_record(struct thread *thread,
405 					  struct evsel *evsel,
406 					  struct perf_sample *sample)
407 {
408 	/* Only kvm_entry records vcpu id. */
409 	if (!thread__priv(thread) && kvm_entry_event(evsel)) {
410 		struct vcpu_event_record *vcpu_record;
411 
412 		vcpu_record = zalloc(sizeof(*vcpu_record));
413 		if (!vcpu_record) {
414 			pr_err("%s: Not enough memory\n", __func__);
415 			return NULL;
416 		}
417 
418 		vcpu_record->vcpu_id = perf_evsel__intval(evsel, sample,
419 							  vcpu_id_str);
420 		thread__set_priv(thread, vcpu_record);
421 	}
422 
423 	return thread__priv(thread);
424 }
425 
426 static bool handle_kvm_event(struct perf_kvm_stat *kvm,
427 			     struct thread *thread,
428 			     struct evsel *evsel,
429 			     struct perf_sample *sample)
430 {
431 	struct vcpu_event_record *vcpu_record;
432 	struct event_key key = { .key = INVALID_KEY,
433 				 .exit_reasons = kvm->exit_reasons };
434 
435 	vcpu_record = per_vcpu_record(thread, evsel, sample);
436 	if (!vcpu_record)
437 		return true;
438 
439 	/* only process events for vcpus user cares about */
440 	if ((kvm->trace_vcpu != -1) &&
441 	    (kvm->trace_vcpu != vcpu_record->vcpu_id))
442 		return true;
443 
444 	if (kvm->events_ops->is_begin_event(evsel, sample, &key))
445 		return handle_begin_event(kvm, vcpu_record, &key, sample->time);
446 
447 	if (is_child_event(kvm, evsel, sample, &key))
448 		return handle_child_event(kvm, vcpu_record, &key, sample);
449 
450 	if (kvm->events_ops->is_end_event(evsel, sample, &key))
451 		return handle_end_event(kvm, vcpu_record, &key, sample);
452 
453 	return true;
454 }
455 
456 #define GET_EVENT_KEY(func, field)					\
457 static u64 get_event_ ##func(struct kvm_event *event, int vcpu)		\
458 {									\
459 	if (vcpu == -1)							\
460 		return event->total.field;				\
461 									\
462 	if (vcpu >= event->max_vcpu)					\
463 		return 0;						\
464 									\
465 	return event->vcpu[vcpu].field;					\
466 }
467 
468 #define COMPARE_EVENT_KEY(func, field)					\
469 GET_EVENT_KEY(func, field)						\
470 static int compare_kvm_event_ ## func(struct kvm_event *one,		\
471 					struct kvm_event *two, int vcpu)\
472 {									\
473 	return get_event_ ##func(one, vcpu) >				\
474 				get_event_ ##func(two, vcpu);		\
475 }
476 
477 GET_EVENT_KEY(time, time);
478 COMPARE_EVENT_KEY(count, stats.n);
479 COMPARE_EVENT_KEY(mean, stats.mean);
480 GET_EVENT_KEY(max, stats.max);
481 GET_EVENT_KEY(min, stats.min);
482 
483 #define DEF_SORT_NAME_KEY(name, compare_key)				\
484 	{ #name, compare_kvm_event_ ## compare_key }
485 
486 static struct kvm_event_key keys[] = {
487 	DEF_SORT_NAME_KEY(sample, count),
488 	DEF_SORT_NAME_KEY(time, mean),
489 	{ NULL, NULL }
490 };
491 
492 static bool select_key(struct perf_kvm_stat *kvm)
493 {
494 	int i;
495 
496 	for (i = 0; keys[i].name; i++) {
497 		if (!strcmp(keys[i].name, kvm->sort_key)) {
498 			kvm->compare = keys[i].key;
499 			return true;
500 		}
501 	}
502 
503 	pr_err("Unknown compare key:%s\n", kvm->sort_key);
504 	return false;
505 }
506 
507 static void insert_to_result(struct rb_root *result, struct kvm_event *event,
508 			     key_cmp_fun bigger, int vcpu)
509 {
510 	struct rb_node **rb = &result->rb_node;
511 	struct rb_node *parent = NULL;
512 	struct kvm_event *p;
513 
514 	while (*rb) {
515 		p = container_of(*rb, struct kvm_event, rb);
516 		parent = *rb;
517 
518 		if (bigger(event, p, vcpu))
519 			rb = &(*rb)->rb_left;
520 		else
521 			rb = &(*rb)->rb_right;
522 	}
523 
524 	rb_link_node(&event->rb, parent, rb);
525 	rb_insert_color(&event->rb, result);
526 }
527 
528 static void
529 update_total_count(struct perf_kvm_stat *kvm, struct kvm_event *event)
530 {
531 	int vcpu = kvm->trace_vcpu;
532 
533 	kvm->total_count += get_event_count(event, vcpu);
534 	kvm->total_time += get_event_time(event, vcpu);
535 }
536 
537 static bool event_is_valid(struct kvm_event *event, int vcpu)
538 {
539 	return !!get_event_count(event, vcpu);
540 }
541 
542 static void sort_result(struct perf_kvm_stat *kvm)
543 {
544 	unsigned int i;
545 	int vcpu = kvm->trace_vcpu;
546 	struct kvm_event *event;
547 
548 	for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
549 		list_for_each_entry(event, &kvm->kvm_events_cache[i], hash_entry) {
550 			if (event_is_valid(event, vcpu)) {
551 				update_total_count(kvm, event);
552 				insert_to_result(&kvm->result, event,
553 						 kvm->compare, vcpu);
554 			}
555 		}
556 	}
557 }
558 
559 /* returns left most element of result, and erase it */
560 static struct kvm_event *pop_from_result(struct rb_root *result)
561 {
562 	struct rb_node *node = rb_first(result);
563 
564 	if (!node)
565 		return NULL;
566 
567 	rb_erase(node, result);
568 	return container_of(node, struct kvm_event, rb);
569 }
570 
571 static void print_vcpu_info(struct perf_kvm_stat *kvm)
572 {
573 	int vcpu = kvm->trace_vcpu;
574 
575 	pr_info("Analyze events for ");
576 
577 	if (kvm->opts.target.system_wide)
578 		pr_info("all VMs, ");
579 	else if (kvm->opts.target.pid)
580 		pr_info("pid(s) %s, ", kvm->opts.target.pid);
581 	else
582 		pr_info("dazed and confused on what is monitored, ");
583 
584 	if (vcpu == -1)
585 		pr_info("all VCPUs:\n\n");
586 	else
587 		pr_info("VCPU %d:\n\n", vcpu);
588 }
589 
590 static void show_timeofday(void)
591 {
592 	char date[64];
593 	struct timeval tv;
594 	struct tm ltime;
595 
596 	gettimeofday(&tv, NULL);
597 	if (localtime_r(&tv.tv_sec, &ltime)) {
598 		strftime(date, sizeof(date), "%H:%M:%S", &ltime);
599 		pr_info("%s.%06ld", date, tv.tv_usec);
600 	} else
601 		pr_info("00:00:00.000000");
602 
603 	return;
604 }
605 
606 static void print_result(struct perf_kvm_stat *kvm)
607 {
608 	char decode[decode_str_len];
609 	struct kvm_event *event;
610 	int vcpu = kvm->trace_vcpu;
611 
612 	if (kvm->live) {
613 		puts(CONSOLE_CLEAR);
614 		show_timeofday();
615 	}
616 
617 	pr_info("\n\n");
618 	print_vcpu_info(kvm);
619 	pr_info("%*s ", decode_str_len, kvm->events_ops->name);
620 	pr_info("%10s ", "Samples");
621 	pr_info("%9s ", "Samples%");
622 
623 	pr_info("%9s ", "Time%");
624 	pr_info("%11s ", "Min Time");
625 	pr_info("%11s ", "Max Time");
626 	pr_info("%16s ", "Avg time");
627 	pr_info("\n\n");
628 
629 	while ((event = pop_from_result(&kvm->result))) {
630 		u64 ecount, etime, max, min;
631 
632 		ecount = get_event_count(event, vcpu);
633 		etime = get_event_time(event, vcpu);
634 		max = get_event_max(event, vcpu);
635 		min = get_event_min(event, vcpu);
636 
637 		kvm->events_ops->decode_key(kvm, &event->key, decode);
638 		pr_info("%*s ", decode_str_len, decode);
639 		pr_info("%10llu ", (unsigned long long)ecount);
640 		pr_info("%8.2f%% ", (double)ecount / kvm->total_count * 100);
641 		pr_info("%8.2f%% ", (double)etime / kvm->total_time * 100);
642 		pr_info("%9.2fus ", (double)min / NSEC_PER_USEC);
643 		pr_info("%9.2fus ", (double)max / NSEC_PER_USEC);
644 		pr_info("%9.2fus ( +-%7.2f%% )", (double)etime / ecount / NSEC_PER_USEC,
645 			kvm_event_rel_stddev(vcpu, event));
646 		pr_info("\n");
647 	}
648 
649 	pr_info("\nTotal Samples:%" PRIu64 ", Total events handled time:%.2fus.\n\n",
650 		kvm->total_count, kvm->total_time / (double)NSEC_PER_USEC);
651 
652 	if (kvm->lost_events)
653 		pr_info("\nLost events: %" PRIu64 "\n\n", kvm->lost_events);
654 }
655 
656 #ifdef HAVE_TIMERFD_SUPPORT
657 static int process_lost_event(struct perf_tool *tool,
658 			      union perf_event *event __maybe_unused,
659 			      struct perf_sample *sample __maybe_unused,
660 			      struct machine *machine __maybe_unused)
661 {
662 	struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat, tool);
663 
664 	kvm->lost_events++;
665 	return 0;
666 }
667 #endif
668 
669 static bool skip_sample(struct perf_kvm_stat *kvm,
670 			struct perf_sample *sample)
671 {
672 	if (kvm->pid_list && intlist__find(kvm->pid_list, sample->pid) == NULL)
673 		return true;
674 
675 	return false;
676 }
677 
678 static int process_sample_event(struct perf_tool *tool,
679 				union perf_event *event,
680 				struct perf_sample *sample,
681 				struct evsel *evsel,
682 				struct machine *machine)
683 {
684 	int err = 0;
685 	struct thread *thread;
686 	struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat,
687 						 tool);
688 
689 	if (skip_sample(kvm, sample))
690 		return 0;
691 
692 	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
693 	if (thread == NULL) {
694 		pr_debug("problem processing %d event, skipping it.\n",
695 			event->header.type);
696 		return -1;
697 	}
698 
699 	if (!handle_kvm_event(kvm, thread, evsel, sample))
700 		err = -1;
701 
702 	thread__put(thread);
703 	return err;
704 }
705 
706 static int cpu_isa_config(struct perf_kvm_stat *kvm)
707 {
708 	char buf[64], *cpuid;
709 	int err;
710 
711 	if (kvm->live) {
712 		err = get_cpuid(buf, sizeof(buf));
713 		if (err != 0) {
714 			pr_err("Failed to look up CPU type\n");
715 			return err;
716 		}
717 		cpuid = buf;
718 	} else
719 		cpuid = kvm->session->header.env.cpuid;
720 
721 	if (!cpuid) {
722 		pr_err("Failed to look up CPU type\n");
723 		return -EINVAL;
724 	}
725 
726 	err = cpu_isa_init(kvm, cpuid);
727 	if (err == -ENOTSUP)
728 		pr_err("CPU %s is not supported.\n", cpuid);
729 
730 	return err;
731 }
732 
733 static bool verify_vcpu(int vcpu)
734 {
735 	if (vcpu != -1 && vcpu < 0) {
736 		pr_err("Invalid vcpu:%d.\n", vcpu);
737 		return false;
738 	}
739 
740 	return true;
741 }
742 
743 #ifdef HAVE_TIMERFD_SUPPORT
744 /* keeping the max events to a modest level to keep
745  * the processing of samples per mmap smooth.
746  */
747 #define PERF_KVM__MAX_EVENTS_PER_MMAP  25
748 
749 static s64 perf_kvm__mmap_read_idx(struct perf_kvm_stat *kvm, int idx,
750 				   u64 *mmap_time)
751 {
752 	struct evlist *evlist = kvm->evlist;
753 	union perf_event *event;
754 	struct mmap *md;
755 	u64 timestamp;
756 	s64 n = 0;
757 	int err;
758 
759 	*mmap_time = ULLONG_MAX;
760 	md = &evlist->mmap[idx];
761 	err = perf_mmap__read_init(md);
762 	if (err < 0)
763 		return (err == -EAGAIN) ? 0 : -1;
764 
765 	while ((event = perf_mmap__read_event(md)) != NULL) {
766 		err = perf_evlist__parse_sample_timestamp(evlist, event, &timestamp);
767 		if (err) {
768 			perf_mmap__consume(md);
769 			pr_err("Failed to parse sample\n");
770 			return -1;
771 		}
772 
773 		err = perf_session__queue_event(kvm->session, event, timestamp, 0);
774 		/*
775 		 * FIXME: Here we can't consume the event, as perf_session__queue_event will
776 		 *        point to it, and it'll get possibly overwritten by the kernel.
777 		 */
778 		perf_mmap__consume(md);
779 
780 		if (err) {
781 			pr_err("Failed to enqueue sample: %d\n", err);
782 			return -1;
783 		}
784 
785 		/* save time stamp of our first sample for this mmap */
786 		if (n == 0)
787 			*mmap_time = timestamp;
788 
789 		/* limit events per mmap handled all at once */
790 		n++;
791 		if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
792 			break;
793 	}
794 
795 	perf_mmap__read_done(md);
796 	return n;
797 }
798 
799 static int perf_kvm__mmap_read(struct perf_kvm_stat *kvm)
800 {
801 	int i, err, throttled = 0;
802 	s64 n, ntotal = 0;
803 	u64 flush_time = ULLONG_MAX, mmap_time;
804 
805 	for (i = 0; i < kvm->evlist->core.nr_mmaps; i++) {
806 		n = perf_kvm__mmap_read_idx(kvm, i, &mmap_time);
807 		if (n < 0)
808 			return -1;
809 
810 		/* flush time is going to be the minimum of all the individual
811 		 * mmap times. Essentially, we flush all the samples queued up
812 		 * from the last pass under our minimal start time -- that leaves
813 		 * a very small race for samples to come in with a lower timestamp.
814 		 * The ioctl to return the perf_clock timestamp should close the
815 		 * race entirely.
816 		 */
817 		if (mmap_time < flush_time)
818 			flush_time = mmap_time;
819 
820 		ntotal += n;
821 		if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
822 			throttled = 1;
823 	}
824 
825 	/* flush queue after each round in which we processed events */
826 	if (ntotal) {
827 		struct ordered_events *oe = &kvm->session->ordered_events;
828 
829 		oe->next_flush = flush_time;
830 		err = ordered_events__flush(oe, OE_FLUSH__ROUND);
831 		if (err) {
832 			if (kvm->lost_events)
833 				pr_info("\nLost events: %" PRIu64 "\n\n",
834 					kvm->lost_events);
835 			return err;
836 		}
837 	}
838 
839 	return throttled;
840 }
841 
842 static volatile int done;
843 
844 static void sig_handler(int sig __maybe_unused)
845 {
846 	done = 1;
847 }
848 
849 static int perf_kvm__timerfd_create(struct perf_kvm_stat *kvm)
850 {
851 	struct itimerspec new_value;
852 	int rc = -1;
853 
854 	kvm->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
855 	if (kvm->timerfd < 0) {
856 		pr_err("timerfd_create failed\n");
857 		goto out;
858 	}
859 
860 	new_value.it_value.tv_sec = kvm->display_time;
861 	new_value.it_value.tv_nsec = 0;
862 	new_value.it_interval.tv_sec = kvm->display_time;
863 	new_value.it_interval.tv_nsec = 0;
864 
865 	if (timerfd_settime(kvm->timerfd, 0, &new_value, NULL) != 0) {
866 		pr_err("timerfd_settime failed: %d\n", errno);
867 		close(kvm->timerfd);
868 		goto out;
869 	}
870 
871 	rc = 0;
872 out:
873 	return rc;
874 }
875 
876 static int perf_kvm__handle_timerfd(struct perf_kvm_stat *kvm)
877 {
878 	uint64_t c;
879 	int rc;
880 
881 	rc = read(kvm->timerfd, &c, sizeof(uint64_t));
882 	if (rc < 0) {
883 		if (errno == EAGAIN)
884 			return 0;
885 
886 		pr_err("Failed to read timer fd: %d\n", errno);
887 		return -1;
888 	}
889 
890 	if (rc != sizeof(uint64_t)) {
891 		pr_err("Error reading timer fd - invalid size returned\n");
892 		return -1;
893 	}
894 
895 	if (c != 1)
896 		pr_debug("Missed timer beats: %" PRIu64 "\n", c-1);
897 
898 	/* update display */
899 	sort_result(kvm);
900 	print_result(kvm);
901 
902 	/* reset counts */
903 	clear_events_cache_stats(kvm->kvm_events_cache);
904 	kvm->total_count = 0;
905 	kvm->total_time = 0;
906 	kvm->lost_events = 0;
907 
908 	return 0;
909 }
910 
911 static int fd_set_nonblock(int fd)
912 {
913 	long arg = 0;
914 
915 	arg = fcntl(fd, F_GETFL);
916 	if (arg < 0) {
917 		pr_err("Failed to get current flags for fd %d\n", fd);
918 		return -1;
919 	}
920 
921 	if (fcntl(fd, F_SETFL, arg | O_NONBLOCK) < 0) {
922 		pr_err("Failed to set non-block option on fd %d\n", fd);
923 		return -1;
924 	}
925 
926 	return 0;
927 }
928 
929 static int perf_kvm__handle_stdin(void)
930 {
931 	int c;
932 
933 	c = getc(stdin);
934 	if (c == 'q')
935 		return 1;
936 
937 	return 0;
938 }
939 
940 static int kvm_events_live_report(struct perf_kvm_stat *kvm)
941 {
942 	int nr_stdin, ret, err = -EINVAL;
943 	struct termios save;
944 
945 	/* live flag must be set first */
946 	kvm->live = true;
947 
948 	ret = cpu_isa_config(kvm);
949 	if (ret < 0)
950 		return ret;
951 
952 	if (!verify_vcpu(kvm->trace_vcpu) ||
953 	    !select_key(kvm) ||
954 	    !register_kvm_events_ops(kvm)) {
955 		goto out;
956 	}
957 
958 	set_term_quiet_input(&save);
959 	init_kvm_event_record(kvm);
960 
961 	signal(SIGINT, sig_handler);
962 	signal(SIGTERM, sig_handler);
963 
964 	/* add timer fd */
965 	if (perf_kvm__timerfd_create(kvm) < 0) {
966 		err = -1;
967 		goto out;
968 	}
969 
970 	if (evlist__add_pollfd(kvm->evlist, kvm->timerfd) < 0)
971 		goto out;
972 
973 	nr_stdin = evlist__add_pollfd(kvm->evlist, fileno(stdin));
974 	if (nr_stdin < 0)
975 		goto out;
976 
977 	if (fd_set_nonblock(fileno(stdin)) != 0)
978 		goto out;
979 
980 	/* everything is good - enable the events and process */
981 	evlist__enable(kvm->evlist);
982 
983 	while (!done) {
984 		struct fdarray *fda = &kvm->evlist->core.pollfd;
985 		int rc;
986 
987 		rc = perf_kvm__mmap_read(kvm);
988 		if (rc < 0)
989 			break;
990 
991 		err = perf_kvm__handle_timerfd(kvm);
992 		if (err)
993 			goto out;
994 
995 		if (fda->entries[nr_stdin].revents & POLLIN)
996 			done = perf_kvm__handle_stdin();
997 
998 		if (!rc && !done)
999 			err = fdarray__poll(fda, 100);
1000 	}
1001 
1002 	evlist__disable(kvm->evlist);
1003 
1004 	if (err == 0) {
1005 		sort_result(kvm);
1006 		print_result(kvm);
1007 	}
1008 
1009 out:
1010 	if (kvm->timerfd >= 0)
1011 		close(kvm->timerfd);
1012 
1013 	tcsetattr(0, TCSAFLUSH, &save);
1014 	return err;
1015 }
1016 
1017 static int kvm_live_open_events(struct perf_kvm_stat *kvm)
1018 {
1019 	int err, rc = -1;
1020 	struct evsel *pos;
1021 	struct evlist *evlist = kvm->evlist;
1022 	char sbuf[STRERR_BUFSIZE];
1023 
1024 	perf_evlist__config(evlist, &kvm->opts, NULL);
1025 
1026 	/*
1027 	 * Note: exclude_{guest,host} do not apply here.
1028 	 *       This command processes KVM tracepoints from host only
1029 	 */
1030 	evlist__for_each_entry(evlist, pos) {
1031 		struct perf_event_attr *attr = &pos->core.attr;
1032 
1033 		/* make sure these *are* set */
1034 		perf_evsel__set_sample_bit(pos, TID);
1035 		perf_evsel__set_sample_bit(pos, TIME);
1036 		perf_evsel__set_sample_bit(pos, CPU);
1037 		perf_evsel__set_sample_bit(pos, RAW);
1038 		/* make sure these are *not*; want as small a sample as possible */
1039 		perf_evsel__reset_sample_bit(pos, PERIOD);
1040 		perf_evsel__reset_sample_bit(pos, IP);
1041 		perf_evsel__reset_sample_bit(pos, CALLCHAIN);
1042 		perf_evsel__reset_sample_bit(pos, ADDR);
1043 		perf_evsel__reset_sample_bit(pos, READ);
1044 		attr->mmap = 0;
1045 		attr->comm = 0;
1046 		attr->task = 0;
1047 
1048 		attr->sample_period = 1;
1049 
1050 		attr->watermark = 0;
1051 		attr->wakeup_events = 1000;
1052 
1053 		/* will enable all once we are ready */
1054 		attr->disabled = 1;
1055 	}
1056 
1057 	err = evlist__open(evlist);
1058 	if (err < 0) {
1059 		printf("Couldn't create the events: %s\n",
1060 		       str_error_r(errno, sbuf, sizeof(sbuf)));
1061 		goto out;
1062 	}
1063 
1064 	if (evlist__mmap(evlist, kvm->opts.mmap_pages) < 0) {
1065 		ui__error("Failed to mmap the events: %s\n",
1066 			  str_error_r(errno, sbuf, sizeof(sbuf)));
1067 		evlist__close(evlist);
1068 		goto out;
1069 	}
1070 
1071 	rc = 0;
1072 
1073 out:
1074 	return rc;
1075 }
1076 #endif
1077 
1078 static int read_events(struct perf_kvm_stat *kvm)
1079 {
1080 	int ret;
1081 
1082 	struct perf_tool eops = {
1083 		.sample			= process_sample_event,
1084 		.comm			= perf_event__process_comm,
1085 		.namespaces		= perf_event__process_namespaces,
1086 		.ordered_events		= true,
1087 	};
1088 	struct perf_data file = {
1089 		.path  = kvm->file_name,
1090 		.mode  = PERF_DATA_MODE_READ,
1091 		.force = kvm->force,
1092 	};
1093 
1094 	kvm->tool = eops;
1095 	kvm->session = perf_session__new(&file, false, &kvm->tool);
1096 	if (IS_ERR(kvm->session)) {
1097 		pr_err("Initializing perf session failed\n");
1098 		return PTR_ERR(kvm->session);
1099 	}
1100 
1101 	symbol__init(&kvm->session->header.env);
1102 
1103 	if (!perf_session__has_traces(kvm->session, "kvm record")) {
1104 		ret = -EINVAL;
1105 		goto out_delete;
1106 	}
1107 
1108 	/*
1109 	 * Do not use 'isa' recorded in kvm_exit tracepoint since it is not
1110 	 * traced in the old kernel.
1111 	 */
1112 	ret = cpu_isa_config(kvm);
1113 	if (ret < 0)
1114 		goto out_delete;
1115 
1116 	ret = perf_session__process_events(kvm->session);
1117 
1118 out_delete:
1119 	perf_session__delete(kvm->session);
1120 	return ret;
1121 }
1122 
1123 static int parse_target_str(struct perf_kvm_stat *kvm)
1124 {
1125 	if (kvm->opts.target.pid) {
1126 		kvm->pid_list = intlist__new(kvm->opts.target.pid);
1127 		if (kvm->pid_list == NULL) {
1128 			pr_err("Error parsing process id string\n");
1129 			return -EINVAL;
1130 		}
1131 	}
1132 
1133 	return 0;
1134 }
1135 
1136 static int kvm_events_report_vcpu(struct perf_kvm_stat *kvm)
1137 {
1138 	int ret = -EINVAL;
1139 	int vcpu = kvm->trace_vcpu;
1140 
1141 	if (parse_target_str(kvm) != 0)
1142 		goto exit;
1143 
1144 	if (!verify_vcpu(vcpu))
1145 		goto exit;
1146 
1147 	if (!select_key(kvm))
1148 		goto exit;
1149 
1150 	if (!register_kvm_events_ops(kvm))
1151 		goto exit;
1152 
1153 	init_kvm_event_record(kvm);
1154 	setup_pager();
1155 
1156 	ret = read_events(kvm);
1157 	if (ret)
1158 		goto exit;
1159 
1160 	sort_result(kvm);
1161 	print_result(kvm);
1162 
1163 exit:
1164 	return ret;
1165 }
1166 
1167 #define STRDUP_FAIL_EXIT(s)		\
1168 	({	char *_p;		\
1169 	_p = strdup(s);		\
1170 		if (!_p)		\
1171 			return -ENOMEM;	\
1172 		_p;			\
1173 	})
1174 
1175 int __weak setup_kvm_events_tp(struct perf_kvm_stat *kvm __maybe_unused)
1176 {
1177 	return 0;
1178 }
1179 
1180 static int
1181 kvm_events_record(struct perf_kvm_stat *kvm, int argc, const char **argv)
1182 {
1183 	unsigned int rec_argc, i, j, events_tp_size;
1184 	const char **rec_argv;
1185 	const char * const record_args[] = {
1186 		"record",
1187 		"-R",
1188 		"-m", "1024",
1189 		"-c", "1",
1190 	};
1191 	const char * const kvm_stat_record_usage[] = {
1192 		"perf kvm stat record [<options>]",
1193 		NULL
1194 	};
1195 	const char * const *events_tp;
1196 	int ret;
1197 
1198 	events_tp_size = 0;
1199 	ret = setup_kvm_events_tp(kvm);
1200 	if (ret < 0) {
1201 		pr_err("Unable to setup the kvm tracepoints\n");
1202 		return ret;
1203 	}
1204 
1205 	for (events_tp = kvm_events_tp; *events_tp; events_tp++)
1206 		events_tp_size++;
1207 
1208 	rec_argc = ARRAY_SIZE(record_args) + argc + 2 +
1209 		   2 * events_tp_size;
1210 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
1211 
1212 	if (rec_argv == NULL)
1213 		return -ENOMEM;
1214 
1215 	for (i = 0; i < ARRAY_SIZE(record_args); i++)
1216 		rec_argv[i] = STRDUP_FAIL_EXIT(record_args[i]);
1217 
1218 	for (j = 0; j < events_tp_size; j++) {
1219 		rec_argv[i++] = "-e";
1220 		rec_argv[i++] = STRDUP_FAIL_EXIT(kvm_events_tp[j]);
1221 	}
1222 
1223 	rec_argv[i++] = STRDUP_FAIL_EXIT("-o");
1224 	rec_argv[i++] = STRDUP_FAIL_EXIT(kvm->file_name);
1225 
1226 	for (j = 1; j < (unsigned int)argc; j++, i++)
1227 		rec_argv[i] = argv[j];
1228 
1229 	set_option_flag(record_options, 'e', "event", PARSE_OPT_HIDDEN);
1230 	set_option_flag(record_options, 0, "filter", PARSE_OPT_HIDDEN);
1231 	set_option_flag(record_options, 'R', "raw-samples", PARSE_OPT_HIDDEN);
1232 
1233 	set_option_flag(record_options, 'F', "freq", PARSE_OPT_DISABLED);
1234 	set_option_flag(record_options, 0, "group", PARSE_OPT_DISABLED);
1235 	set_option_flag(record_options, 'g', NULL, PARSE_OPT_DISABLED);
1236 	set_option_flag(record_options, 0, "call-graph", PARSE_OPT_DISABLED);
1237 	set_option_flag(record_options, 'd', "data", PARSE_OPT_DISABLED);
1238 	set_option_flag(record_options, 'T', "timestamp", PARSE_OPT_DISABLED);
1239 	set_option_flag(record_options, 'P', "period", PARSE_OPT_DISABLED);
1240 	set_option_flag(record_options, 'n', "no-samples", PARSE_OPT_DISABLED);
1241 	set_option_flag(record_options, 'N', "no-buildid-cache", PARSE_OPT_DISABLED);
1242 	set_option_flag(record_options, 'B', "no-buildid", PARSE_OPT_DISABLED);
1243 	set_option_flag(record_options, 'G', "cgroup", PARSE_OPT_DISABLED);
1244 	set_option_flag(record_options, 'b', "branch-any", PARSE_OPT_DISABLED);
1245 	set_option_flag(record_options, 'j', "branch-filter", PARSE_OPT_DISABLED);
1246 	set_option_flag(record_options, 'W', "weight", PARSE_OPT_DISABLED);
1247 	set_option_flag(record_options, 0, "transaction", PARSE_OPT_DISABLED);
1248 
1249 	record_usage = kvm_stat_record_usage;
1250 	return cmd_record(i, rec_argv);
1251 }
1252 
1253 static int
1254 kvm_events_report(struct perf_kvm_stat *kvm, int argc, const char **argv)
1255 {
1256 	const struct option kvm_events_report_options[] = {
1257 		OPT_STRING(0, "event", &kvm->report_event, "report event",
1258 			   "event for reporting: vmexit, "
1259 			   "mmio (x86 only), ioport (x86 only)"),
1260 		OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1261 			    "vcpu id to report"),
1262 		OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1263 			    "key for sorting: sample(sort by samples number)"
1264 			    " time (sort by avg time)"),
1265 		OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1266 			   "analyze events only for given process id(s)"),
1267 		OPT_BOOLEAN('f', "force", &kvm->force, "don't complain, do it"),
1268 		OPT_END()
1269 	};
1270 
1271 	const char * const kvm_events_report_usage[] = {
1272 		"perf kvm stat report [<options>]",
1273 		NULL
1274 	};
1275 
1276 	if (argc) {
1277 		argc = parse_options(argc, argv,
1278 				     kvm_events_report_options,
1279 				     kvm_events_report_usage, 0);
1280 		if (argc)
1281 			usage_with_options(kvm_events_report_usage,
1282 					   kvm_events_report_options);
1283 	}
1284 
1285 	if (!kvm->opts.target.pid)
1286 		kvm->opts.target.system_wide = true;
1287 
1288 	return kvm_events_report_vcpu(kvm);
1289 }
1290 
1291 #ifdef HAVE_TIMERFD_SUPPORT
1292 static struct evlist *kvm_live_event_list(void)
1293 {
1294 	struct evlist *evlist;
1295 	char *tp, *name, *sys;
1296 	int err = -1;
1297 	const char * const *events_tp;
1298 
1299 	evlist = evlist__new();
1300 	if (evlist == NULL)
1301 		return NULL;
1302 
1303 	for (events_tp = kvm_events_tp; *events_tp; events_tp++) {
1304 
1305 		tp = strdup(*events_tp);
1306 		if (tp == NULL)
1307 			goto out;
1308 
1309 		/* split tracepoint into subsystem and name */
1310 		sys = tp;
1311 		name = strchr(tp, ':');
1312 		if (name == NULL) {
1313 			pr_err("Error parsing %s tracepoint: subsystem delimiter not found\n",
1314 			       *events_tp);
1315 			free(tp);
1316 			goto out;
1317 		}
1318 		*name = '\0';
1319 		name++;
1320 
1321 		if (perf_evlist__add_newtp(evlist, sys, name, NULL)) {
1322 			pr_err("Failed to add %s tracepoint to the list\n", *events_tp);
1323 			free(tp);
1324 			goto out;
1325 		}
1326 
1327 		free(tp);
1328 	}
1329 
1330 	err = 0;
1331 
1332 out:
1333 	if (err) {
1334 		evlist__delete(evlist);
1335 		evlist = NULL;
1336 	}
1337 
1338 	return evlist;
1339 }
1340 
1341 static int kvm_events_live(struct perf_kvm_stat *kvm,
1342 			   int argc, const char **argv)
1343 {
1344 	char errbuf[BUFSIZ];
1345 	int err;
1346 
1347 	const struct option live_options[] = {
1348 		OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1349 			"record events on existing process id"),
1350 		OPT_CALLBACK('m', "mmap-pages", &kvm->opts.mmap_pages, "pages",
1351 			"number of mmap data pages",
1352 			perf_evlist__parse_mmap_pages),
1353 		OPT_INCR('v', "verbose", &verbose,
1354 			"be more verbose (show counter open errors, etc)"),
1355 		OPT_BOOLEAN('a', "all-cpus", &kvm->opts.target.system_wide,
1356 			"system-wide collection from all CPUs"),
1357 		OPT_UINTEGER('d', "display", &kvm->display_time,
1358 			"time in seconds between display updates"),
1359 		OPT_STRING(0, "event", &kvm->report_event, "report event",
1360 			"event for reporting: "
1361 			"vmexit, mmio (x86 only), ioport (x86 only)"),
1362 		OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1363 			"vcpu id to report"),
1364 		OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1365 			"key for sorting: sample(sort by samples number)"
1366 			" time (sort by avg time)"),
1367 		OPT_U64(0, "duration", &kvm->duration,
1368 			"show events other than"
1369 			" HLT (x86 only) or Wait state (s390 only)"
1370 			" that take longer than duration usecs"),
1371 		OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
1372 				"per thread proc mmap processing timeout in ms"),
1373 		OPT_END()
1374 	};
1375 	const char * const live_usage[] = {
1376 		"perf kvm stat live [<options>]",
1377 		NULL
1378 	};
1379 	struct perf_data data = {
1380 		.mode = PERF_DATA_MODE_WRITE,
1381 	};
1382 
1383 
1384 	/* event handling */
1385 	kvm->tool.sample = process_sample_event;
1386 	kvm->tool.comm   = perf_event__process_comm;
1387 	kvm->tool.exit   = perf_event__process_exit;
1388 	kvm->tool.fork   = perf_event__process_fork;
1389 	kvm->tool.lost   = process_lost_event;
1390 	kvm->tool.namespaces  = perf_event__process_namespaces;
1391 	kvm->tool.ordered_events = true;
1392 	perf_tool__fill_defaults(&kvm->tool);
1393 
1394 	/* set defaults */
1395 	kvm->display_time = 1;
1396 	kvm->opts.user_interval = 1;
1397 	kvm->opts.mmap_pages = 512;
1398 	kvm->opts.target.uses_mmap = false;
1399 	kvm->opts.target.uid_str = NULL;
1400 	kvm->opts.target.uid = UINT_MAX;
1401 
1402 	symbol__init(NULL);
1403 	disable_buildid_cache();
1404 
1405 	use_browser = 0;
1406 
1407 	if (argc) {
1408 		argc = parse_options(argc, argv, live_options,
1409 				     live_usage, 0);
1410 		if (argc)
1411 			usage_with_options(live_usage, live_options);
1412 	}
1413 
1414 	kvm->duration *= NSEC_PER_USEC;   /* convert usec to nsec */
1415 
1416 	/*
1417 	 * target related setups
1418 	 */
1419 	err = target__validate(&kvm->opts.target);
1420 	if (err) {
1421 		target__strerror(&kvm->opts.target, err, errbuf, BUFSIZ);
1422 		ui__warning("%s", errbuf);
1423 	}
1424 
1425 	if (target__none(&kvm->opts.target))
1426 		kvm->opts.target.system_wide = true;
1427 
1428 
1429 	/*
1430 	 * generate the event list
1431 	 */
1432 	err = setup_kvm_events_tp(kvm);
1433 	if (err < 0) {
1434 		pr_err("Unable to setup the kvm tracepoints\n");
1435 		return err;
1436 	}
1437 
1438 	kvm->evlist = kvm_live_event_list();
1439 	if (kvm->evlist == NULL) {
1440 		err = -1;
1441 		goto out;
1442 	}
1443 
1444 	if (perf_evlist__create_maps(kvm->evlist, &kvm->opts.target) < 0)
1445 		usage_with_options(live_usage, live_options);
1446 
1447 	/*
1448 	 * perf session
1449 	 */
1450 	kvm->session = perf_session__new(&data, false, &kvm->tool);
1451 	if (IS_ERR(kvm->session)) {
1452 		err = PTR_ERR(kvm->session);
1453 		goto out;
1454 	}
1455 	kvm->session->evlist = kvm->evlist;
1456 	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 				    kvm->evlist->core.threads, false, 1);
1460 	err = kvm_live_open_events(kvm);
1461 	if (err)
1462 		goto out;
1463 
1464 	err = kvm_events_live_report(kvm);
1465 
1466 out:
1467 	perf_session__delete(kvm->session);
1468 	kvm->session = NULL;
1469 	evlist__delete(kvm->evlist);
1470 
1471 	return err;
1472 }
1473 #endif
1474 
1475 static void print_kvm_stat_usage(void)
1476 {
1477 	printf("Usage: perf kvm stat <command>\n\n");
1478 
1479 	printf("# Available commands:\n");
1480 	printf("\trecord: record kvm events\n");
1481 	printf("\treport: report statistical data of kvm events\n");
1482 	printf("\tlive:   live reporting of statistical data of kvm events\n");
1483 
1484 	printf("\nOtherwise, it is the alias of 'perf stat':\n");
1485 }
1486 
1487 static int kvm_cmd_stat(const char *file_name, int argc, const char **argv)
1488 {
1489 	struct perf_kvm_stat kvm = {
1490 		.file_name = file_name,
1491 
1492 		.trace_vcpu	= -1,
1493 		.report_event	= "vmexit",
1494 		.sort_key	= "sample",
1495 
1496 	};
1497 
1498 	if (argc == 1) {
1499 		print_kvm_stat_usage();
1500 		goto perf_stat;
1501 	}
1502 
1503 	if (!strncmp(argv[1], "rec", 3))
1504 		return kvm_events_record(&kvm, argc - 1, argv + 1);
1505 
1506 	if (!strncmp(argv[1], "rep", 3))
1507 		return kvm_events_report(&kvm, argc - 1 , argv + 1);
1508 
1509 #ifdef HAVE_TIMERFD_SUPPORT
1510 	if (!strncmp(argv[1], "live", 4))
1511 		return kvm_events_live(&kvm, argc - 1 , argv + 1);
1512 #endif
1513 
1514 perf_stat:
1515 	return cmd_stat(argc, argv);
1516 }
1517 #endif /* HAVE_KVM_STAT_SUPPORT */
1518 
1519 int __weak kvm_add_default_arch_event(int *argc __maybe_unused,
1520 					const char **argv __maybe_unused)
1521 {
1522 	return 0;
1523 }
1524 
1525 static int __cmd_record(const char *file_name, int argc, const char **argv)
1526 {
1527 	int rec_argc, i = 0, j, ret;
1528 	const char **rec_argv;
1529 
1530 	ret = kvm_add_default_arch_event(&argc, argv);
1531 	if (ret)
1532 		return -EINVAL;
1533 
1534 	rec_argc = argc + 2;
1535 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
1536 	rec_argv[i++] = strdup("record");
1537 	rec_argv[i++] = strdup("-o");
1538 	rec_argv[i++] = strdup(file_name);
1539 	for (j = 1; j < argc; j++, i++)
1540 		rec_argv[i] = argv[j];
1541 
1542 	BUG_ON(i != rec_argc);
1543 
1544 	return cmd_record(i, rec_argv);
1545 }
1546 
1547 static int __cmd_report(const char *file_name, int argc, const char **argv)
1548 {
1549 	int rec_argc, i = 0, j;
1550 	const char **rec_argv;
1551 
1552 	rec_argc = argc + 2;
1553 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
1554 	rec_argv[i++] = strdup("report");
1555 	rec_argv[i++] = strdup("-i");
1556 	rec_argv[i++] = strdup(file_name);
1557 	for (j = 1; j < argc; j++, i++)
1558 		rec_argv[i] = argv[j];
1559 
1560 	BUG_ON(i != rec_argc);
1561 
1562 	return cmd_report(i, rec_argv);
1563 }
1564 
1565 static int
1566 __cmd_buildid_list(const char *file_name, int argc, const char **argv)
1567 {
1568 	int rec_argc, i = 0, j;
1569 	const char **rec_argv;
1570 
1571 	rec_argc = argc + 2;
1572 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
1573 	rec_argv[i++] = strdup("buildid-list");
1574 	rec_argv[i++] = strdup("-i");
1575 	rec_argv[i++] = strdup(file_name);
1576 	for (j = 1; j < argc; j++, i++)
1577 		rec_argv[i] = argv[j];
1578 
1579 	BUG_ON(i != rec_argc);
1580 
1581 	return cmd_buildid_list(i, rec_argv);
1582 }
1583 
1584 int cmd_kvm(int argc, const char **argv)
1585 {
1586 	const char *file_name = NULL;
1587 	const struct option kvm_options[] = {
1588 		OPT_STRING('i', "input", &file_name, "file",
1589 			   "Input file name"),
1590 		OPT_STRING('o', "output", &file_name, "file",
1591 			   "Output file name"),
1592 		OPT_BOOLEAN(0, "guest", &perf_guest,
1593 			    "Collect guest os data"),
1594 		OPT_BOOLEAN(0, "host", &perf_host,
1595 			    "Collect host os data"),
1596 		OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
1597 			   "guest mount directory under which every guest os"
1598 			   " instance has a subdir"),
1599 		OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
1600 			   "file", "file saving guest os vmlinux"),
1601 		OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
1602 			   "file", "file saving guest os /proc/kallsyms"),
1603 		OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
1604 			   "file", "file saving guest os /proc/modules"),
1605 		OPT_INCR('v', "verbose", &verbose,
1606 			    "be more verbose (show counter open errors, etc)"),
1607 		OPT_END()
1608 	};
1609 
1610 	const char *const kvm_subcommands[] = { "top", "record", "report", "diff",
1611 						"buildid-list", "stat", NULL };
1612 	const char *kvm_usage[] = { NULL, NULL };
1613 
1614 	perf_host  = 0;
1615 	perf_guest = 1;
1616 
1617 	argc = parse_options_subcommand(argc, argv, kvm_options, kvm_subcommands, kvm_usage,
1618 					PARSE_OPT_STOP_AT_NON_OPTION);
1619 	if (!argc)
1620 		usage_with_options(kvm_usage, kvm_options);
1621 
1622 	if (!perf_host)
1623 		perf_guest = 1;
1624 
1625 	if (!file_name) {
1626 		file_name = get_filename_for_perf_kvm();
1627 
1628 		if (!file_name) {
1629 			pr_err("Failed to allocate memory for filename\n");
1630 			return -ENOMEM;
1631 		}
1632 	}
1633 
1634 	if (!strncmp(argv[0], "rec", 3))
1635 		return __cmd_record(file_name, argc, argv);
1636 	else if (!strncmp(argv[0], "rep", 3))
1637 		return __cmd_report(file_name, argc, argv);
1638 	else if (!strncmp(argv[0], "diff", 4))
1639 		return cmd_diff(argc, argv);
1640 	else if (!strncmp(argv[0], "top", 3))
1641 		return cmd_top(argc, argv);
1642 	else if (!strncmp(argv[0], "buildid-list", 12))
1643 		return __cmd_buildid_list(file_name, argc, argv);
1644 #ifdef HAVE_KVM_STAT_SUPPORT
1645 	else if (!strncmp(argv[0], "stat", 4))
1646 		return kvm_cmd_stat(file_name, argc, argv);
1647 #endif
1648 	else
1649 		usage_with_options(kvm_usage, kvm_options);
1650 
1651 	return 0;
1652 }
1653