qemu/target/i386/kvm.c
<<
>>
Prefs
   1/*
   2 * QEMU KVM support
   3 *
   4 * Copyright (C) 2006-2008 Qumranet Technologies
   5 * Copyright IBM, Corp. 2008
   6 *
   7 * Authors:
   8 *  Anthony Liguori   <aliguori@us.ibm.com>
   9 *
  10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
  11 * See the COPYING file in the top-level directory.
  12 *
  13 */
  14
  15#include "qemu/osdep.h"
  16#include "qapi/error.h"
  17#include <sys/ioctl.h>
  18#include <sys/utsname.h>
  19
  20#include <linux/kvm.h>
  21#include <linux/kvm_para.h>
  22
  23#include "qemu-common.h"
  24#include "cpu.h"
  25#include "sysemu/sysemu.h"
  26#include "sysemu/hw_accel.h"
  27#include "sysemu/kvm_int.h"
  28#include "kvm_i386.h"
  29#include "hyperv.h"
  30#include "hyperv-proto.h"
  31
  32#include "exec/gdbstub.h"
  33#include "qemu/host-utils.h"
  34#include "qemu/config-file.h"
  35#include "qemu/error-report.h"
  36#include "hw/i386/pc.h"
  37#include "hw/i386/apic.h"
  38#include "hw/i386/apic_internal.h"
  39#include "hw/i386/apic-msidef.h"
  40#include "hw/i386/intel_iommu.h"
  41#include "hw/i386/x86-iommu.h"
  42
  43#include "exec/ioport.h"
  44#include "hw/pci/pci.h"
  45#include "hw/pci/msi.h"
  46#include "hw/pci/msix.h"
  47#include "migration/blocker.h"
  48#include "exec/memattrs.h"
  49#include "trace.h"
  50
  51//#define DEBUG_KVM
  52
  53#ifdef DEBUG_KVM
  54#define DPRINTF(fmt, ...) \
  55    do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
  56#else
  57#define DPRINTF(fmt, ...) \
  58    do { } while (0)
  59#endif
  60
  61#define MSR_KVM_WALL_CLOCK  0x11
  62#define MSR_KVM_SYSTEM_TIME 0x12
  63
  64/* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
  65 * 255 kvm_msr_entry structs */
  66#define MSR_BUF_SIZE 4096
  67
  68const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
  69    KVM_CAP_INFO(SET_TSS_ADDR),
  70    KVM_CAP_INFO(EXT_CPUID),
  71    KVM_CAP_INFO(MP_STATE),
  72    KVM_CAP_LAST_INFO
  73};
  74
  75static bool has_msr_star;
  76static bool has_msr_hsave_pa;
  77static bool has_msr_tsc_aux;
  78static bool has_msr_tsc_adjust;
  79static bool has_msr_tsc_deadline;
  80static bool has_msr_feature_control;
  81static bool has_msr_misc_enable;
  82static bool has_msr_smbase;
  83static bool has_msr_bndcfgs;
  84static int lm_capable_kernel;
  85static bool has_msr_hv_hypercall;
  86static bool has_msr_hv_crash;
  87static bool has_msr_hv_reset;
  88static bool has_msr_hv_vpindex;
  89static bool has_msr_hv_runtime;
  90static bool has_msr_hv_synic;
  91static bool has_msr_hv_stimer;
  92static bool has_msr_hv_frequencies;
  93static bool has_msr_xss;
  94static bool has_msr_spec_ctrl;
  95static bool has_msr_smi_count;
  96
  97static uint32_t has_architectural_pmu_version;
  98static uint32_t num_architectural_pmu_gp_counters;
  99static uint32_t num_architectural_pmu_fixed_counters;
 100
 101static int has_xsave;
 102static int has_xcrs;
 103static int has_pit_state2;
 104
 105static bool has_msr_mcg_ext_ctl;
 106
 107static struct kvm_cpuid2 *cpuid_cache;
 108
 109int kvm_has_pit_state2(void)
 110{
 111    return has_pit_state2;
 112}
 113
 114bool kvm_has_smm(void)
 115{
 116    return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
 117}
 118
 119bool kvm_has_adjust_clock_stable(void)
 120{
 121    int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
 122
 123    return (ret == KVM_CLOCK_TSC_STABLE);
 124}
 125
 126bool kvm_allows_irq0_override(void)
 127{
 128    return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
 129}
 130
 131static bool kvm_x2apic_api_set_flags(uint64_t flags)
 132{
 133    KVMState *s = KVM_STATE(current_machine->accelerator);
 134
 135    return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
 136}
 137
 138#define MEMORIZE(fn, _result) \
 139    ({ \
 140        static bool _memorized; \
 141        \
 142        if (_memorized) { \
 143            return _result; \
 144        } \
 145        _memorized = true; \
 146        _result = fn; \
 147    })
 148
 149static bool has_x2apic_api;
 150
 151bool kvm_has_x2apic_api(void)
 152{
 153    return has_x2apic_api;
 154}
 155
 156bool kvm_enable_x2apic(void)
 157{
 158    return MEMORIZE(
 159             kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
 160                                      KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
 161             has_x2apic_api);
 162}
 163
 164static int kvm_get_tsc(CPUState *cs)
 165{
 166    X86CPU *cpu = X86_CPU(cs);
 167    CPUX86State *env = &cpu->env;
 168    struct {
 169        struct kvm_msrs info;
 170        struct kvm_msr_entry entries[1];
 171    } msr_data;
 172    int ret;
 173
 174    if (env->tsc_valid) {
 175        return 0;
 176    }
 177
 178    msr_data.info.nmsrs = 1;
 179    msr_data.entries[0].index = MSR_IA32_TSC;
 180    env->tsc_valid = !runstate_is_running();
 181
 182    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
 183    if (ret < 0) {
 184        return ret;
 185    }
 186
 187    assert(ret == 1);
 188    env->tsc = msr_data.entries[0].data;
 189    return 0;
 190}
 191
 192static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
 193{
 194    kvm_get_tsc(cpu);
 195}
 196
 197void kvm_synchronize_all_tsc(void)
 198{
 199    CPUState *cpu;
 200
 201    if (kvm_enabled()) {
 202        CPU_FOREACH(cpu) {
 203            run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
 204        }
 205    }
 206}
 207
 208static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
 209{
 210    struct kvm_cpuid2 *cpuid;
 211    int r, size;
 212
 213    size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
 214    cpuid = g_malloc0(size);
 215    cpuid->nent = max;
 216    r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
 217    if (r == 0 && cpuid->nent >= max) {
 218        r = -E2BIG;
 219    }
 220    if (r < 0) {
 221        if (r == -E2BIG) {
 222            g_free(cpuid);
 223            return NULL;
 224        } else {
 225            fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
 226                    strerror(-r));
 227            exit(1);
 228        }
 229    }
 230    return cpuid;
 231}
 232
 233/* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
 234 * for all entries.
 235 */
 236static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
 237{
 238    struct kvm_cpuid2 *cpuid;
 239    int max = 1;
 240
 241    if (cpuid_cache != NULL) {
 242        return cpuid_cache;
 243    }
 244    while ((cpuid = try_get_cpuid(s, max)) == NULL) {
 245        max *= 2;
 246    }
 247    cpuid_cache = cpuid;
 248    return cpuid;
 249}
 250
 251static const struct kvm_para_features {
 252    int cap;
 253    int feature;
 254} para_features[] = {
 255    { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
 256    { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
 257    { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
 258    { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
 259};
 260
 261static int get_para_features(KVMState *s)
 262{
 263    int i, features = 0;
 264
 265    for (i = 0; i < ARRAY_SIZE(para_features); i++) {
 266        if (kvm_check_extension(s, para_features[i].cap)) {
 267            features |= (1 << para_features[i].feature);
 268        }
 269    }
 270
 271    return features;
 272}
 273
 274static bool host_tsx_blacklisted(void)
 275{
 276    int family, model, stepping;\
 277    char vendor[CPUID_VENDOR_SZ + 1];
 278
 279    host_vendor_fms(vendor, &family, &model, &stepping);
 280
 281    /* Check if we are running on a Haswell host known to have broken TSX */
 282    return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
 283           (family == 6) &&
 284           ((model == 63 && stepping < 4) ||
 285            model == 60 || model == 69 || model == 70);
 286}
 287
 288/* Returns the value for a specific register on the cpuid entry
 289 */
 290static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
 291{
 292    uint32_t ret = 0;
 293    switch (reg) {
 294    case R_EAX:
 295        ret = entry->eax;
 296        break;
 297    case R_EBX:
 298        ret = entry->ebx;
 299        break;
 300    case R_ECX:
 301        ret = entry->ecx;
 302        break;
 303    case R_EDX:
 304        ret = entry->edx;
 305        break;
 306    }
 307    return ret;
 308}
 309
 310/* Find matching entry for function/index on kvm_cpuid2 struct
 311 */
 312static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
 313                                                 uint32_t function,
 314                                                 uint32_t index)
 315{
 316    int i;
 317    for (i = 0; i < cpuid->nent; ++i) {
 318        if (cpuid->entries[i].function == function &&
 319            cpuid->entries[i].index == index) {
 320            return &cpuid->entries[i];
 321        }
 322    }
 323    /* not found: */
 324    return NULL;
 325}
 326
 327uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
 328                                      uint32_t index, int reg)
 329{
 330    struct kvm_cpuid2 *cpuid;
 331    uint32_t ret = 0;
 332    uint32_t cpuid_1_edx;
 333    bool found = false;
 334
 335    cpuid = get_supported_cpuid(s);
 336
 337    struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
 338    if (entry) {
 339        found = true;
 340        ret = cpuid_entry_get_reg(entry, reg);
 341    }
 342
 343    /* Fixups for the data returned by KVM, below */
 344
 345    if (function == 1 && reg == R_EDX) {
 346        /* KVM before 2.6.30 misreports the following features */
 347        ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
 348    } else if (function == 1 && reg == R_ECX) {
 349        /* We can set the hypervisor flag, even if KVM does not return it on
 350         * GET_SUPPORTED_CPUID
 351         */
 352        ret |= CPUID_EXT_HYPERVISOR;
 353        /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
 354         * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
 355         * and the irqchip is in the kernel.
 356         */
 357        if (kvm_irqchip_in_kernel() &&
 358                kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
 359            ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
 360        }
 361
 362        /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
 363         * without the in-kernel irqchip
 364         */
 365        if (!kvm_irqchip_in_kernel()) {
 366            ret &= ~CPUID_EXT_X2APIC;
 367        }
 368    } else if (function == 6 && reg == R_EAX) {
 369        ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
 370    } else if (function == 7 && index == 0 && reg == R_EBX) {
 371        if (host_tsx_blacklisted()) {
 372            ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
 373        }
 374    } else if (function == 0x80000001 && reg == R_EDX) {
 375        /* On Intel, kvm returns cpuid according to the Intel spec,
 376         * so add missing bits according to the AMD spec:
 377         */
 378        cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
 379        ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
 380    } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
 381        /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
 382         * be enabled without the in-kernel irqchip
 383         */
 384        if (!kvm_irqchip_in_kernel()) {
 385            ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
 386        }
 387    } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
 388        ret |= KVM_HINTS_DEDICATED;
 389        found = 1;
 390    }
 391
 392    /* fallback for older kernels */
 393    if ((function == KVM_CPUID_FEATURES) && !found) {
 394        ret = get_para_features(s);
 395    }
 396
 397    return ret;
 398}
 399
 400typedef struct HWPoisonPage {
 401    ram_addr_t ram_addr;
 402    QLIST_ENTRY(HWPoisonPage) list;
 403} HWPoisonPage;
 404
 405static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
 406    QLIST_HEAD_INITIALIZER(hwpoison_page_list);
 407
 408static void kvm_unpoison_all(void *param)
 409{
 410    HWPoisonPage *page, *next_page;
 411
 412    QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
 413        QLIST_REMOVE(page, list);
 414        qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
 415        g_free(page);
 416    }
 417}
 418
 419static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
 420{
 421    HWPoisonPage *page;
 422
 423    QLIST_FOREACH(page, &hwpoison_page_list, list) {
 424        if (page->ram_addr == ram_addr) {
 425            return;
 426        }
 427    }
 428    page = g_new(HWPoisonPage, 1);
 429    page->ram_addr = ram_addr;
 430    QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
 431}
 432
 433static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
 434                                     int *max_banks)
 435{
 436    int r;
 437
 438    r = kvm_check_extension(s, KVM_CAP_MCE);
 439    if (r > 0) {
 440        *max_banks = r;
 441        return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
 442    }
 443    return -ENOSYS;
 444}
 445
 446static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
 447{
 448    CPUState *cs = CPU(cpu);
 449    CPUX86State *env = &cpu->env;
 450    uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
 451                      MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
 452    uint64_t mcg_status = MCG_STATUS_MCIP;
 453    int flags = 0;
 454
 455    if (code == BUS_MCEERR_AR) {
 456        status |= MCI_STATUS_AR | 0x134;
 457        mcg_status |= MCG_STATUS_EIPV;
 458    } else {
 459        status |= 0xc0;
 460        mcg_status |= MCG_STATUS_RIPV;
 461    }
 462
 463    flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
 464    /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
 465     * guest kernel back into env->mcg_ext_ctl.
 466     */
 467    cpu_synchronize_state(cs);
 468    if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
 469        mcg_status |= MCG_STATUS_LMCE;
 470        flags = 0;
 471    }
 472
 473    cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
 474                       (MCM_ADDR_PHYS << 6) | 0xc, flags);
 475}
 476
 477static void hardware_memory_error(void)
 478{
 479    fprintf(stderr, "Hardware memory error!\n");
 480    exit(1);
 481}
 482
 483void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
 484{
 485    X86CPU *cpu = X86_CPU(c);
 486    CPUX86State *env = &cpu->env;
 487    ram_addr_t ram_addr;
 488    hwaddr paddr;
 489
 490    /* If we get an action required MCE, it has been injected by KVM
 491     * while the VM was running.  An action optional MCE instead should
 492     * be coming from the main thread, which qemu_init_sigbus identifies
 493     * as the "early kill" thread.
 494     */
 495    assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
 496
 497    if ((env->mcg_cap & MCG_SER_P) && addr) {
 498        ram_addr = qemu_ram_addr_from_host(addr);
 499        if (ram_addr != RAM_ADDR_INVALID &&
 500            kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
 501            kvm_hwpoison_page_add(ram_addr);
 502            kvm_mce_inject(cpu, paddr, code);
 503            return;
 504        }
 505
 506        fprintf(stderr, "Hardware memory error for memory used by "
 507                "QEMU itself instead of guest system!\n");
 508    }
 509
 510    if (code == BUS_MCEERR_AR) {
 511        hardware_memory_error();
 512    }
 513
 514    /* Hope we are lucky for AO MCE */
 515}
 516
 517static int kvm_inject_mce_oldstyle(X86CPU *cpu)
 518{
 519    CPUX86State *env = &cpu->env;
 520
 521    if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
 522        unsigned int bank, bank_num = env->mcg_cap & 0xff;
 523        struct kvm_x86_mce mce;
 524
 525        env->exception_injected = -1;
 526
 527        /*
 528         * There must be at least one bank in use if an MCE is pending.
 529         * Find it and use its values for the event injection.
 530         */
 531        for (bank = 0; bank < bank_num; bank++) {
 532            if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
 533                break;
 534            }
 535        }
 536        assert(bank < bank_num);
 537
 538        mce.bank = bank;
 539        mce.status = env->mce_banks[bank * 4 + 1];
 540        mce.mcg_status = env->mcg_status;
 541        mce.addr = env->mce_banks[bank * 4 + 2];
 542        mce.misc = env->mce_banks[bank * 4 + 3];
 543
 544        return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
 545    }
 546    return 0;
 547}
 548
 549static void cpu_update_state(void *opaque, int running, RunState state)
 550{
 551    CPUX86State *env = opaque;
 552
 553    if (running) {
 554        env->tsc_valid = false;
 555    }
 556}
 557
 558unsigned long kvm_arch_vcpu_id(CPUState *cs)
 559{
 560    X86CPU *cpu = X86_CPU(cs);
 561    return cpu->apic_id;
 562}
 563
 564#ifndef KVM_CPUID_SIGNATURE_NEXT
 565#define KVM_CPUID_SIGNATURE_NEXT                0x40000100
 566#endif
 567
 568static bool hyperv_hypercall_available(X86CPU *cpu)
 569{
 570    return cpu->hyperv_vapic ||
 571           (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
 572}
 573
 574static bool hyperv_enabled(X86CPU *cpu)
 575{
 576    CPUState *cs = CPU(cpu);
 577    return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
 578           (hyperv_hypercall_available(cpu) ||
 579            cpu->hyperv_time  ||
 580            cpu->hyperv_relaxed_timing ||
 581            cpu->hyperv_crash ||
 582            cpu->hyperv_reset ||
 583            cpu->hyperv_vpindex ||
 584            cpu->hyperv_runtime ||
 585            cpu->hyperv_synic ||
 586            cpu->hyperv_stimer);
 587}
 588
 589static int kvm_arch_set_tsc_khz(CPUState *cs)
 590{
 591    X86CPU *cpu = X86_CPU(cs);
 592    CPUX86State *env = &cpu->env;
 593    int r;
 594
 595    if (!env->tsc_khz) {
 596        return 0;
 597    }
 598
 599    r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
 600        kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
 601        -ENOTSUP;
 602    if (r < 0) {
 603        /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
 604         * TSC frequency doesn't match the one we want.
 605         */
 606        int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
 607                       kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
 608                       -ENOTSUP;
 609        if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
 610            warn_report("TSC frequency mismatch between "
 611                        "VM (%" PRId64 " kHz) and host (%d kHz), "
 612                        "and TSC scaling unavailable",
 613                        env->tsc_khz, cur_freq);
 614            return r;
 615        }
 616    }
 617
 618    return 0;
 619}
 620
 621static bool tsc_is_stable_and_known(CPUX86State *env)
 622{
 623    if (!env->tsc_khz) {
 624        return false;
 625    }
 626    return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
 627        || env->user_tsc_khz;
 628}
 629
 630static int hyperv_handle_properties(CPUState *cs)
 631{
 632    X86CPU *cpu = X86_CPU(cs);
 633    CPUX86State *env = &cpu->env;
 634
 635    if (cpu->hyperv_relaxed_timing) {
 636        env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
 637    }
 638    if (cpu->hyperv_vapic) {
 639        env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
 640        env->features[FEAT_HYPERV_EAX] |= HV_APIC_ACCESS_AVAILABLE;
 641    }
 642    if (cpu->hyperv_time) {
 643        if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) <= 0) {
 644            fprintf(stderr, "Hyper-V clocksources "
 645                    "(requested by 'hv-time' cpu flag) "
 646                    "are not supported by kernel\n");
 647            return -ENOSYS;
 648        }
 649        env->features[FEAT_HYPERV_EAX] |= HV_HYPERCALL_AVAILABLE;
 650        env->features[FEAT_HYPERV_EAX] |= HV_TIME_REF_COUNT_AVAILABLE;
 651        env->features[FEAT_HYPERV_EAX] |= HV_REFERENCE_TSC_AVAILABLE;
 652    }
 653    if (cpu->hyperv_frequencies) {
 654        if (!has_msr_hv_frequencies) {
 655            fprintf(stderr, "Hyper-V frequency MSRs "
 656                    "(requested by 'hv-frequencies' cpu flag) "
 657                    "are not supported by kernel\n");
 658            return -ENOSYS;
 659        }
 660        env->features[FEAT_HYPERV_EAX] |= HV_ACCESS_FREQUENCY_MSRS;
 661        env->features[FEAT_HYPERV_EDX] |= HV_FREQUENCY_MSRS_AVAILABLE;
 662    }
 663    if (cpu->hyperv_crash) {
 664        if (!has_msr_hv_crash) {
 665            fprintf(stderr, "Hyper-V crash MSRs "
 666                    "(requested by 'hv-crash' cpu flag) "
 667                    "are not supported by kernel\n");
 668            return -ENOSYS;
 669        }
 670        env->features[FEAT_HYPERV_EDX] |= HV_GUEST_CRASH_MSR_AVAILABLE;
 671    }
 672    env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
 673    if (cpu->hyperv_reset) {
 674        if (!has_msr_hv_reset) {
 675            fprintf(stderr, "Hyper-V reset MSR "
 676                    "(requested by 'hv-reset' cpu flag) "
 677                    "is not supported by kernel\n");
 678            return -ENOSYS;
 679        }
 680        env->features[FEAT_HYPERV_EAX] |= HV_RESET_AVAILABLE;
 681    }
 682    if (cpu->hyperv_vpindex) {
 683        if (!has_msr_hv_vpindex) {
 684            fprintf(stderr, "Hyper-V VP_INDEX MSR "
 685                    "(requested by 'hv-vpindex' cpu flag) "
 686                    "is not supported by kernel\n");
 687            return -ENOSYS;
 688        }
 689        env->features[FEAT_HYPERV_EAX] |= HV_VP_INDEX_AVAILABLE;
 690    }
 691    if (cpu->hyperv_runtime) {
 692        if (!has_msr_hv_runtime) {
 693            fprintf(stderr, "Hyper-V VP_RUNTIME MSR "
 694                    "(requested by 'hv-runtime' cpu flag) "
 695                    "is not supported by kernel\n");
 696            return -ENOSYS;
 697        }
 698        env->features[FEAT_HYPERV_EAX] |= HV_VP_RUNTIME_AVAILABLE;
 699    }
 700    if (cpu->hyperv_synic) {
 701        if (!has_msr_hv_synic ||
 702            kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
 703            fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
 704            return -ENOSYS;
 705        }
 706
 707        env->features[FEAT_HYPERV_EAX] |= HV_SYNIC_AVAILABLE;
 708    }
 709    if (cpu->hyperv_stimer) {
 710        if (!has_msr_hv_stimer) {
 711            fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
 712            return -ENOSYS;
 713        }
 714        env->features[FEAT_HYPERV_EAX] |= HV_SYNTIMERS_AVAILABLE;
 715    }
 716    return 0;
 717}
 718
 719static Error *invtsc_mig_blocker;
 720
 721#define KVM_MAX_CPUID_ENTRIES  100
 722
 723int kvm_arch_init_vcpu(CPUState *cs)
 724{
 725    struct {
 726        struct kvm_cpuid2 cpuid;
 727        struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
 728    } QEMU_PACKED cpuid_data;
 729    X86CPU *cpu = X86_CPU(cs);
 730    CPUX86State *env = &cpu->env;
 731    uint32_t limit, i, j, cpuid_i;
 732    uint32_t unused;
 733    struct kvm_cpuid_entry2 *c;
 734    uint32_t signature[3];
 735    int kvm_base = KVM_CPUID_SIGNATURE;
 736    int r;
 737    Error *local_err = NULL;
 738
 739    memset(&cpuid_data, 0, sizeof(cpuid_data));
 740
 741    cpuid_i = 0;
 742
 743    r = kvm_arch_set_tsc_khz(cs);
 744    if (r < 0) {
 745        goto fail;
 746    }
 747
 748    /* vcpu's TSC frequency is either specified by user, or following
 749     * the value used by KVM if the former is not present. In the
 750     * latter case, we query it from KVM and record in env->tsc_khz,
 751     * so that vcpu's TSC frequency can be migrated later via this field.
 752     */
 753    if (!env->tsc_khz) {
 754        r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
 755            kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
 756            -ENOTSUP;
 757        if (r > 0) {
 758            env->tsc_khz = r;
 759        }
 760    }
 761
 762    /* Paravirtualization CPUIDs */
 763    if (hyperv_enabled(cpu)) {
 764        c = &cpuid_data.entries[cpuid_i++];
 765        c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
 766        if (!cpu->hyperv_vendor_id) {
 767            memcpy(signature, "Microsoft Hv", 12);
 768        } else {
 769            size_t len = strlen(cpu->hyperv_vendor_id);
 770
 771            if (len > 12) {
 772                error_report("hv-vendor-id truncated to 12 characters");
 773                len = 12;
 774            }
 775            memset(signature, 0, 12);
 776            memcpy(signature, cpu->hyperv_vendor_id, len);
 777        }
 778        c->eax = HV_CPUID_MIN;
 779        c->ebx = signature[0];
 780        c->ecx = signature[1];
 781        c->edx = signature[2];
 782
 783        c = &cpuid_data.entries[cpuid_i++];
 784        c->function = HV_CPUID_INTERFACE;
 785        memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
 786        c->eax = signature[0];
 787        c->ebx = 0;
 788        c->ecx = 0;
 789        c->edx = 0;
 790
 791        c = &cpuid_data.entries[cpuid_i++];
 792        c->function = HV_CPUID_VERSION;
 793        c->eax = 0x00001bbc;
 794        c->ebx = 0x00060001;
 795
 796        c = &cpuid_data.entries[cpuid_i++];
 797        c->function = HV_CPUID_FEATURES;
 798        r = hyperv_handle_properties(cs);
 799        if (r) {
 800            return r;
 801        }
 802        c->eax = env->features[FEAT_HYPERV_EAX];
 803        c->ebx = env->features[FEAT_HYPERV_EBX];
 804        c->edx = env->features[FEAT_HYPERV_EDX];
 805
 806        c = &cpuid_data.entries[cpuid_i++];
 807        c->function = HV_CPUID_ENLIGHTMENT_INFO;
 808        if (cpu->hyperv_relaxed_timing) {
 809            c->eax |= HV_RELAXED_TIMING_RECOMMENDED;
 810        }
 811        if (cpu->hyperv_vapic) {
 812            c->eax |= HV_APIC_ACCESS_RECOMMENDED;
 813        }
 814        c->ebx = cpu->hyperv_spinlock_attempts;
 815
 816        c = &cpuid_data.entries[cpuid_i++];
 817        c->function = HV_CPUID_IMPLEMENT_LIMITS;
 818
 819        c->eax = cpu->hv_max_vps;
 820        c->ebx = 0x40;
 821
 822        kvm_base = KVM_CPUID_SIGNATURE_NEXT;
 823        has_msr_hv_hypercall = true;
 824    }
 825
 826    if (cpu->expose_kvm) {
 827        memcpy(signature, "KVMKVMKVM\0\0\0", 12);
 828        c = &cpuid_data.entries[cpuid_i++];
 829        c->function = KVM_CPUID_SIGNATURE | kvm_base;
 830        c->eax = KVM_CPUID_FEATURES | kvm_base;
 831        c->ebx = signature[0];
 832        c->ecx = signature[1];
 833        c->edx = signature[2];
 834
 835        c = &cpuid_data.entries[cpuid_i++];
 836        c->function = KVM_CPUID_FEATURES | kvm_base;
 837        c->eax = env->features[FEAT_KVM];
 838        c->edx = env->features[FEAT_KVM_HINTS];
 839    }
 840
 841    cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
 842
 843    for (i = 0; i <= limit; i++) {
 844        if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 845            fprintf(stderr, "unsupported level value: 0x%x\n", limit);
 846            abort();
 847        }
 848        c = &cpuid_data.entries[cpuid_i++];
 849
 850        switch (i) {
 851        case 2: {
 852            /* Keep reading function 2 till all the input is received */
 853            int times;
 854
 855            c->function = i;
 856            c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
 857                       KVM_CPUID_FLAG_STATE_READ_NEXT;
 858            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 859            times = c->eax & 0xff;
 860
 861            for (j = 1; j < times; ++j) {
 862                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 863                    fprintf(stderr, "cpuid_data is full, no space for "
 864                            "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
 865                    abort();
 866                }
 867                c = &cpuid_data.entries[cpuid_i++];
 868                c->function = i;
 869                c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
 870                cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 871            }
 872            break;
 873        }
 874        case 4:
 875        case 0xb:
 876        case 0xd:
 877            for (j = 0; ; j++) {
 878                if (i == 0xd && j == 64) {
 879                    break;
 880                }
 881                c->function = i;
 882                c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
 883                c->index = j;
 884                cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
 885
 886                if (i == 4 && c->eax == 0) {
 887                    break;
 888                }
 889                if (i == 0xb && !(c->ecx & 0xff00)) {
 890                    break;
 891                }
 892                if (i == 0xd && c->eax == 0) {
 893                    continue;
 894                }
 895                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 896                    fprintf(stderr, "cpuid_data is full, no space for "
 897                            "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
 898                    abort();
 899                }
 900                c = &cpuid_data.entries[cpuid_i++];
 901            }
 902            break;
 903        case 0x14: {
 904            uint32_t times;
 905
 906            c->function = i;
 907            c->index = 0;
 908            c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
 909            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 910            times = c->eax;
 911
 912            for (j = 1; j <= times; ++j) {
 913                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 914                    fprintf(stderr, "cpuid_data is full, no space for "
 915                                "cpuid(eax:0x14,ecx:0x%x)\n", j);
 916                    abort();
 917                }
 918                c = &cpuid_data.entries[cpuid_i++];
 919                c->function = i;
 920                c->index = j;
 921                c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
 922                cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
 923            }
 924            break;
 925        }
 926        default:
 927            c->function = i;
 928            c->flags = 0;
 929            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 930            break;
 931        }
 932    }
 933
 934    if (limit >= 0x0a) {
 935        uint32_t eax, edx;
 936
 937        cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
 938
 939        has_architectural_pmu_version = eax & 0xff;
 940        if (has_architectural_pmu_version > 0) {
 941            num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
 942
 943            /* Shouldn't be more than 32, since that's the number of bits
 944             * available in EBX to tell us _which_ counters are available.
 945             * Play it safe.
 946             */
 947            if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
 948                num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
 949            }
 950
 951            if (has_architectural_pmu_version > 1) {
 952                num_architectural_pmu_fixed_counters = edx & 0x1f;
 953
 954                if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
 955                    num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
 956                }
 957            }
 958        }
 959    }
 960
 961    cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
 962
 963    for (i = 0x80000000; i <= limit; i++) {
 964        if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 965            fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
 966            abort();
 967        }
 968        c = &cpuid_data.entries[cpuid_i++];
 969
 970        c->function = i;
 971        c->flags = 0;
 972        cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 973    }
 974
 975    /* Call Centaur's CPUID instructions they are supported. */
 976    if (env->cpuid_xlevel2 > 0) {
 977        cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
 978
 979        for (i = 0xC0000000; i <= limit; i++) {
 980            if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 981                fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
 982                abort();
 983            }
 984            c = &cpuid_data.entries[cpuid_i++];
 985
 986            c->function = i;
 987            c->flags = 0;
 988            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 989        }
 990    }
 991
 992    cpuid_data.cpuid.nent = cpuid_i;
 993
 994    if (((env->cpuid_version >> 8)&0xF) >= 6
 995        && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
 996           (CPUID_MCE | CPUID_MCA)
 997        && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
 998        uint64_t mcg_cap, unsupported_caps;
 999        int banks;
1000        int ret;
1001
1002        ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1003        if (ret < 0) {
1004            fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1005            return ret;
1006        }
1007
1008        if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1009            error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1010                         (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1011            return -ENOTSUP;
1012        }
1013
1014        unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1015        if (unsupported_caps) {
1016            if (unsupported_caps & MCG_LMCE_P) {
1017                error_report("kvm: LMCE not supported");
1018                return -ENOTSUP;
1019            }
1020            warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1021                        unsupported_caps);
1022        }
1023
1024        env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1025        ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1026        if (ret < 0) {
1027            fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1028            return ret;
1029        }
1030    }
1031
1032    qemu_add_vm_change_state_handler(cpu_update_state, env);
1033
1034    c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1035    if (c) {
1036        has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1037                                  !!(c->ecx & CPUID_EXT_SMX);
1038    }
1039
1040    if (env->mcg_cap & MCG_LMCE_P) {
1041        has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1042    }
1043
1044    if (!env->user_tsc_khz) {
1045        if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1046            invtsc_mig_blocker == NULL) {
1047            /* for migration */
1048            error_setg(&invtsc_mig_blocker,
1049                       "State blocked by non-migratable CPU device"
1050                       " (invtsc flag)");
1051            r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1052            if (local_err) {
1053                error_report_err(local_err);
1054                error_free(invtsc_mig_blocker);
1055                goto fail;
1056            }
1057            /* for savevm */
1058            vmstate_x86_cpu.unmigratable = 1;
1059        }
1060    }
1061
1062    if (cpu->vmware_cpuid_freq
1063        /* Guests depend on 0x40000000 to detect this feature, so only expose
1064         * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1065        && cpu->expose_kvm
1066        && kvm_base == KVM_CPUID_SIGNATURE
1067        /* TSC clock must be stable and known for this feature. */
1068        && tsc_is_stable_and_known(env)) {
1069
1070        c = &cpuid_data.entries[cpuid_i++];
1071        c->function = KVM_CPUID_SIGNATURE | 0x10;
1072        c->eax = env->tsc_khz;
1073        /* LAPIC resolution of 1ns (freq: 1GHz) is hardcoded in KVM's
1074         * APIC_BUS_CYCLE_NS */
1075        c->ebx = 1000000;
1076        c->ecx = c->edx = 0;
1077
1078        c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1079        c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1080    }
1081
1082    cpuid_data.cpuid.nent = cpuid_i;
1083
1084    cpuid_data.cpuid.padding = 0;
1085    r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1086    if (r) {
1087        goto fail;
1088    }
1089
1090    if (has_xsave) {
1091        env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1092    }
1093    cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1094
1095    if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1096        has_msr_tsc_aux = false;
1097    }
1098
1099    return 0;
1100
1101 fail:
1102    migrate_del_blocker(invtsc_mig_blocker);
1103    return r;
1104}
1105
1106void kvm_arch_reset_vcpu(X86CPU *cpu)
1107{
1108    CPUX86State *env = &cpu->env;
1109
1110    env->xcr0 = 1;
1111    if (kvm_irqchip_in_kernel()) {
1112        env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1113                                          KVM_MP_STATE_UNINITIALIZED;
1114    } else {
1115        env->mp_state = KVM_MP_STATE_RUNNABLE;
1116    }
1117
1118    if (cpu->hyperv_synic) {
1119        int i;
1120        for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1121            env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1122        }
1123    }
1124}
1125
1126void kvm_arch_do_init_vcpu(X86CPU *cpu)
1127{
1128    CPUX86State *env = &cpu->env;
1129
1130    /* APs get directly into wait-for-SIPI state.  */
1131    if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1132        env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1133    }
1134}
1135
1136static int kvm_get_supported_msrs(KVMState *s)
1137{
1138    static int kvm_supported_msrs;
1139    int ret = 0;
1140
1141    /* first time */
1142    if (kvm_supported_msrs == 0) {
1143        struct kvm_msr_list msr_list, *kvm_msr_list;
1144
1145        kvm_supported_msrs = -1;
1146
1147        /* Obtain MSR list from KVM.  These are the MSRs that we must
1148         * save/restore */
1149        msr_list.nmsrs = 0;
1150        ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1151        if (ret < 0 && ret != -E2BIG) {
1152            return ret;
1153        }
1154        /* Old kernel modules had a bug and could write beyond the provided
1155           memory. Allocate at least a safe amount of 1K. */
1156        kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1157                                              msr_list.nmsrs *
1158                                              sizeof(msr_list.indices[0])));
1159
1160        kvm_msr_list->nmsrs = msr_list.nmsrs;
1161        ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1162        if (ret >= 0) {
1163            int i;
1164
1165            for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1166                switch (kvm_msr_list->indices[i]) {
1167                case MSR_STAR:
1168                    has_msr_star = true;
1169                    break;
1170                case MSR_VM_HSAVE_PA:
1171                    has_msr_hsave_pa = true;
1172                    break;
1173                case MSR_TSC_AUX:
1174                    has_msr_tsc_aux = true;
1175                    break;
1176                case MSR_TSC_ADJUST:
1177                    has_msr_tsc_adjust = true;
1178                    break;
1179                case MSR_IA32_TSCDEADLINE:
1180                    has_msr_tsc_deadline = true;
1181                    break;
1182                case MSR_IA32_SMBASE:
1183                    has_msr_smbase = true;
1184                    break;
1185                case MSR_SMI_COUNT:
1186                    has_msr_smi_count = true;
1187                    break;
1188                case MSR_IA32_MISC_ENABLE:
1189                    has_msr_misc_enable = true;
1190                    break;
1191                case MSR_IA32_BNDCFGS:
1192                    has_msr_bndcfgs = true;
1193                    break;
1194                case MSR_IA32_XSS:
1195                    has_msr_xss = true;
1196                    break;
1197                case HV_X64_MSR_CRASH_CTL:
1198                    has_msr_hv_crash = true;
1199                    break;
1200                case HV_X64_MSR_RESET:
1201                    has_msr_hv_reset = true;
1202                    break;
1203                case HV_X64_MSR_VP_INDEX:
1204                    has_msr_hv_vpindex = true;
1205                    break;
1206                case HV_X64_MSR_VP_RUNTIME:
1207                    has_msr_hv_runtime = true;
1208                    break;
1209                case HV_X64_MSR_SCONTROL:
1210                    has_msr_hv_synic = true;
1211                    break;
1212                case HV_X64_MSR_STIMER0_CONFIG:
1213                    has_msr_hv_stimer = true;
1214                    break;
1215                case HV_X64_MSR_TSC_FREQUENCY:
1216                    has_msr_hv_frequencies = true;
1217                    break;
1218                case MSR_IA32_SPEC_CTRL:
1219                    has_msr_spec_ctrl = true;
1220                    break;
1221                }
1222            }
1223        }
1224
1225        g_free(kvm_msr_list);
1226    }
1227
1228    return ret;
1229}
1230
1231static Notifier smram_machine_done;
1232static KVMMemoryListener smram_listener;
1233static AddressSpace smram_address_space;
1234static MemoryRegion smram_as_root;
1235static MemoryRegion smram_as_mem;
1236
1237static void register_smram_listener(Notifier *n, void *unused)
1238{
1239    MemoryRegion *smram =
1240        (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
1241
1242    /* Outer container... */
1243    memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
1244    memory_region_set_enabled(&smram_as_root, true);
1245
1246    /* ... with two regions inside: normal system memory with low
1247     * priority, and...
1248     */
1249    memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
1250                             get_system_memory(), 0, ~0ull);
1251    memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
1252    memory_region_set_enabled(&smram_as_mem, true);
1253
1254    if (smram) {
1255        /* ... SMRAM with higher priority */
1256        memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
1257        memory_region_set_enabled(smram, true);
1258    }
1259
1260    address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
1261    kvm_memory_listener_register(kvm_state, &smram_listener,
1262                                 &smram_address_space, 1);
1263}
1264
1265int kvm_arch_init(MachineState *ms, KVMState *s)
1266{
1267    uint64_t identity_base = 0xfffbc000;
1268    uint64_t shadow_mem;
1269    int ret;
1270    struct utsname utsname;
1271
1272#ifdef KVM_CAP_XSAVE
1273    has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
1274#endif
1275
1276#ifdef KVM_CAP_XCRS
1277    has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
1278#endif
1279
1280#ifdef KVM_CAP_PIT_STATE2
1281    has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
1282#endif
1283
1284    ret = kvm_get_supported_msrs(s);
1285    if (ret < 0) {
1286        return ret;
1287    }
1288
1289    uname(&utsname);
1290    lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
1291
1292    /*
1293     * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
1294     * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
1295     * Since these must be part of guest physical memory, we need to allocate
1296     * them, both by setting their start addresses in the kernel and by
1297     * creating a corresponding e820 entry. We need 4 pages before the BIOS.
1298     *
1299     * Older KVM versions may not support setting the identity map base. In
1300     * that case we need to stick with the default, i.e. a 256K maximum BIOS
1301     * size.
1302     */
1303    if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
1304        /* Allows up to 16M BIOSes. */
1305        identity_base = 0xfeffc000;
1306
1307        ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
1308        if (ret < 0) {
1309            return ret;
1310        }
1311    }
1312
1313    /* Set TSS base one page after EPT identity map. */
1314    ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1315    if (ret < 0) {
1316        return ret;
1317    }
1318
1319    /* Tell fw_cfg to notify the BIOS to reserve the range. */
1320    ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1321    if (ret < 0) {
1322        fprintf(stderr, "e820_add_entry() table is full\n");
1323        return ret;
1324    }
1325    qemu_register_reset(kvm_unpoison_all, NULL);
1326
1327    shadow_mem = machine_kvm_shadow_mem(ms);
1328    if (shadow_mem != -1) {
1329        shadow_mem /= 4096;
1330        ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
1331        if (ret < 0) {
1332            return ret;
1333        }
1334    }
1335
1336    if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
1337        object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE) &&
1338        pc_machine_is_smm_enabled(PC_MACHINE(ms))) {
1339        smram_machine_done.notify = register_smram_listener;
1340        qemu_add_machine_init_done_notifier(&smram_machine_done);
1341    }
1342    return 0;
1343}
1344
1345static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1346{
1347    lhs->selector = rhs->selector;
1348    lhs->base = rhs->base;
1349    lhs->limit = rhs->limit;
1350    lhs->type = 3;
1351    lhs->present = 1;
1352    lhs->dpl = 3;
1353    lhs->db = 0;
1354    lhs->s = 1;
1355    lhs->l = 0;
1356    lhs->g = 0;
1357    lhs->avl = 0;
1358    lhs->unusable = 0;
1359}
1360
1361static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
1362{
1363    unsigned flags = rhs->flags;
1364    lhs->selector = rhs->selector;
1365    lhs->base = rhs->base;
1366    lhs->limit = rhs->limit;
1367    lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
1368    lhs->present = (flags & DESC_P_MASK) != 0;
1369    lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
1370    lhs->db = (flags >> DESC_B_SHIFT) & 1;
1371    lhs->s = (flags & DESC_S_MASK) != 0;
1372    lhs->l = (flags >> DESC_L_SHIFT) & 1;
1373    lhs->g = (flags & DESC_G_MASK) != 0;
1374    lhs->avl = (flags & DESC_AVL_MASK) != 0;
1375    lhs->unusable = !lhs->present;
1376    lhs->padding = 0;
1377}
1378
1379static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
1380{
1381    lhs->selector = rhs->selector;
1382    lhs->base = rhs->base;
1383    lhs->limit = rhs->limit;
1384    lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
1385                 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
1386                 (rhs->dpl << DESC_DPL_SHIFT) |
1387                 (rhs->db << DESC_B_SHIFT) |
1388                 (rhs->s * DESC_S_MASK) |
1389                 (rhs->l << DESC_L_SHIFT) |
1390                 (rhs->g * DESC_G_MASK) |
1391                 (rhs->avl * DESC_AVL_MASK);
1392}
1393
1394static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
1395{
1396    if (set) {
1397        *kvm_reg = *qemu_reg;
1398    } else {
1399        *qemu_reg = *kvm_reg;
1400    }
1401}
1402
1403static int kvm_getput_regs(X86CPU *cpu, int set)
1404{
1405    CPUX86State *env = &cpu->env;
1406    struct kvm_regs regs;
1407    int ret = 0;
1408
1409    if (!set) {
1410        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1411        if (ret < 0) {
1412            return ret;
1413        }
1414    }
1415
1416    kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
1417    kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
1418    kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
1419    kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
1420    kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
1421    kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
1422    kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
1423    kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
1424#ifdef TARGET_X86_64
1425    kvm_getput_reg(&regs.r8, &env->regs[8], set);
1426    kvm_getput_reg(&regs.r9, &env->regs[9], set);
1427    kvm_getput_reg(&regs.r10, &env->regs[10], set);
1428    kvm_getput_reg(&regs.r11, &env->regs[11], set);
1429    kvm_getput_reg(&regs.r12, &env->regs[12], set);
1430    kvm_getput_reg(&regs.r13, &env->regs[13], set);
1431    kvm_getput_reg(&regs.r14, &env->regs[14], set);
1432    kvm_getput_reg(&regs.r15, &env->regs[15], set);
1433#endif
1434
1435    kvm_getput_reg(&regs.rflags, &env->eflags, set);
1436    kvm_getput_reg(&regs.rip, &env->eip, set);
1437
1438    if (set) {
1439        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1440    }
1441
1442    return ret;
1443}
1444
1445static int kvm_put_fpu(X86CPU *cpu)
1446{
1447    CPUX86State *env = &cpu->env;
1448    struct kvm_fpu fpu;
1449    int i;
1450
1451    memset(&fpu, 0, sizeof fpu);
1452    fpu.fsw = env->fpus & ~(7 << 11);
1453    fpu.fsw |= (env->fpstt & 7) << 11;
1454    fpu.fcw = env->fpuc;
1455    fpu.last_opcode = env->fpop;
1456    fpu.last_ip = env->fpip;
1457    fpu.last_dp = env->fpdp;
1458    for (i = 0; i < 8; ++i) {
1459        fpu.ftwx |= (!env->fptags[i]) << i;
1460    }
1461    memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1462    for (i = 0; i < CPU_NB_REGS; i++) {
1463        stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
1464        stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1465    }
1466    fpu.mxcsr = env->mxcsr;
1467
1468    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
1469}
1470
1471#define XSAVE_FCW_FSW     0
1472#define XSAVE_FTW_FOP     1
1473#define XSAVE_CWD_RIP     2
1474#define XSAVE_CWD_RDP     4
1475#define XSAVE_MXCSR       6
1476#define XSAVE_ST_SPACE    8
1477#define XSAVE_XMM_SPACE   40
1478#define XSAVE_XSTATE_BV   128
1479#define XSAVE_YMMH_SPACE  144
1480#define XSAVE_BNDREGS     240
1481#define XSAVE_BNDCSR      256
1482#define XSAVE_OPMASK      272
1483#define XSAVE_ZMM_Hi256   288
1484#define XSAVE_Hi16_ZMM    416
1485#define XSAVE_PKRU        672
1486
1487#define XSAVE_BYTE_OFFSET(word_offset) \
1488    ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))
1489
1490#define ASSERT_OFFSET(word_offset, field) \
1491    QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
1492                      offsetof(X86XSaveArea, field))
1493
1494ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
1495ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
1496ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
1497ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
1498ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
1499ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
1500ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
1501ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
1502ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
1503ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
1504ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
1505ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
1506ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
1507ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
1508ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
1509
1510static int kvm_put_xsave(X86CPU *cpu)
1511{
1512    CPUX86State *env = &cpu->env;
1513    X86XSaveArea *xsave = env->kvm_xsave_buf;
1514
1515    if (!has_xsave) {
1516        return kvm_put_fpu(cpu);
1517    }
1518    x86_cpu_xsave_all_areas(cpu, xsave);
1519
1520    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1521}
1522
1523static int kvm_put_xcrs(X86CPU *cpu)
1524{
1525    CPUX86State *env = &cpu->env;
1526    struct kvm_xcrs xcrs = {};
1527
1528    if (!has_xcrs) {
1529        return 0;
1530    }
1531
1532    xcrs.nr_xcrs = 1;
1533    xcrs.flags = 0;
1534    xcrs.xcrs[0].xcr = 0;
1535    xcrs.xcrs[0].value = env->xcr0;
1536    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1537}
1538
1539static int kvm_put_sregs(X86CPU *cpu)
1540{
1541    CPUX86State *env = &cpu->env;
1542    struct kvm_sregs sregs;
1543
1544    memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
1545    if (env->interrupt_injected >= 0) {
1546        sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
1547                (uint64_t)1 << (env->interrupt_injected % 64);
1548    }
1549
1550    if ((env->eflags & VM_MASK)) {
1551        set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1552        set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1553        set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1554        set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1555        set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1556        set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1557    } else {
1558        set_seg(&sregs.cs, &env->segs[R_CS]);
1559        set_seg(&sregs.ds, &env->segs[R_DS]);
1560        set_seg(&sregs.es, &env->segs[R_ES]);
1561        set_seg(&sregs.fs, &env->segs[R_FS]);
1562        set_seg(&sregs.gs, &env->segs[R_GS]);
1563        set_seg(&sregs.ss, &env->segs[R_SS]);
1564    }
1565
1566    set_seg(&sregs.tr, &env->tr);
1567    set_seg(&sregs.ldt, &env->ldt);
1568
1569    sregs.idt.limit = env->idt.limit;
1570    sregs.idt.base = env->idt.base;
1571    memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1572    sregs.gdt.limit = env->gdt.limit;
1573    sregs.gdt.base = env->gdt.base;
1574    memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1575
1576    sregs.cr0 = env->cr[0];
1577    sregs.cr2 = env->cr[2];
1578    sregs.cr3 = env->cr[3];
1579    sregs.cr4 = env->cr[4];
1580
1581    sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
1582    sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
1583
1584    sregs.efer = env->efer;
1585
1586    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1587}
1588
1589static void kvm_msr_buf_reset(X86CPU *cpu)
1590{
1591    memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
1592}
1593
1594static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
1595{
1596    struct kvm_msrs *msrs = cpu->kvm_msr_buf;
1597    void *limit = ((void *)msrs) + MSR_BUF_SIZE;
1598    struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
1599
1600    assert((void *)(entry + 1) <= limit);
1601
1602    entry->index = index;
1603    entry->reserved = 0;
1604    entry->data = value;
1605    msrs->nmsrs++;
1606}
1607
1608static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
1609{
1610    kvm_msr_buf_reset(cpu);
1611    kvm_msr_entry_add(cpu, index, value);
1612
1613    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1614}
1615
1616void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
1617{
1618    int ret;
1619
1620    ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
1621    assert(ret == 1);
1622}
1623
1624static int kvm_put_tscdeadline_msr(X86CPU *cpu)
1625{
1626    CPUX86State *env = &cpu->env;
1627    int ret;
1628
1629    if (!has_msr_tsc_deadline) {
1630        return 0;
1631    }
1632
1633    ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1634    if (ret < 0) {
1635        return ret;
1636    }
1637
1638    assert(ret == 1);
1639    return 0;
1640}
1641
1642/*
1643 * Provide a separate write service for the feature control MSR in order to
1644 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
1645 * before writing any other state because forcibly leaving nested mode
1646 * invalidates the VCPU state.
1647 */
1648static int kvm_put_msr_feature_control(X86CPU *cpu)
1649{
1650    int ret;
1651
1652    if (!has_msr_feature_control) {
1653        return 0;
1654    }
1655
1656    ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
1657                          cpu->env.msr_ia32_feature_control);
1658    if (ret < 0) {
1659        return ret;
1660    }
1661
1662    assert(ret == 1);
1663    return 0;
1664}
1665
1666static int kvm_put_msrs(X86CPU *cpu, int level)
1667{
1668    CPUX86State *env = &cpu->env;
1669    int i;
1670    int ret;
1671
1672    kvm_msr_buf_reset(cpu);
1673
1674    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1675    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1676    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1677    kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1678    if (has_msr_star) {
1679        kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1680    }
1681    if (has_msr_hsave_pa) {
1682        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1683    }
1684    if (has_msr_tsc_aux) {
1685        kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1686    }
1687    if (has_msr_tsc_adjust) {
1688        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1689    }
1690    if (has_msr_misc_enable) {
1691        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
1692                          env->msr_ia32_misc_enable);
1693    }
1694    if (has_msr_smbase) {
1695        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1696    }
1697    if (has_msr_smi_count) {
1698        kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
1699    }
1700    if (has_msr_bndcfgs) {
1701        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1702    }
1703    if (has_msr_xss) {
1704        kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1705    }
1706    if (has_msr_spec_ctrl) {
1707        kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
1708    }
1709#ifdef TARGET_X86_64
1710    if (lm_capable_kernel) {
1711        kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
1712        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
1713        kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
1714        kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1715    }
1716#endif
1717
1718    /*
1719     * The following MSRs have side effects on the guest or are too heavy
1720     * for normal writeback. Limit them to reset or full state updates.
1721     */
1722    if (level >= KVM_PUT_RESET_STATE) {
1723        kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
1724        kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
1725        kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1726        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
1727            kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1728        }
1729        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
1730            kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
1731        }
1732        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
1733            kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1734        }
1735        if (has_architectural_pmu_version > 0) {
1736            if (has_architectural_pmu_version > 1) {
1737                /* Stop the counter.  */
1738                kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
1739                kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
1740            }
1741
1742            /* Set the counter values.  */
1743            for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
1744                kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
1745                                  env->msr_fixed_counters[i]);
1746            }
1747            for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
1748                kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
1749                                  env->msr_gp_counters[i]);
1750                kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
1751                                  env->msr_gp_evtsel[i]);
1752            }
1753            if (has_architectural_pmu_version > 1) {
1754                kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
1755                                  env->msr_global_status);
1756                kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
1757                                  env->msr_global_ovf_ctrl);
1758
1759                /* Now start the PMU.  */
1760                kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
1761                                  env->msr_fixed_ctr_ctrl);
1762                kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
1763                                  env->msr_global_ctrl);
1764            }
1765        }
1766        /*
1767         * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
1768         * only sync them to KVM on the first cpu
1769         */
1770        if (current_cpu == first_cpu) {
1771            if (has_msr_hv_hypercall) {
1772                kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1773                                  env->msr_hv_guest_os_id);
1774                kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1775                                  env->msr_hv_hypercall);
1776            }
1777            if (cpu->hyperv_time) {
1778                kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
1779                                  env->msr_hv_tsc);
1780            }
1781        }
1782        if (cpu->hyperv_vapic) {
1783            kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1784                              env->msr_hv_vapic);
1785        }
1786        if (has_msr_hv_crash) {
1787            int j;
1788
1789            for (j = 0; j < HV_CRASH_PARAMS; j++)
1790                kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1791                                  env->msr_hv_crash_params[j]);
1792
1793            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
1794        }
1795        if (has_msr_hv_runtime) {
1796            kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1797        }
1798        if (cpu->hyperv_synic) {
1799            int j;
1800
1801            kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
1802
1803            kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1804                              env->msr_hv_synic_control);
1805            kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1806                              env->msr_hv_synic_evt_page);
1807            kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1808                              env->msr_hv_synic_msg_page);
1809
1810            for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1811                kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1812                                  env->msr_hv_synic_sint[j]);
1813            }
1814        }
1815        if (has_msr_hv_stimer) {
1816            int j;
1817
1818            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1819                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1820                                env->msr_hv_stimer_config[j]);
1821            }
1822
1823            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1824                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1825                                env->msr_hv_stimer_count[j]);
1826            }
1827        }
1828        if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
1829            uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
1830
1831            kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
1832            kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
1833            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
1834            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
1835            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
1836            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
1837            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
1838            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
1839            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
1840            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
1841            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
1842            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1843            for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1844                /* The CPU GPs if we write to a bit above the physical limit of
1845                 * the host CPU (and KVM emulates that)
1846                 */
1847                uint64_t mask = env->mtrr_var[i].mask;
1848                mask &= phys_mask;
1849
1850                kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
1851                                  env->mtrr_var[i].base);
1852                kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
1853            }
1854        }
1855        if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
1856            int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
1857                                                    0x14, 1, R_EAX) & 0x7;
1858
1859            kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
1860                            env->msr_rtit_ctrl);
1861            kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
1862                            env->msr_rtit_status);
1863            kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
1864                            env->msr_rtit_output_base);
1865            kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
1866                            env->msr_rtit_output_mask);
1867            kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
1868                            env->msr_rtit_cr3_match);
1869            for (i = 0; i < addr_num; i++) {
1870                kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
1871                            env->msr_rtit_addrs[i]);
1872            }
1873        }
1874
1875        /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
1876         *       kvm_put_msr_feature_control. */
1877    }
1878    if (env->mcg_cap) {
1879        int i;
1880
1881        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
1882        kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1883        if (has_msr_mcg_ext_ctl) {
1884            kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
1885        }
1886        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1887            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1888        }
1889    }
1890
1891    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1892    if (ret < 0) {
1893        return ret;
1894    }
1895
1896    if (ret < cpu->kvm_msr_buf->nmsrs) {
1897        struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
1898        error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
1899                     (uint32_t)e->index, (uint64_t)e->data);
1900    }
1901
1902    assert(ret == cpu->kvm_msr_buf->nmsrs);
1903    return 0;
1904}
1905
1906
1907static int kvm_get_fpu(X86CPU *cpu)
1908{
1909    CPUX86State *env = &cpu->env;
1910    struct kvm_fpu fpu;
1911    int i, ret;
1912
1913    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1914    if (ret < 0) {
1915        return ret;
1916    }
1917
1918    env->fpstt = (fpu.fsw >> 11) & 7;
1919    env->fpus = fpu.fsw;
1920    env->fpuc = fpu.fcw;
1921    env->fpop = fpu.last_opcode;
1922    env->fpip = fpu.last_ip;
1923    env->fpdp = fpu.last_dp;
1924    for (i = 0; i < 8; ++i) {
1925        env->fptags[i] = !((fpu.ftwx >> i) & 1);
1926    }
1927    memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1928    for (i = 0; i < CPU_NB_REGS; i++) {
1929        env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
1930        env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1931    }
1932    env->mxcsr = fpu.mxcsr;
1933
1934    return 0;
1935}
1936
1937static int kvm_get_xsave(X86CPU *cpu)
1938{
1939    CPUX86State *env = &cpu->env;
1940    X86XSaveArea *xsave = env->kvm_xsave_buf;
1941    int ret;
1942
1943    if (!has_xsave) {
1944        return kvm_get_fpu(cpu);
1945    }
1946
1947    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1948    if (ret < 0) {
1949        return ret;
1950    }
1951    x86_cpu_xrstor_all_areas(cpu, xsave);
1952
1953    return 0;
1954}
1955
1956static int kvm_get_xcrs(X86CPU *cpu)
1957{
1958    CPUX86State *env = &cpu->env;
1959    int i, ret;
1960    struct kvm_xcrs xcrs;
1961
1962    if (!has_xcrs) {
1963        return 0;
1964    }
1965
1966    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1967    if (ret < 0) {
1968        return ret;
1969    }
1970
1971    for (i = 0; i < xcrs.nr_xcrs; i++) {
1972        /* Only support xcr0 now */
1973        if (xcrs.xcrs[i].xcr == 0) {
1974            env->xcr0 = xcrs.xcrs[i].value;
1975            break;
1976        }
1977    }
1978    return 0;
1979}
1980
1981static int kvm_get_sregs(X86CPU *cpu)
1982{
1983    CPUX86State *env = &cpu->env;
1984    struct kvm_sregs sregs;
1985    int bit, i, ret;
1986
1987    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1988    if (ret < 0) {
1989        return ret;
1990    }
1991
1992    /* There can only be one pending IRQ set in the bitmap at a time, so try
1993       to find it and save its number instead (-1 for none). */
1994    env->interrupt_injected = -1;
1995    for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1996        if (sregs.interrupt_bitmap[i]) {
1997            bit = ctz64(sregs.interrupt_bitmap[i]);
1998            env->interrupt_injected = i * 64 + bit;
1999            break;
2000        }
2001    }
2002
2003    get_seg(&env->segs[R_CS], &sregs.cs);
2004    get_seg(&env->segs[R_DS], &sregs.ds);
2005    get_seg(&env->segs[R_ES], &sregs.es);
2006    get_seg(&env->segs[R_FS], &sregs.fs);
2007    get_seg(&env->segs[R_GS], &sregs.gs);
2008    get_seg(&env->segs[R_SS], &sregs.ss);
2009
2010    get_seg(&env->tr, &sregs.tr);
2011    get_seg(&env->ldt, &sregs.ldt);
2012
2013    env->idt.limit = sregs.idt.limit;
2014    env->idt.base = sregs.idt.base;
2015    env->gdt.limit = sregs.gdt.limit;
2016    env->gdt.base = sregs.gdt.base;
2017
2018    env->cr[0] = sregs.cr0;
2019    env->cr[2] = sregs.cr2;
2020    env->cr[3] = sregs.cr3;
2021    env->cr[4] = sregs.cr4;
2022
2023    env->efer = sregs.efer;
2024
2025    /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
2026    x86_update_hflags(env);
2027
2028    return 0;
2029}
2030
2031static int kvm_get_msrs(X86CPU *cpu)
2032{
2033    CPUX86State *env = &cpu->env;
2034    struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
2035    int ret, i;
2036    uint64_t mtrr_top_bits;
2037
2038    kvm_msr_buf_reset(cpu);
2039
2040    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
2041    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
2042    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
2043    kvm_msr_entry_add(cpu, MSR_PAT, 0);
2044    if (has_msr_star) {
2045        kvm_msr_entry_add(cpu, MSR_STAR, 0);
2046    }
2047    if (has_msr_hsave_pa) {
2048        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
2049    }
2050    if (has_msr_tsc_aux) {
2051        kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
2052    }
2053    if (has_msr_tsc_adjust) {
2054        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
2055    }
2056    if (has_msr_tsc_deadline) {
2057        kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
2058    }
2059    if (has_msr_misc_enable) {
2060        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
2061    }
2062    if (has_msr_smbase) {
2063        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
2064    }
2065    if (has_msr_smi_count) {
2066        kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
2067    }
2068    if (has_msr_feature_control) {
2069        kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
2070    }
2071    if (has_msr_bndcfgs) {
2072        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
2073    }
2074    if (has_msr_xss) {
2075        kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
2076    }
2077    if (has_msr_spec_ctrl) {
2078        kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
2079    }
2080
2081
2082    if (!env->tsc_valid) {
2083        kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
2084        env->tsc_valid = !runstate_is_running();
2085    }
2086
2087#ifdef TARGET_X86_64
2088    if (lm_capable_kernel) {
2089        kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
2090        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
2091        kvm_msr_entry_add(cpu, MSR_FMASK, 0);
2092        kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
2093    }
2094#endif
2095    kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
2096    kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
2097    if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2098        kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
2099    }
2100    if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2101        kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
2102    }
2103    if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2104        kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
2105    }
2106    if (has_architectural_pmu_version > 0) {
2107        if (has_architectural_pmu_version > 1) {
2108            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2109            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2110            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
2111            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
2112        }
2113        for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2114            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
2115        }
2116        for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2117            kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
2118            kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
2119        }
2120    }
2121
2122    if (env->mcg_cap) {
2123        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
2124        kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2125        if (has_msr_mcg_ext_ctl) {
2126            kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
2127        }
2128        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2129            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2130        }
2131    }
2132
2133    if (has_msr_hv_hypercall) {
2134        kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
2135        kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2136    }
2137    if (cpu->hyperv_vapic) {
2138        kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2139    }
2140    if (cpu->hyperv_time) {
2141        kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2142    }
2143    if (has_msr_hv_crash) {
2144        int j;
2145
2146        for (j = 0; j < HV_CRASH_PARAMS; j++) {
2147            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2148        }
2149    }
2150    if (has_msr_hv_runtime) {
2151        kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2152    }
2153    if (cpu->hyperv_synic) {
2154        uint32_t msr;
2155
2156        kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
2157        kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
2158        kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2159        for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2160            kvm_msr_entry_add(cpu, msr, 0);
2161        }
2162    }
2163    if (has_msr_hv_stimer) {
2164        uint32_t msr;
2165
2166        for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
2167             msr++) {
2168            kvm_msr_entry_add(cpu, msr, 0);
2169        }
2170    }
2171    if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2172        kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
2173        kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
2174        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
2175        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
2176        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
2177        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
2178        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
2179        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
2180        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
2181        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
2182        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
2183        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2184        for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2185            kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
2186            kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2187        }
2188    }
2189
2190    if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2191        int addr_num =
2192            kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
2193
2194        kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
2195        kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
2196        kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
2197        kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
2198        kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
2199        for (i = 0; i < addr_num; i++) {
2200            kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
2201        }
2202    }
2203
2204    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2205    if (ret < 0) {
2206        return ret;
2207    }
2208
2209    if (ret < cpu->kvm_msr_buf->nmsrs) {
2210        struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2211        error_report("error: failed to get MSR 0x%" PRIx32,
2212                     (uint32_t)e->index);
2213    }
2214
2215    assert(ret == cpu->kvm_msr_buf->nmsrs);
2216    /*
2217     * MTRR masks: Each mask consists of 5 parts
2218     * a  10..0: must be zero
2219     * b  11   : valid bit
2220     * c n-1.12: actual mask bits
2221     * d  51..n: reserved must be zero
2222     * e  63.52: reserved must be zero
2223     *
2224     * 'n' is the number of physical bits supported by the CPU and is
2225     * apparently always <= 52.   We know our 'n' but don't know what
2226     * the destinations 'n' is; it might be smaller, in which case
2227     * it masks (c) on loading. It might be larger, in which case
2228     * we fill 'd' so that d..c is consistent irrespetive of the 'n'
2229     * we're migrating to.
2230     */
2231
2232    if (cpu->fill_mtrr_mask) {
2233        QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);
2234        assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);
2235        mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);
2236    } else {
2237        mtrr_top_bits = 0;
2238    }
2239
2240    for (i = 0; i < ret; i++) {
2241        uint32_t index = msrs[i].index;
2242        switch (index) {
2243        case MSR_IA32_SYSENTER_CS:
2244            env->sysenter_cs = msrs[i].data;
2245            break;
2246        case MSR_IA32_SYSENTER_ESP:
2247            env->sysenter_esp = msrs[i].data;
2248            break;
2249        case MSR_IA32_SYSENTER_EIP:
2250            env->sysenter_eip = msrs[i].data;
2251            break;
2252        case MSR_PAT:
2253            env->pat = msrs[i].data;
2254            break;
2255        case MSR_STAR:
2256            env->star = msrs[i].data;
2257            break;
2258#ifdef TARGET_X86_64
2259        case MSR_CSTAR:
2260            env->cstar = msrs[i].data;
2261            break;
2262        case MSR_KERNELGSBASE:
2263            env->kernelgsbase = msrs[i].data;
2264            break;
2265        case MSR_FMASK:
2266            env->fmask = msrs[i].data;
2267            break;
2268        case MSR_LSTAR:
2269            env->lstar = msrs[i].data;
2270            break;
2271#endif
2272        case MSR_IA32_TSC:
2273            env->tsc = msrs[i].data;
2274            break;
2275        case MSR_TSC_AUX:
2276            env->tsc_aux = msrs[i].data;
2277            break;
2278        case MSR_TSC_ADJUST:
2279            env->tsc_adjust = msrs[i].data;
2280            break;
2281        case MSR_IA32_TSCDEADLINE:
2282            env->tsc_deadline = msrs[i].data;
2283            break;
2284        case MSR_VM_HSAVE_PA:
2285            env->vm_hsave = msrs[i].data;
2286            break;
2287        case MSR_KVM_SYSTEM_TIME:
2288            env->system_time_msr = msrs[i].data;
2289            break;
2290        case MSR_KVM_WALL_CLOCK:
2291            env->wall_clock_msr = msrs[i].data;
2292            break;
2293        case MSR_MCG_STATUS:
2294            env->mcg_status = msrs[i].data;
2295            break;
2296        case MSR_MCG_CTL:
2297            env->mcg_ctl = msrs[i].data;
2298            break;
2299        case MSR_MCG_EXT_CTL:
2300            env->mcg_ext_ctl = msrs[i].data;
2301            break;
2302        case MSR_IA32_MISC_ENABLE:
2303            env->msr_ia32_misc_enable = msrs[i].data;
2304            break;
2305        case MSR_IA32_SMBASE:
2306            env->smbase = msrs[i].data;
2307            break;
2308        case MSR_SMI_COUNT:
2309            env->msr_smi_count = msrs[i].data;
2310            break;
2311        case MSR_IA32_FEATURE_CONTROL:
2312            env->msr_ia32_feature_control = msrs[i].data;
2313            break;
2314        case MSR_IA32_BNDCFGS:
2315            env->msr_bndcfgs = msrs[i].data;
2316            break;
2317        case MSR_IA32_XSS:
2318            env->xss = msrs[i].data;
2319            break;
2320        default:
2321            if (msrs[i].index >= MSR_MC0_CTL &&
2322                msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
2323                env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
2324            }
2325            break;
2326        case MSR_KVM_ASYNC_PF_EN:
2327            env->async_pf_en_msr = msrs[i].data;
2328            break;
2329        case MSR_KVM_PV_EOI_EN:
2330            env->pv_eoi_en_msr = msrs[i].data;
2331            break;
2332        case MSR_KVM_STEAL_TIME:
2333            env->steal_time_msr = msrs[i].data;
2334            break;
2335        case MSR_CORE_PERF_FIXED_CTR_CTRL:
2336            env->msr_fixed_ctr_ctrl = msrs[i].data;
2337            break;
2338        case MSR_CORE_PERF_GLOBAL_CTRL:
2339            env->msr_global_ctrl = msrs[i].data;
2340            break;
2341        case MSR_CORE_PERF_GLOBAL_STATUS:
2342            env->msr_global_status = msrs[i].data;
2343            break;
2344        case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
2345            env->msr_global_ovf_ctrl = msrs[i].data;
2346            break;
2347        case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
2348            env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
2349            break;
2350        case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
2351            env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
2352            break;
2353        case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
2354            env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
2355            break;
2356        case HV_X64_MSR_HYPERCALL:
2357            env->msr_hv_hypercall = msrs[i].data;
2358            break;
2359        case HV_X64_MSR_GUEST_OS_ID:
2360            env->msr_hv_guest_os_id = msrs[i].data;
2361            break;
2362        case HV_X64_MSR_APIC_ASSIST_PAGE:
2363            env->msr_hv_vapic = msrs[i].data;
2364            break;
2365        case HV_X64_MSR_REFERENCE_TSC:
2366            env->msr_hv_tsc = msrs[i].data;
2367            break;
2368        case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
2369            env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
2370            break;
2371        case HV_X64_MSR_VP_RUNTIME:
2372            env->msr_hv_runtime = msrs[i].data;
2373            break;
2374        case HV_X64_MSR_SCONTROL:
2375            env->msr_hv_synic_control = msrs[i].data;
2376            break;
2377        case HV_X64_MSR_SIEFP:
2378            env->msr_hv_synic_evt_page = msrs[i].data;
2379            break;
2380        case HV_X64_MSR_SIMP:
2381            env->msr_hv_synic_msg_page = msrs[i].data;
2382            break;
2383        case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
2384            env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2385            break;
2386        case HV_X64_MSR_STIMER0_CONFIG:
2387        case HV_X64_MSR_STIMER1_CONFIG:
2388        case HV_X64_MSR_STIMER2_CONFIG:
2389        case HV_X64_MSR_STIMER3_CONFIG:
2390            env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
2391                                msrs[i].data;
2392            break;
2393        case HV_X64_MSR_STIMER0_COUNT:
2394        case HV_X64_MSR_STIMER1_COUNT:
2395        case HV_X64_MSR_STIMER2_COUNT:
2396        case HV_X64_MSR_STIMER3_COUNT:
2397            env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
2398                                msrs[i].data;
2399            break;
2400        case MSR_MTRRdefType:
2401            env->mtrr_deftype = msrs[i].data;
2402            break;
2403        case MSR_MTRRfix64K_00000:
2404            env->mtrr_fixed[0] = msrs[i].data;
2405            break;
2406        case MSR_MTRRfix16K_80000:
2407            env->mtrr_fixed[1] = msrs[i].data;
2408            break;
2409        case MSR_MTRRfix16K_A0000:
2410            env->mtrr_fixed[2] = msrs[i].data;
2411            break;
2412        case MSR_MTRRfix4K_C0000:
2413            env->mtrr_fixed[3] = msrs[i].data;
2414            break;
2415        case MSR_MTRRfix4K_C8000:
2416            env->mtrr_fixed[4] = msrs[i].data;
2417            break;
2418        case MSR_MTRRfix4K_D0000:
2419            env->mtrr_fixed[5] = msrs[i].data;
2420            break;
2421        case MSR_MTRRfix4K_D8000:
2422            env->mtrr_fixed[6] = msrs[i].data;
2423            break;
2424        case MSR_MTRRfix4K_E0000:
2425            env->mtrr_fixed[7] = msrs[i].data;
2426            break;
2427        case MSR_MTRRfix4K_E8000:
2428            env->mtrr_fixed[8] = msrs[i].data;
2429            break;
2430        case MSR_MTRRfix4K_F0000:
2431            env->mtrr_fixed[9] = msrs[i].data;
2432            break;
2433        case MSR_MTRRfix4K_F8000:
2434            env->mtrr_fixed[10] = msrs[i].data;
2435            break;
2436        case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
2437            if (index & 1) {
2438                env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |
2439                                                               mtrr_top_bits;
2440            } else {
2441                env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
2442            }
2443            break;
2444        case MSR_IA32_SPEC_CTRL:
2445            env->spec_ctrl = msrs[i].data;
2446            break;
2447        case MSR_IA32_RTIT_CTL:
2448            env->msr_rtit_ctrl = msrs[i].data;
2449            break;
2450        case MSR_IA32_RTIT_STATUS:
2451            env->msr_rtit_status = msrs[i].data;
2452            break;
2453        case MSR_IA32_RTIT_OUTPUT_BASE:
2454            env->msr_rtit_output_base = msrs[i].data;
2455            break;
2456        case MSR_IA32_RTIT_OUTPUT_MASK:
2457            env->msr_rtit_output_mask = msrs[i].data;
2458            break;
2459        case MSR_IA32_RTIT_CR3_MATCH:
2460            env->msr_rtit_cr3_match = msrs[i].data;
2461            break;
2462        case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2463            env->msr_rtit_addrs[index - MSR_IA32_RTIT_ADDR0_A] = msrs[i].data;
2464            break;
2465        }
2466    }
2467
2468    return 0;
2469}
2470
2471static int kvm_put_mp_state(X86CPU *cpu)
2472{
2473    struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2474
2475    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2476}
2477
2478static int kvm_get_mp_state(X86CPU *cpu)
2479{
2480    CPUState *cs = CPU(cpu);
2481    CPUX86State *env = &cpu->env;
2482    struct kvm_mp_state mp_state;
2483    int ret;
2484
2485    ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2486    if (ret < 0) {
2487        return ret;
2488    }
2489    env->mp_state = mp_state.mp_state;
2490    if (kvm_irqchip_in_kernel()) {
2491        cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2492    }
2493    return 0;
2494}
2495
2496static int kvm_get_apic(X86CPU *cpu)
2497{
2498    DeviceState *apic = cpu->apic_state;
2499    struct kvm_lapic_state kapic;
2500    int ret;
2501
2502    if (apic && kvm_irqchip_in_kernel()) {
2503        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2504        if (ret < 0) {
2505            return ret;
2506        }
2507
2508        kvm_get_apic_state(apic, &kapic);
2509    }
2510    return 0;
2511}
2512
2513static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2514{
2515    CPUState *cs = CPU(cpu);
2516    CPUX86State *env = &cpu->env;
2517    struct kvm_vcpu_events events = {};
2518
2519    if (!kvm_has_vcpu_events()) {
2520        return 0;
2521    }
2522
2523    events.exception.injected = (env->exception_injected >= 0);
2524    events.exception.nr = env->exception_injected;
2525    events.exception.has_error_code = env->has_error_code;
2526    events.exception.error_code = env->error_code;
2527    events.exception.pad = 0;
2528
2529    events.interrupt.injected = (env->interrupt_injected >= 0);
2530    events.interrupt.nr = env->interrupt_injected;
2531    events.interrupt.soft = env->soft_interrupt;
2532
2533    events.nmi.injected = env->nmi_injected;
2534    events.nmi.pending = env->nmi_pending;
2535    events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2536    events.nmi.pad = 0;
2537
2538    events.sipi_vector = env->sipi_vector;
2539    events.flags = 0;
2540
2541    if (has_msr_smbase) {
2542        events.smi.smm = !!(env->hflags & HF_SMM_MASK);
2543        events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
2544        if (kvm_irqchip_in_kernel()) {
2545            /* As soon as these are moved to the kernel, remove them
2546             * from cs->interrupt_request.
2547             */
2548            events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
2549            events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
2550            cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
2551        } else {
2552            /* Keep these in cs->interrupt_request.  */
2553            events.smi.pending = 0;
2554            events.smi.latched_init = 0;
2555        }
2556        /* Stop SMI delivery on old machine types to avoid a reboot
2557         * on an inward migration of an old VM.
2558         */
2559        if (!cpu->kvm_no_smi_migration) {
2560            events.flags |= KVM_VCPUEVENT_VALID_SMM;
2561        }
2562    }
2563
2564    if (level >= KVM_PUT_RESET_STATE) {
2565        events.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
2566        if (env->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
2567            events.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
2568        }
2569    }
2570
2571    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2572}
2573
2574static int kvm_get_vcpu_events(X86CPU *cpu)
2575{
2576    CPUX86State *env = &cpu->env;
2577    struct kvm_vcpu_events events;
2578    int ret;
2579
2580    if (!kvm_has_vcpu_events()) {
2581        return 0;
2582    }
2583
2584    memset(&events, 0, sizeof(events));
2585    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2586    if (ret < 0) {
2587       return ret;
2588    }
2589    env->exception_injected =
2590       events.exception.injected ? events.exception.nr : -1;
2591    env->has_error_code = events.exception.has_error_code;
2592    env->error_code = events.exception.error_code;
2593
2594    env->interrupt_injected =
2595        events.interrupt.injected ? events.interrupt.nr : -1;
2596    env->soft_interrupt = events.interrupt.soft;
2597
2598    env->nmi_injected = events.nmi.injected;
2599    env->nmi_pending = events.nmi.pending;
2600    if (events.nmi.masked) {
2601        env->hflags2 |= HF2_NMI_MASK;
2602    } else {
2603        env->hflags2 &= ~HF2_NMI_MASK;
2604    }
2605
2606    if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
2607        if (events.smi.smm) {
2608            env->hflags |= HF_SMM_MASK;
2609        } else {
2610            env->hflags &= ~HF_SMM_MASK;
2611        }
2612        if (events.smi.pending) {
2613            cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2614        } else {
2615            cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
2616        }
2617        if (events.smi.smm_inside_nmi) {
2618            env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
2619        } else {
2620            env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
2621        }
2622        if (events.smi.latched_init) {
2623            cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2624        } else {
2625            cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
2626        }
2627    }
2628
2629    env->sipi_vector = events.sipi_vector;
2630
2631    return 0;
2632}
2633
2634static int kvm_guest_debug_workarounds(X86CPU *cpu)
2635{
2636    CPUState *cs = CPU(cpu);
2637    CPUX86State *env = &cpu->env;
2638    int ret = 0;
2639    unsigned long reinject_trap = 0;
2640
2641    if (!kvm_has_vcpu_events()) {
2642        if (env->exception_injected == 1) {
2643            reinject_trap = KVM_GUESTDBG_INJECT_DB;
2644        } else if (env->exception_injected == 3) {
2645            reinject_trap = KVM_GUESTDBG_INJECT_BP;
2646        }
2647        env->exception_injected = -1;
2648    }
2649
2650    /*
2651     * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
2652     * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
2653     * by updating the debug state once again if single-stepping is on.
2654     * Another reason to call kvm_update_guest_debug here is a pending debug
2655     * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
2656     * reinject them via SET_GUEST_DEBUG.
2657     */
2658    if (reinject_trap ||
2659        (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2660        ret = kvm_update_guest_debug(cs, reinject_trap);
2661    }
2662    return ret;
2663}
2664
2665static int kvm_put_debugregs(X86CPU *cpu)
2666{
2667    CPUX86State *env = &cpu->env;
2668    struct kvm_debugregs dbgregs;
2669    int i;
2670
2671    if (!kvm_has_debugregs()) {
2672        return 0;
2673    }
2674
2675    for (i = 0; i < 4; i++) {
2676        dbgregs.db[i] = env->dr[i];
2677    }
2678    dbgregs.dr6 = env->dr[6];
2679    dbgregs.dr7 = env->dr[7];
2680    dbgregs.flags = 0;
2681
2682    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2683}
2684
2685static int kvm_get_debugregs(X86CPU *cpu)
2686{
2687    CPUX86State *env = &cpu->env;
2688    struct kvm_debugregs dbgregs;
2689    int i, ret;
2690
2691    if (!kvm_has_debugregs()) {
2692        return 0;
2693    }
2694
2695    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2696    if (ret < 0) {
2697        return ret;
2698    }
2699    for (i = 0; i < 4; i++) {
2700        env->dr[i] = dbgregs.db[i];
2701    }
2702    env->dr[4] = env->dr[6] = dbgregs.dr6;
2703    env->dr[5] = env->dr[7] = dbgregs.dr7;
2704
2705    return 0;
2706}
2707
2708int kvm_arch_put_registers(CPUState *cpu, int level)
2709{
2710    X86CPU *x86_cpu = X86_CPU(cpu);
2711    int ret;
2712
2713    assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2714
2715    if (level >= KVM_PUT_RESET_STATE) {
2716        ret = kvm_put_msr_feature_control(x86_cpu);
2717        if (ret < 0) {
2718            return ret;
2719        }
2720    }
2721
2722    if (level == KVM_PUT_FULL_STATE) {
2723        /* We don't check for kvm_arch_set_tsc_khz() errors here,
2724         * because TSC frequency mismatch shouldn't abort migration,
2725         * unless the user explicitly asked for a more strict TSC
2726         * setting (e.g. using an explicit "tsc-freq" option).
2727         */
2728        kvm_arch_set_tsc_khz(cpu);
2729    }
2730
2731    ret = kvm_getput_regs(x86_cpu, 1);
2732    if (ret < 0) {
2733        return ret;
2734    }
2735    ret = kvm_put_xsave(x86_cpu);
2736    if (ret < 0) {
2737        return ret;
2738    }
2739    ret = kvm_put_xcrs(x86_cpu);
2740    if (ret < 0) {
2741        return ret;
2742    }
2743    ret = kvm_put_sregs(x86_cpu);
2744    if (ret < 0) {
2745        return ret;
2746    }
2747    /* must be before kvm_put_msrs */
2748    ret = kvm_inject_mce_oldstyle(x86_cpu);
2749    if (ret < 0) {
2750        return ret;
2751    }
2752    ret = kvm_put_msrs(x86_cpu, level);
2753    if (ret < 0) {
2754        return ret;
2755    }
2756    ret = kvm_put_vcpu_events(x86_cpu, level);
2757    if (ret < 0) {
2758        return ret;
2759    }
2760    if (level >= KVM_PUT_RESET_STATE) {
2761        ret = kvm_put_mp_state(x86_cpu);
2762        if (ret < 0) {
2763            return ret;
2764        }
2765    }
2766
2767    ret = kvm_put_tscdeadline_msr(x86_cpu);
2768    if (ret < 0) {
2769        return ret;
2770    }
2771    ret = kvm_put_debugregs(x86_cpu);
2772    if (ret < 0) {
2773        return ret;
2774    }
2775    /* must be last */
2776    ret = kvm_guest_debug_workarounds(x86_cpu);
2777    if (ret < 0) {
2778        return ret;
2779    }
2780    return 0;
2781}
2782
2783int kvm_arch_get_registers(CPUState *cs)
2784{
2785    X86CPU *cpu = X86_CPU(cs);
2786    int ret;
2787
2788    assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2789
2790    ret = kvm_get_vcpu_events(cpu);
2791    if (ret < 0) {
2792        goto out;
2793    }
2794    /*
2795     * KVM_GET_MPSTATE can modify CS and RIP, call it before
2796     * KVM_GET_REGS and KVM_GET_SREGS.
2797     */
2798    ret = kvm_get_mp_state(cpu);
2799    if (ret < 0) {
2800        goto out;
2801    }
2802    ret = kvm_getput_regs(cpu, 0);
2803    if (ret < 0) {
2804        goto out;
2805    }
2806    ret = kvm_get_xsave(cpu);
2807    if (ret < 0) {
2808        goto out;
2809    }
2810    ret = kvm_get_xcrs(cpu);
2811    if (ret < 0) {
2812        goto out;
2813    }
2814    ret = kvm_get_sregs(cpu);
2815    if (ret < 0) {
2816        goto out;
2817    }
2818    ret = kvm_get_msrs(cpu);
2819    if (ret < 0) {
2820        goto out;
2821    }
2822    ret = kvm_get_apic(cpu);
2823    if (ret < 0) {
2824        goto out;
2825    }
2826    ret = kvm_get_debugregs(cpu);
2827    if (ret < 0) {
2828        goto out;
2829    }
2830    ret = 0;
2831 out:
2832    cpu_sync_bndcs_hflags(&cpu->env);
2833    return ret;
2834}
2835
2836void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
2837{
2838    X86CPU *x86_cpu = X86_CPU(cpu);
2839    CPUX86State *env = &x86_cpu->env;
2840    int ret;
2841
2842    /* Inject NMI */
2843    if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
2844        if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
2845            qemu_mutex_lock_iothread();
2846            cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
2847            qemu_mutex_unlock_iothread();
2848            DPRINTF("injected NMI\n");
2849            ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
2850            if (ret < 0) {
2851                fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
2852                        strerror(-ret));
2853            }
2854        }
2855        if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
2856            qemu_mutex_lock_iothread();
2857            cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
2858            qemu_mutex_unlock_iothread();
2859            DPRINTF("injected SMI\n");
2860            ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
2861            if (ret < 0) {
2862                fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
2863                        strerror(-ret));
2864            }
2865        }
2866    }
2867
2868    if (!kvm_pic_in_kernel()) {
2869        qemu_mutex_lock_iothread();
2870    }
2871
2872    /* Force the VCPU out of its inner loop to process any INIT requests
2873     * or (for userspace APIC, but it is cheap to combine the checks here)
2874     * pending TPR access reports.
2875     */
2876    if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2877        if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
2878            !(env->hflags & HF_SMM_MASK)) {
2879            cpu->exit_request = 1;
2880        }
2881        if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
2882            cpu->exit_request = 1;
2883        }
2884    }
2885
2886    if (!kvm_pic_in_kernel()) {
2887        /* Try to inject an interrupt if the guest can accept it */
2888        if (run->ready_for_interrupt_injection &&
2889            (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2890            (env->eflags & IF_MASK)) {
2891            int irq;
2892
2893            cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2894            irq = cpu_get_pic_interrupt(env);
2895            if (irq >= 0) {
2896                struct kvm_interrupt intr;
2897
2898                intr.irq = irq;
2899                DPRINTF("injected interrupt %d\n", irq);
2900                ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2901                if (ret < 0) {
2902                    fprintf(stderr,
2903                            "KVM: injection failed, interrupt lost (%s)\n",
2904                            strerror(-ret));
2905                }
2906            }
2907        }
2908
2909        /* If we have an interrupt but the guest is not ready to receive an
2910         * interrupt, request an interrupt window exit.  This will
2911         * cause a return to userspace as soon as the guest is ready to
2912         * receive interrupts. */
2913        if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2914            run->request_interrupt_window = 1;
2915        } else {
2916            run->request_interrupt_window = 0;
2917        }
2918
2919        DPRINTF("setting tpr\n");
2920        run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2921
2922        qemu_mutex_unlock_iothread();
2923    }
2924}
2925
2926MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
2927{
2928    X86CPU *x86_cpu = X86_CPU(cpu);
2929    CPUX86State *env = &x86_cpu->env;
2930
2931    if (run->flags & KVM_RUN_X86_SMM) {
2932        env->hflags |= HF_SMM_MASK;
2933    } else {
2934        env->hflags &= ~HF_SMM_MASK;
2935    }
2936    if (run->if_flag) {
2937        env->eflags |= IF_MASK;
2938    } else {
2939        env->eflags &= ~IF_MASK;
2940    }
2941
2942    /* We need to protect the apic state against concurrent accesses from
2943     * different threads in case the userspace irqchip is used. */
2944    if (!kvm_irqchip_in_kernel()) {
2945        qemu_mutex_lock_iothread();
2946    }
2947    cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
2948    cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2949    if (!kvm_irqchip_in_kernel()) {
2950        qemu_mutex_unlock_iothread();
2951    }
2952    return cpu_get_mem_attrs(env);
2953}
2954
2955int kvm_arch_process_async_events(CPUState *cs)
2956{
2957    X86CPU *cpu = X86_CPU(cs);
2958    CPUX86State *env = &cpu->env;
2959
2960    if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2961        /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
2962        assert(env->mcg_cap);
2963
2964        cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2965
2966        kvm_cpu_synchronize_state(cs);
2967
2968        if (env->exception_injected == EXCP08_DBLE) {
2969            /* this means triple fault */
2970            qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
2971            cs->exit_request = 1;
2972            return 0;
2973        }
2974        env->exception_injected = EXCP12_MCHK;
2975        env->has_error_code = 0;
2976
2977        cs->halted = 0;
2978        if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
2979            env->mp_state = KVM_MP_STATE_RUNNABLE;
2980        }
2981    }
2982
2983    if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
2984        !(env->hflags & HF_SMM_MASK)) {
2985        kvm_cpu_synchronize_state(cs);
2986        do_cpu_init(cpu);
2987    }
2988
2989    if (kvm_irqchip_in_kernel()) {
2990        return 0;
2991    }
2992
2993    if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
2994        cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2995        apic_poll_irq(cpu->apic_state);
2996    }
2997    if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2998         (env->eflags & IF_MASK)) ||
2999        (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3000        cs->halted = 0;
3001    }
3002    if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
3003        kvm_cpu_synchronize_state(cs);
3004        do_cpu_sipi(cpu);
3005    }
3006    if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
3007        cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
3008        kvm_cpu_synchronize_state(cs);
3009        apic_handle_tpr_access_report(cpu->apic_state, env->eip,
3010                                      env->tpr_access_type);
3011    }
3012
3013    return cs->halted;
3014}
3015
3016static int kvm_handle_halt(X86CPU *cpu)
3017{
3018    CPUState *cs = CPU(cpu);
3019    CPUX86State *env = &cpu->env;
3020
3021    if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
3022          (env->eflags & IF_MASK)) &&
3023        !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
3024        cs->halted = 1;
3025        return EXCP_HLT;
3026    }
3027
3028    return 0;
3029}
3030
3031static int kvm_handle_tpr_access(X86CPU *cpu)
3032{
3033    CPUState *cs = CPU(cpu);
3034    struct kvm_run *run = cs->kvm_run;
3035
3036    apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
3037                                  run->tpr_access.is_write ? TPR_ACCESS_WRITE
3038                                                           : TPR_ACCESS_READ);
3039    return 1;
3040}
3041
3042int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3043{
3044    static const uint8_t int3 = 0xcc;
3045
3046    if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
3047        cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
3048        return -EINVAL;
3049    }
3050    return 0;
3051}
3052
3053int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
3054{
3055    uint8_t int3;
3056
3057    if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
3058        cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
3059        return -EINVAL;
3060    }
3061    return 0;
3062}
3063
3064static struct {
3065    target_ulong addr;
3066    int len;
3067    int type;
3068} hw_breakpoint[4];
3069
3070static int nb_hw_breakpoint;
3071
3072static int find_hw_breakpoint(target_ulong addr, int len, int type)
3073{
3074    int n;
3075
3076    for (n = 0; n < nb_hw_breakpoint; n++) {
3077        if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
3078            (hw_breakpoint[n].len == len || len == -1)) {
3079            return n;
3080        }
3081    }
3082    return -1;
3083}
3084
3085int kvm_arch_insert_hw_breakpoint(target_ulong addr,
3086                                  target_ulong len, int type)
3087{
3088    switch (type) {
3089    case GDB_BREAKPOINT_HW:
3090        len = 1;
3091        break;
3092    case GDB_WATCHPOINT_WRITE:
3093    case GDB_WATCHPOINT_ACCESS:
3094        switch (len) {
3095        case 1:
3096            break;
3097        case 2:
3098        case 4:
3099        case 8:
3100            if (addr & (len - 1)) {
3101                return -EINVAL;
3102            }
3103            break;
3104        default:
3105            return -EINVAL;
3106        }
3107        break;
3108    default:
3109        return -ENOSYS;
3110    }
3111
3112    if (nb_hw_breakpoint == 4) {
3113        return -ENOBUFS;
3114    }
3115    if (find_hw_breakpoint(addr, len, type) >= 0) {
3116        return -EEXIST;
3117    }
3118    hw_breakpoint[nb_hw_breakpoint].addr = addr;
3119    hw_breakpoint[nb_hw_breakpoint].len = len;
3120    hw_breakpoint[nb_hw_breakpoint].type = type;
3121    nb_hw_breakpoint++;
3122
3123    return 0;
3124}
3125
3126int kvm_arch_remove_hw_breakpoint(target_ulong addr,
3127                                  target_ulong len, int type)
3128{
3129    int n;
3130
3131    n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
3132    if (n < 0) {
3133        return -ENOENT;
3134    }
3135    nb_hw_breakpoint--;
3136    hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
3137
3138    return 0;
3139}
3140
3141void kvm_arch_remove_all_hw_breakpoints(void)
3142{
3143    nb_hw_breakpoint = 0;
3144}
3145
3146static CPUWatchpoint hw_watchpoint;
3147
3148static int kvm_handle_debug(X86CPU *cpu,
3149                            struct kvm_debug_exit_arch *arch_info)
3150{
3151    CPUState *cs = CPU(cpu);
3152    CPUX86State *env = &cpu->env;
3153    int ret = 0;
3154    int n;
3155
3156    if (arch_info->exception == 1) {
3157        if (arch_info->dr6 & (1 << 14)) {
3158            if (cs->singlestep_enabled) {
3159                ret = EXCP_DEBUG;
3160            }
3161        } else {
3162            for (n = 0; n < 4; n++) {
3163                if (arch_info->dr6 & (1 << n)) {
3164                    switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
3165                    case 0x0:
3166                        ret = EXCP_DEBUG;
3167                        break;
3168                    case 0x1:
3169                        ret = EXCP_DEBUG;
3170                        cs->watchpoint_hit = &hw_watchpoint;
3171                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3172                        hw_watchpoint.flags = BP_MEM_WRITE;
3173                        break;
3174                    case 0x3:
3175                        ret = EXCP_DEBUG;
3176                        cs->watchpoint_hit = &hw_watchpoint;
3177                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;
3178                        hw_watchpoint.flags = BP_MEM_ACCESS;
3179                        break;
3180                    }
3181                }
3182            }
3183        }
3184    } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3185        ret = EXCP_DEBUG;
3186    }
3187    if (ret == 0) {
3188        cpu_synchronize_state(cs);
3189        assert(env->exception_injected == -1);
3190
3191        /* pass to guest */
3192        env->exception_injected = arch_info->exception;
3193        env->has_error_code = 0;
3194    }
3195
3196    return ret;
3197}
3198
3199void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3200{
3201    const uint8_t type_code[] = {
3202        [GDB_BREAKPOINT_HW] = 0x0,
3203        [GDB_WATCHPOINT_WRITE] = 0x1,
3204        [GDB_WATCHPOINT_ACCESS] = 0x3
3205    };
3206    const uint8_t len_code[] = {
3207        [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
3208    };
3209    int n;
3210
3211    if (kvm_sw_breakpoints_active(cpu)) {
3212        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3213    }
3214    if (nb_hw_breakpoint > 0) {
3215        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
3216        dbg->arch.debugreg[7] = 0x0600;
3217        for (n = 0; n < nb_hw_breakpoint; n++) {
3218            dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
3219            dbg->arch.debugreg[7] |= (2 << (n * 2)) |
3220                (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3221                ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3222        }
3223    }
3224}
3225
3226static bool host_supports_vmx(void)
3227{
3228    uint32_t ecx, unused;
3229
3230    host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
3231    return ecx & CPUID_EXT_VMX;
3232}
3233
3234#define VMX_INVALID_GUEST_STATE 0x80000021
3235
3236int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3237{
3238    X86CPU *cpu = X86_CPU(cs);
3239    uint64_t code;
3240    int ret;
3241
3242    switch (run->exit_reason) {
3243    case KVM_EXIT_HLT:
3244        DPRINTF("handle_hlt\n");
3245        qemu_mutex_lock_iothread();
3246        ret = kvm_handle_halt(cpu);
3247        qemu_mutex_unlock_iothread();
3248        break;
3249    case KVM_EXIT_SET_TPR:
3250        ret = 0;
3251        break;
3252    case KVM_EXIT_TPR_ACCESS:
3253        qemu_mutex_lock_iothread();
3254        ret = kvm_handle_tpr_access(cpu);
3255        qemu_mutex_unlock_iothread();
3256        break;
3257    case KVM_EXIT_FAIL_ENTRY:
3258        code = run->fail_entry.hardware_entry_failure_reason;
3259        fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
3260                code);
3261        if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
3262            fprintf(stderr,
3263                    "\nIf you're running a guest on an Intel machine without "
3264                        "unrestricted mode\n"
3265                    "support, the failure can be most likely due to the guest "
3266                        "entering an invalid\n"
3267                    "state for Intel VT. For example, the guest maybe running "
3268                        "in big real mode\n"
3269                    "which is not supported on less recent Intel processors."
3270                        "\n\n");
3271        }
3272        ret = -1;
3273        break;
3274    case KVM_EXIT_EXCEPTION:
3275        fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
3276                run->ex.exception, run->ex.error_code);
3277        ret = -1;
3278        break;
3279    case KVM_EXIT_DEBUG:
3280        DPRINTF("kvm_exit_debug\n");
3281        qemu_mutex_lock_iothread();
3282        ret = kvm_handle_debug(cpu, &run->debug.arch);
3283        qemu_mutex_unlock_iothread();
3284        break;
3285    case KVM_EXIT_HYPERV:
3286        ret = kvm_hv_handle_exit(cpu, &run->hyperv);
3287        break;
3288    case KVM_EXIT_IOAPIC_EOI:
3289        ioapic_eoi_broadcast(run->eoi.vector);
3290        ret = 0;
3291        break;
3292    default:
3293        fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
3294        ret = -1;
3295        break;
3296    }
3297
3298    return ret;
3299}
3300
3301bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3302{
3303    X86CPU *cpu = X86_CPU(cs);
3304    CPUX86State *env = &cpu->env;
3305
3306    kvm_cpu_synchronize_state(cs);
3307    return !(env->cr[0] & CR0_PE_MASK) ||
3308           ((env->segs[R_CS].selector  & 3) != 3);
3309}
3310
3311void kvm_arch_init_irq_routing(KVMState *s)
3312{
3313    if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
3314        /* If kernel can't do irq routing, interrupt source
3315         * override 0->2 cannot be set up as required by HPET.
3316         * So we have to disable it.
3317         */
3318        no_hpet = 1;
3319    }
3320    /* We know at this point that we're using the in-kernel
3321     * irqchip, so we can use irqfds, and on x86 we know
3322     * we can use msi via irqfd and GSI routing.
3323     */
3324    kvm_msi_via_irqfd_allowed = true;
3325    kvm_gsi_routing_allowed = true;
3326
3327    if (kvm_irqchip_is_split()) {
3328        int i;
3329
3330        /* If the ioapic is in QEMU and the lapics are in KVM, reserve
3331           MSI routes for signaling interrupts to the local apics. */
3332        for (i = 0; i < IOAPIC_NUM_PINS; i++) {
3333            if (kvm_irqchip_add_msi_route(s, 0, NULL) < 0) {
3334                error_report("Could not enable split IRQ mode.");
3335                exit(1);
3336            }
3337        }
3338    }
3339}
3340
3341int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
3342{
3343    int ret;
3344    if (machine_kernel_irqchip_split(ms)) {
3345        ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
3346        if (ret) {
3347            error_report("Could not enable split irqchip mode: %s",
3348                         strerror(-ret));
3349            exit(1);
3350        } else {
3351            DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
3352            kvm_split_irqchip = true;
3353            return 1;
3354        }
3355    } else {
3356        return 0;
3357    }
3358}
3359
3360/* Classic KVM device assignment interface. Will remain x86 only. */
3361int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
3362                          uint32_t flags, uint32_t *dev_id)
3363{
3364    struct kvm_assigned_pci_dev dev_data = {
3365        .segnr = dev_addr->domain,
3366        .busnr = dev_addr->bus,
3367        .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
3368        .flags = flags,
3369    };
3370    int ret;
3371
3372    dev_data.assigned_dev_id =
3373        (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
3374
3375    ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
3376    if (ret < 0) {
3377        return ret;
3378    }
3379
3380    *dev_id = dev_data.assigned_dev_id;
3381
3382    return 0;
3383}
3384
3385int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
3386{
3387    struct kvm_assigned_pci_dev dev_data = {
3388        .assigned_dev_id = dev_id,
3389    };
3390
3391    return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
3392}
3393
3394static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
3395                                   uint32_t irq_type, uint32_t guest_irq)
3396{
3397    struct kvm_assigned_irq assigned_irq = {
3398        .assigned_dev_id = dev_id,
3399        .guest_irq = guest_irq,
3400        .flags = irq_type,
3401    };
3402
3403    if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
3404        return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
3405    } else {
3406        return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
3407    }
3408}
3409
3410int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
3411                           uint32_t guest_irq)
3412{
3413    uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
3414        (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
3415
3416    return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
3417}
3418
3419int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
3420{
3421    struct kvm_assigned_pci_dev dev_data = {
3422        .assigned_dev_id = dev_id,
3423        .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
3424    };
3425
3426    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
3427}
3428
3429static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
3430                                     uint32_t type)
3431{
3432    struct kvm_assigned_irq assigned_irq = {
3433        .assigned_dev_id = dev_id,
3434        .flags = type,
3435    };
3436
3437    return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
3438}
3439
3440int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
3441{
3442    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
3443        (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
3444}
3445
3446int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
3447{
3448    return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
3449                                              KVM_DEV_IRQ_GUEST_MSI, virq);
3450}
3451
3452int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
3453{
3454    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
3455                                                KVM_DEV_IRQ_HOST_MSI);
3456}
3457
3458bool kvm_device_msix_supported(KVMState *s)
3459{
3460    /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
3461     * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
3462    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
3463}
3464
3465int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
3466                                 uint32_t nr_vectors)
3467{
3468    struct kvm_assigned_msix_nr msix_nr = {
3469        .assigned_dev_id = dev_id,
3470        .entry_nr = nr_vectors,
3471    };
3472
3473    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
3474}
3475
3476int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
3477                               int virq)
3478{
3479    struct kvm_assigned_msix_entry msix_entry = {
3480        .assigned_dev_id = dev_id,
3481        .gsi = virq,
3482        .entry = vector,
3483    };
3484
3485    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
3486}
3487
3488int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
3489{
3490    return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
3491                                              KVM_DEV_IRQ_GUEST_MSIX, 0);
3492}
3493
3494int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
3495{
3496    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
3497                                                KVM_DEV_IRQ_HOST_MSIX);
3498}
3499
3500int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3501                             uint64_t address, uint32_t data, PCIDevice *dev)
3502{
3503    X86IOMMUState *iommu = x86_iommu_get_default();
3504
3505    if (iommu) {
3506        int ret;
3507        MSIMessage src, dst;
3508        X86IOMMUClass *class = X86_IOMMU_GET_CLASS(iommu);
3509
3510        src.address = route->u.msi.address_hi;
3511        src.address <<= VTD_MSI_ADDR_HI_SHIFT;
3512        src.address |= route->u.msi.address_lo;
3513        src.data = route->u.msi.data;
3514
3515        ret = class->int_remap(iommu, &src, &dst, dev ? \
3516                               pci_requester_id(dev) : \
3517                               X86_IOMMU_SID_INVALID);
3518        if (ret) {
3519            trace_kvm_x86_fixup_msi_error(route->gsi);
3520            return 1;
3521        }
3522
3523        route->u.msi.address_hi = dst.address >> VTD_MSI_ADDR_HI_SHIFT;
3524        route->u.msi.address_lo = dst.address & VTD_MSI_ADDR_LO_MASK;
3525        route->u.msi.data = dst.data;
3526    }
3527
3528    return 0;
3529}
3530
3531typedef struct MSIRouteEntry MSIRouteEntry;
3532
3533struct MSIRouteEntry {
3534    PCIDevice *dev;             /* Device pointer */
3535    int vector;                 /* MSI/MSIX vector index */
3536    int virq;                   /* Virtual IRQ index */
3537    QLIST_ENTRY(MSIRouteEntry) list;
3538};
3539
3540/* List of used GSI routes */
3541static QLIST_HEAD(, MSIRouteEntry) msi_route_list = \
3542    QLIST_HEAD_INITIALIZER(msi_route_list);
3543
3544static void kvm_update_msi_routes_all(void *private, bool global,
3545                                      uint32_t index, uint32_t mask)
3546{
3547    int cnt = 0;
3548    MSIRouteEntry *entry;
3549    MSIMessage msg;
3550    PCIDevice *dev;
3551
3552    /* TODO: explicit route update */
3553    QLIST_FOREACH(entry, &msi_route_list, list) {
3554        cnt++;
3555        dev = entry->dev;
3556        if (!msix_enabled(dev) && !msi_enabled(dev)) {
3557            continue;
3558        }
3559        msg = pci_get_msi_message(dev, entry->vector);
3560        kvm_irqchip_update_msi_route(kvm_state, entry->virq, msg, dev);
3561    }
3562    kvm_irqchip_commit_routes(kvm_state);
3563    trace_kvm_x86_update_msi_routes(cnt);
3564}
3565
3566int kvm_arch_add_msi_route_post(struct kvm_irq_routing_entry *route,
3567                                int vector, PCIDevice *dev)
3568{
3569    static bool notify_list_inited = false;
3570    MSIRouteEntry *entry;
3571
3572    if (!dev) {
3573        /* These are (possibly) IOAPIC routes only used for split
3574         * kernel irqchip mode, while what we are housekeeping are
3575         * PCI devices only. */
3576        return 0;
3577    }
3578
3579    entry = g_new0(MSIRouteEntry, 1);
3580    entry->dev = dev;
3581    entry->vector = vector;
3582    entry->virq = route->gsi;
3583    QLIST_INSERT_HEAD(&msi_route_list, entry, list);
3584
3585    trace_kvm_x86_add_msi_route(route->gsi);
3586
3587    if (!notify_list_inited) {
3588        /* For the first time we do add route, add ourselves into
3589         * IOMMU's IEC notify list if needed. */
3590        X86IOMMUState *iommu = x86_iommu_get_default();
3591        if (iommu) {
3592            x86_iommu_iec_register_notifier(iommu,
3593                                            kvm_update_msi_routes_all,
3594                                            NULL);
3595        }
3596        notify_list_inited = true;
3597    }
3598    return 0;
3599}
3600
3601int kvm_arch_release_virq_post(int virq)
3602{
3603    MSIRouteEntry *entry, *next;
3604    QLIST_FOREACH_SAFE(entry, &msi_route_list, list, next) {
3605        if (entry->virq == virq) {
3606            trace_kvm_x86_remove_msi_route(virq);
3607            QLIST_REMOVE(entry, list);
3608            g_free(entry);
3609            break;
3610        }
3611    }
3612    return 0;
3613}
3614
3615int kvm_arch_msi_data_to_gsi(uint32_t data)
3616{
3617    abort();
3618}
3619