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