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