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