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