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 <sys/types.h>
  16#include <sys/ioctl.h>
  17#include <sys/mman.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 "sysemu/sysemu.h"
  25#include "sysemu/kvm.h"
  26#include "kvm_i386.h"
  27#include "cpu.h"
  28#include "exec/gdbstub.h"
  29#include "qemu/host-utils.h"
  30#include "qemu/config-file.h"
  31#include "hw/i386/pc.h"
  32#include "hw/i386/apic.h"
  33#include "exec/ioport.h"
  34#include "hyperv.h"
  35#include "hw/pci/pci.h"
  36
  37//#define DEBUG_KVM
  38
  39#ifdef DEBUG_KVM
  40#define DPRINTF(fmt, ...) \
  41    do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
  42#else
  43#define DPRINTF(fmt, ...) \
  44    do { } while (0)
  45#endif
  46
  47#define MSR_KVM_WALL_CLOCK  0x11
  48#define MSR_KVM_SYSTEM_TIME 0x12
  49
  50#ifndef BUS_MCEERR_AR
  51#define BUS_MCEERR_AR 4
  52#endif
  53#ifndef BUS_MCEERR_AO
  54#define BUS_MCEERR_AO 5
  55#endif
  56
  57const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
  58    KVM_CAP_INFO(SET_TSS_ADDR),
  59    KVM_CAP_INFO(EXT_CPUID),
  60    KVM_CAP_INFO(MP_STATE),
  61    KVM_CAP_LAST_INFO
  62};
  63
  64static bool has_msr_star;
  65static bool has_msr_hsave_pa;
  66static bool has_msr_tsc_adjust;
  67static bool has_msr_tsc_deadline;
  68static bool has_msr_async_pf_en;
  69static bool has_msr_pv_eoi_en;
  70static bool has_msr_misc_enable;
  71static bool has_msr_kvm_steal_time;
  72static int lm_capable_kernel;
  73
  74bool kvm_allows_irq0_override(void)
  75{
  76    return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
  77}
  78
  79static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
  80{
  81    struct kvm_cpuid2 *cpuid;
  82    int r, size;
  83
  84    size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
  85    cpuid = (struct kvm_cpuid2 *)g_malloc0(size);
  86    cpuid->nent = max;
  87    r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
  88    if (r == 0 && cpuid->nent >= max) {
  89        r = -E2BIG;
  90    }
  91    if (r < 0) {
  92        if (r == -E2BIG) {
  93            g_free(cpuid);
  94            return NULL;
  95        } else {
  96            fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
  97                    strerror(-r));
  98            exit(1);
  99        }
 100    }
 101    return cpuid;
 102}
 103
 104/* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
 105 * for all entries.
 106 */
 107static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
 108{
 109    struct kvm_cpuid2 *cpuid;
 110    int max = 1;
 111    while ((cpuid = try_get_cpuid(s, max)) == NULL) {
 112        max *= 2;
 113    }
 114    return cpuid;
 115}
 116
 117struct kvm_para_features {
 118    int cap;
 119    int feature;
 120} para_features[] = {
 121    { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
 122    { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
 123    { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
 124    { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
 125    { -1, -1 }
 126};
 127
 128static int get_para_features(KVMState *s)
 129{
 130    int i, features = 0;
 131
 132    for (i = 0; i < ARRAY_SIZE(para_features) - 1; i++) {
 133        if (kvm_check_extension(s, para_features[i].cap)) {
 134            features |= (1 << para_features[i].feature);
 135        }
 136    }
 137
 138    return features;
 139}
 140
 141
 142/* Returns the value for a specific register on the cpuid entry
 143 */
 144static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
 145{
 146    uint32_t ret = 0;
 147    switch (reg) {
 148    case R_EAX:
 149        ret = entry->eax;
 150        break;
 151    case R_EBX:
 152        ret = entry->ebx;
 153        break;
 154    case R_ECX:
 155        ret = entry->ecx;
 156        break;
 157    case R_EDX:
 158        ret = entry->edx;
 159        break;
 160    }
 161    return ret;
 162}
 163
 164/* Find matching entry for function/index on kvm_cpuid2 struct
 165 */
 166static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
 167                                                 uint32_t function,
 168                                                 uint32_t index)
 169{
 170    int i;
 171    for (i = 0; i < cpuid->nent; ++i) {
 172        if (cpuid->entries[i].function == function &&
 173            cpuid->entries[i].index == index) {
 174            return &cpuid->entries[i];
 175        }
 176    }
 177    /* not found: */
 178    return NULL;
 179}
 180
 181uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
 182                                      uint32_t index, int reg)
 183{
 184    struct kvm_cpuid2 *cpuid;
 185    uint32_t ret = 0;
 186    uint32_t cpuid_1_edx;
 187    bool found = false;
 188
 189    cpuid = get_supported_cpuid(s);
 190
 191    struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
 192    if (entry) {
 193        found = true;
 194        ret = cpuid_entry_get_reg(entry, reg);
 195    }
 196
 197    /* Fixups for the data returned by KVM, below */
 198
 199    if (function == 1 && reg == R_EDX) {
 200        /* KVM before 2.6.30 misreports the following features */
 201        ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
 202    } else if (function == 1 && reg == R_ECX) {
 203        /* We can set the hypervisor flag, even if KVM does not return it on
 204         * GET_SUPPORTED_CPUID
 205         */
 206        ret |= CPUID_EXT_HYPERVISOR;
 207        /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
 208         * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
 209         * and the irqchip is in the kernel.
 210         */
 211        if (kvm_irqchip_in_kernel() &&
 212                kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
 213            ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
 214        }
 215
 216        /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
 217         * without the in-kernel irqchip
 218         */
 219        if (!kvm_irqchip_in_kernel()) {
 220            ret &= ~CPUID_EXT_X2APIC;
 221        }
 222    } else if (function == 0x80000001 && reg == R_EDX) {
 223        /* On Intel, kvm returns cpuid according to the Intel spec,
 224         * so add missing bits according to the AMD spec:
 225         */
 226        cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
 227        ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
 228    }
 229
 230    g_free(cpuid);
 231
 232    /* fallback for older kernels */
 233    if ((function == KVM_CPUID_FEATURES) && !found) {
 234        ret = get_para_features(s);
 235    }
 236
 237    return ret;
 238}
 239
 240typedef struct HWPoisonPage {
 241    ram_addr_t ram_addr;
 242    QLIST_ENTRY(HWPoisonPage) list;
 243} HWPoisonPage;
 244
 245static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
 246    QLIST_HEAD_INITIALIZER(hwpoison_page_list);
 247
 248static void kvm_unpoison_all(void *param)
 249{
 250    HWPoisonPage *page, *next_page;
 251
 252    QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
 253        QLIST_REMOVE(page, list);
 254        qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
 255        g_free(page);
 256    }
 257}
 258
 259static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
 260{
 261    HWPoisonPage *page;
 262
 263    QLIST_FOREACH(page, &hwpoison_page_list, list) {
 264        if (page->ram_addr == ram_addr) {
 265            return;
 266        }
 267    }
 268    page = g_malloc(sizeof(HWPoisonPage));
 269    page->ram_addr = ram_addr;
 270    QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
 271}
 272
 273static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
 274                                     int *max_banks)
 275{
 276    int r;
 277
 278    r = kvm_check_extension(s, KVM_CAP_MCE);
 279    if (r > 0) {
 280        *max_banks = r;
 281        return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
 282    }
 283    return -ENOSYS;
 284}
 285
 286static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
 287{
 288    CPUX86State *env = &cpu->env;
 289    uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
 290                      MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
 291    uint64_t mcg_status = MCG_STATUS_MCIP;
 292
 293    if (code == BUS_MCEERR_AR) {
 294        status |= MCI_STATUS_AR | 0x134;
 295        mcg_status |= MCG_STATUS_EIPV;
 296    } else {
 297        status |= 0xc0;
 298        mcg_status |= MCG_STATUS_RIPV;
 299    }
 300    cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
 301                       (MCM_ADDR_PHYS << 6) | 0xc,
 302                       cpu_x86_support_mca_broadcast(env) ?
 303                       MCE_INJECT_BROADCAST : 0);
 304}
 305
 306static void hardware_memory_error(void)
 307{
 308    fprintf(stderr, "Hardware memory error!\n");
 309    exit(1);
 310}
 311
 312int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
 313{
 314    X86CPU *cpu = X86_CPU(c);
 315    CPUX86State *env = &cpu->env;
 316    ram_addr_t ram_addr;
 317    hwaddr paddr;
 318
 319    if ((env->mcg_cap & MCG_SER_P) && addr
 320        && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
 321        if (qemu_ram_addr_from_host(addr, &ram_addr) ||
 322            !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
 323            fprintf(stderr, "Hardware memory error for memory used by "
 324                    "QEMU itself instead of guest system!\n");
 325            /* Hope we are lucky for AO MCE */
 326            if (code == BUS_MCEERR_AO) {
 327                return 0;
 328            } else {
 329                hardware_memory_error();
 330            }
 331        }
 332        kvm_hwpoison_page_add(ram_addr);
 333        kvm_mce_inject(cpu, paddr, code);
 334    } else {
 335        if (code == BUS_MCEERR_AO) {
 336            return 0;
 337        } else if (code == BUS_MCEERR_AR) {
 338            hardware_memory_error();
 339        } else {
 340            return 1;
 341        }
 342    }
 343    return 0;
 344}
 345
 346int kvm_arch_on_sigbus(int code, void *addr)
 347{
 348    if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
 349        ram_addr_t ram_addr;
 350        hwaddr paddr;
 351
 352        /* Hope we are lucky for AO MCE */
 353        if (qemu_ram_addr_from_host(addr, &ram_addr) ||
 354            !kvm_physical_memory_addr_from_host(CPU(first_cpu)->kvm_state,
 355                                                addr, &paddr)) {
 356            fprintf(stderr, "Hardware memory error for memory used by "
 357                    "QEMU itself instead of guest system!: %p\n", addr);
 358            return 0;
 359        }
 360        kvm_hwpoison_page_add(ram_addr);
 361        kvm_mce_inject(x86_env_get_cpu(first_cpu), paddr, code);
 362    } else {
 363        if (code == BUS_MCEERR_AO) {
 364            return 0;
 365        } else if (code == BUS_MCEERR_AR) {
 366            hardware_memory_error();
 367        } else {
 368            return 1;
 369        }
 370    }
 371    return 0;
 372}
 373
 374static int kvm_inject_mce_oldstyle(X86CPU *cpu)
 375{
 376    CPUX86State *env = &cpu->env;
 377
 378    if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
 379        unsigned int bank, bank_num = env->mcg_cap & 0xff;
 380        struct kvm_x86_mce mce;
 381
 382        env->exception_injected = -1;
 383
 384        /*
 385         * There must be at least one bank in use if an MCE is pending.
 386         * Find it and use its values for the event injection.
 387         */
 388        for (bank = 0; bank < bank_num; bank++) {
 389            if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
 390                break;
 391            }
 392        }
 393        assert(bank < bank_num);
 394
 395        mce.bank = bank;
 396        mce.status = env->mce_banks[bank * 4 + 1];
 397        mce.mcg_status = env->mcg_status;
 398        mce.addr = env->mce_banks[bank * 4 + 2];
 399        mce.misc = env->mce_banks[bank * 4 + 3];
 400
 401        return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
 402    }
 403    return 0;
 404}
 405
 406static void cpu_update_state(void *opaque, int running, RunState state)
 407{
 408    CPUX86State *env = opaque;
 409
 410    if (running) {
 411        env->tsc_valid = false;
 412    }
 413}
 414
 415unsigned long kvm_arch_vcpu_id(CPUState *cs)
 416{
 417    X86CPU *cpu = X86_CPU(cs);
 418    return cpu->env.cpuid_apic_id;
 419}
 420
 421#define KVM_MAX_CPUID_ENTRIES  100
 422
 423int kvm_arch_init_vcpu(CPUState *cs)
 424{
 425    struct {
 426        struct kvm_cpuid2 cpuid;
 427        struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
 428    } QEMU_PACKED cpuid_data;
 429    X86CPU *cpu = X86_CPU(cs);
 430    CPUX86State *env = &cpu->env;
 431    uint32_t limit, i, j, cpuid_i;
 432    uint32_t unused;
 433    struct kvm_cpuid_entry2 *c;
 434    uint32_t signature[3];
 435    int r;
 436
 437    cpuid_i = 0;
 438
 439    /* Paravirtualization CPUIDs */
 440    c = &cpuid_data.entries[cpuid_i++];
 441    memset(c, 0, sizeof(*c));
 442    c->function = KVM_CPUID_SIGNATURE;
 443    if (!hyperv_enabled()) {
 444        memcpy(signature, "KVMKVMKVM\0\0\0", 12);
 445        c->eax = 0;
 446    } else {
 447        memcpy(signature, "Microsoft Hv", 12);
 448        c->eax = HYPERV_CPUID_MIN;
 449    }
 450    c->ebx = signature[0];
 451    c->ecx = signature[1];
 452    c->edx = signature[2];
 453
 454    c = &cpuid_data.entries[cpuid_i++];
 455    memset(c, 0, sizeof(*c));
 456    c->function = KVM_CPUID_FEATURES;
 457    c->eax = env->features[FEAT_KVM];
 458
 459    if (hyperv_enabled()) {
 460        memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
 461        c->eax = signature[0];
 462
 463        c = &cpuid_data.entries[cpuid_i++];
 464        memset(c, 0, sizeof(*c));
 465        c->function = HYPERV_CPUID_VERSION;
 466        c->eax = 0x00001bbc;
 467        c->ebx = 0x00060001;
 468
 469        c = &cpuid_data.entries[cpuid_i++];
 470        memset(c, 0, sizeof(*c));
 471        c->function = HYPERV_CPUID_FEATURES;
 472        if (hyperv_relaxed_timing_enabled()) {
 473            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
 474        }
 475        if (hyperv_vapic_recommended()) {
 476            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
 477            c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
 478        }
 479
 480        c = &cpuid_data.entries[cpuid_i++];
 481        memset(c, 0, sizeof(*c));
 482        c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
 483        if (hyperv_relaxed_timing_enabled()) {
 484            c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
 485        }
 486        if (hyperv_vapic_recommended()) {
 487            c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
 488        }
 489        c->ebx = hyperv_get_spinlock_retries();
 490
 491        c = &cpuid_data.entries[cpuid_i++];
 492        memset(c, 0, sizeof(*c));
 493        c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
 494        c->eax = 0x40;
 495        c->ebx = 0x40;
 496
 497        c = &cpuid_data.entries[cpuid_i++];
 498        memset(c, 0, sizeof(*c));
 499        c->function = KVM_CPUID_SIGNATURE_NEXT;
 500        memcpy(signature, "KVMKVMKVM\0\0\0", 12);
 501        c->eax = 0;
 502        c->ebx = signature[0];
 503        c->ecx = signature[1];
 504        c->edx = signature[2];
 505    }
 506
 507    has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
 508
 509    has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
 510
 511    has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
 512
 513    cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
 514
 515    for (i = 0; i <= limit; i++) {
 516        if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 517            fprintf(stderr, "unsupported level value: 0x%x\n", limit);
 518            abort();
 519        }
 520        c = &cpuid_data.entries[cpuid_i++];
 521
 522        switch (i) {
 523        case 2: {
 524            /* Keep reading function 2 till all the input is received */
 525            int times;
 526
 527            c->function = i;
 528            c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
 529                       KVM_CPUID_FLAG_STATE_READ_NEXT;
 530            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 531            times = c->eax & 0xff;
 532
 533            for (j = 1; j < times; ++j) {
 534                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 535                    fprintf(stderr, "cpuid_data is full, no space for "
 536                            "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
 537                    abort();
 538                }
 539                c = &cpuid_data.entries[cpuid_i++];
 540                c->function = i;
 541                c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
 542                cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 543            }
 544            break;
 545        }
 546        case 4:
 547        case 0xb:
 548        case 0xd:
 549            for (j = 0; ; j++) {
 550                if (i == 0xd && j == 64) {
 551                    break;
 552                }
 553                c->function = i;
 554                c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
 555                c->index = j;
 556                cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
 557
 558                if (i == 4 && c->eax == 0) {
 559                    break;
 560                }
 561                if (i == 0xb && !(c->ecx & 0xff00)) {
 562                    break;
 563                }
 564                if (i == 0xd && c->eax == 0) {
 565                    continue;
 566                }
 567                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 568                    fprintf(stderr, "cpuid_data is full, no space for "
 569                            "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
 570                    abort();
 571                }
 572                c = &cpuid_data.entries[cpuid_i++];
 573            }
 574            break;
 575        default:
 576            c->function = i;
 577            c->flags = 0;
 578            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 579            break;
 580        }
 581    }
 582    cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
 583
 584    for (i = 0x80000000; i <= limit; i++) {
 585        if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 586            fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
 587            abort();
 588        }
 589        c = &cpuid_data.entries[cpuid_i++];
 590
 591        c->function = i;
 592        c->flags = 0;
 593        cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 594    }
 595
 596    /* Call Centaur's CPUID instructions they are supported. */
 597    if (env->cpuid_xlevel2 > 0) {
 598        cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
 599
 600        for (i = 0xC0000000; i <= limit; i++) {
 601            if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
 602                fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
 603                abort();
 604            }
 605            c = &cpuid_data.entries[cpuid_i++];
 606
 607            c->function = i;
 608            c->flags = 0;
 609            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
 610        }
 611    }
 612
 613    cpuid_data.cpuid.nent = cpuid_i;
 614
 615    if (((env->cpuid_version >> 8)&0xF) >= 6
 616        && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
 617           (CPUID_MCE | CPUID_MCA)
 618        && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
 619        uint64_t mcg_cap;
 620        int banks;
 621        int ret;
 622
 623        ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
 624        if (ret < 0) {
 625            fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
 626            return ret;
 627        }
 628
 629        if (banks > MCE_BANKS_DEF) {
 630            banks = MCE_BANKS_DEF;
 631        }
 632        mcg_cap &= MCE_CAP_DEF;
 633        mcg_cap |= banks;
 634        ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &mcg_cap);
 635        if (ret < 0) {
 636            fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
 637            return ret;
 638        }
 639
 640        env->mcg_cap = mcg_cap;
 641    }
 642
 643    qemu_add_vm_change_state_handler(cpu_update_state, env);
 644
 645    cpuid_data.cpuid.padding = 0;
 646    r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
 647    if (r) {
 648        return r;
 649    }
 650
 651    r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL);
 652    if (r && env->tsc_khz) {
 653        r = kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz);
 654        if (r < 0) {
 655            fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");
 656            return r;
 657        }
 658    }
 659
 660    if (kvm_has_xsave()) {
 661        env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
 662    }
 663
 664    return 0;
 665}
 666
 667void kvm_arch_reset_vcpu(CPUState *cs)
 668{
 669    X86CPU *cpu = X86_CPU(cs);
 670    CPUX86State *env = &cpu->env;
 671
 672    env->exception_injected = -1;
 673    env->interrupt_injected = -1;
 674    env->xcr0 = 1;
 675    if (kvm_irqchip_in_kernel()) {
 676        env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
 677                                          KVM_MP_STATE_UNINITIALIZED;
 678    } else {
 679        env->mp_state = KVM_MP_STATE_RUNNABLE;
 680    }
 681}
 682
 683static int kvm_get_supported_msrs(KVMState *s)
 684{
 685    static int kvm_supported_msrs;
 686    int ret = 0;
 687
 688    /* first time */
 689    if (kvm_supported_msrs == 0) {
 690        struct kvm_msr_list msr_list, *kvm_msr_list;
 691
 692        kvm_supported_msrs = -1;
 693
 694        /* Obtain MSR list from KVM.  These are the MSRs that we must
 695         * save/restore */
 696        msr_list.nmsrs = 0;
 697        ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
 698        if (ret < 0 && ret != -E2BIG) {
 699            return ret;
 700        }
 701        /* Old kernel modules had a bug and could write beyond the provided
 702           memory. Allocate at least a safe amount of 1K. */
 703        kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
 704                                              msr_list.nmsrs *
 705                                              sizeof(msr_list.indices[0])));
 706
 707        kvm_msr_list->nmsrs = msr_list.nmsrs;
 708        ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
 709        if (ret >= 0) {
 710            int i;
 711
 712            for (i = 0; i < kvm_msr_list->nmsrs; i++) {
 713                if (kvm_msr_list->indices[i] == MSR_STAR) {
 714                    has_msr_star = true;
 715                    continue;
 716                }
 717                if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
 718                    has_msr_hsave_pa = true;
 719                    continue;
 720                }
 721                if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
 722                    has_msr_tsc_adjust = true;
 723                    continue;
 724                }
 725                if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
 726                    has_msr_tsc_deadline = true;
 727                    continue;
 728                }
 729                if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
 730                    has_msr_misc_enable = true;
 731                    continue;
 732                }
 733            }
 734        }
 735
 736        g_free(kvm_msr_list);
 737    }
 738
 739    return ret;
 740}
 741
 742int kvm_arch_init(KVMState *s)
 743{
 744    QemuOptsList *list = qemu_find_opts("machine");
 745    uint64_t identity_base = 0xfffbc000;
 746    uint64_t shadow_mem;
 747    int ret;
 748    struct utsname utsname;
 749
 750    ret = kvm_get_supported_msrs(s);
 751    if (ret < 0) {
 752        return ret;
 753    }
 754
 755    uname(&utsname);
 756    lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
 757
 758    /*
 759     * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
 760     * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
 761     * Since these must be part of guest physical memory, we need to allocate
 762     * them, both by setting their start addresses in the kernel and by
 763     * creating a corresponding e820 entry. We need 4 pages before the BIOS.
 764     *
 765     * Older KVM versions may not support setting the identity map base. In
 766     * that case we need to stick with the default, i.e. a 256K maximum BIOS
 767     * size.
 768     */
 769    if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
 770        /* Allows up to 16M BIOSes. */
 771        identity_base = 0xfeffc000;
 772
 773        ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
 774        if (ret < 0) {
 775            return ret;
 776        }
 777    }
 778
 779    /* Set TSS base one page after EPT identity map. */
 780    ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
 781    if (ret < 0) {
 782        return ret;
 783    }
 784
 785    /* Tell fw_cfg to notify the BIOS to reserve the range. */
 786    ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
 787    if (ret < 0) {
 788        fprintf(stderr, "e820_add_entry() table is full\n");
 789        return ret;
 790    }
 791    qemu_register_reset(kvm_unpoison_all, NULL);
 792
 793    if (!QTAILQ_EMPTY(&list->head)) {
 794        shadow_mem = qemu_opt_get_size(QTAILQ_FIRST(&list->head),
 795                                       "kvm_shadow_mem", -1);
 796        if (shadow_mem != -1) {
 797            shadow_mem /= 4096;
 798            ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
 799            if (ret < 0) {
 800                return ret;
 801            }
 802        }
 803    }
 804    return 0;
 805}
 806
 807static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
 808{
 809    lhs->selector = rhs->selector;
 810    lhs->base = rhs->base;
 811    lhs->limit = rhs->limit;
 812    lhs->type = 3;
 813    lhs->present = 1;
 814    lhs->dpl = 3;
 815    lhs->db = 0;
 816    lhs->s = 1;
 817    lhs->l = 0;
 818    lhs->g = 0;
 819    lhs->avl = 0;
 820    lhs->unusable = 0;
 821}
 822
 823static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
 824{
 825    unsigned flags = rhs->flags;
 826    lhs->selector = rhs->selector;
 827    lhs->base = rhs->base;
 828    lhs->limit = rhs->limit;
 829    lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
 830    lhs->present = (flags & DESC_P_MASK) != 0;
 831    lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
 832    lhs->db = (flags >> DESC_B_SHIFT) & 1;
 833    lhs->s = (flags & DESC_S_MASK) != 0;
 834    lhs->l = (flags >> DESC_L_SHIFT) & 1;
 835    lhs->g = (flags & DESC_G_MASK) != 0;
 836    lhs->avl = (flags & DESC_AVL_MASK) != 0;
 837    lhs->unusable = 0;
 838    lhs->padding = 0;
 839}
 840
 841static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
 842{
 843    lhs->selector = rhs->selector;
 844    lhs->base = rhs->base;
 845    lhs->limit = rhs->limit;
 846    lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
 847                 (rhs->present * DESC_P_MASK) |
 848                 (rhs->dpl << DESC_DPL_SHIFT) |
 849                 (rhs->db << DESC_B_SHIFT) |
 850                 (rhs->s * DESC_S_MASK) |
 851                 (rhs->l << DESC_L_SHIFT) |
 852                 (rhs->g * DESC_G_MASK) |
 853                 (rhs->avl * DESC_AVL_MASK);
 854}
 855
 856static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
 857{
 858    if (set) {
 859        *kvm_reg = *qemu_reg;
 860    } else {
 861        *qemu_reg = *kvm_reg;
 862    }
 863}
 864
 865static int kvm_getput_regs(X86CPU *cpu, int set)
 866{
 867    CPUX86State *env = &cpu->env;
 868    struct kvm_regs regs;
 869    int ret = 0;
 870
 871    if (!set) {
 872        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
 873        if (ret < 0) {
 874            return ret;
 875        }
 876    }
 877
 878    kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
 879    kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
 880    kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
 881    kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
 882    kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
 883    kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
 884    kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
 885    kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
 886#ifdef TARGET_X86_64
 887    kvm_getput_reg(&regs.r8, &env->regs[8], set);
 888    kvm_getput_reg(&regs.r9, &env->regs[9], set);
 889    kvm_getput_reg(&regs.r10, &env->regs[10], set);
 890    kvm_getput_reg(&regs.r11, &env->regs[11], set);
 891    kvm_getput_reg(&regs.r12, &env->regs[12], set);
 892    kvm_getput_reg(&regs.r13, &env->regs[13], set);
 893    kvm_getput_reg(&regs.r14, &env->regs[14], set);
 894    kvm_getput_reg(&regs.r15, &env->regs[15], set);
 895#endif
 896
 897    kvm_getput_reg(&regs.rflags, &env->eflags, set);
 898    kvm_getput_reg(&regs.rip, &env->eip, set);
 899
 900    if (set) {
 901        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
 902    }
 903
 904    return ret;
 905}
 906
 907static int kvm_put_fpu(X86CPU *cpu)
 908{
 909    CPUX86State *env = &cpu->env;
 910    struct kvm_fpu fpu;
 911    int i;
 912
 913    memset(&fpu, 0, sizeof fpu);
 914    fpu.fsw = env->fpus & ~(7 << 11);
 915    fpu.fsw |= (env->fpstt & 7) << 11;
 916    fpu.fcw = env->fpuc;
 917    fpu.last_opcode = env->fpop;
 918    fpu.last_ip = env->fpip;
 919    fpu.last_dp = env->fpdp;
 920    for (i = 0; i < 8; ++i) {
 921        fpu.ftwx |= (!env->fptags[i]) << i;
 922    }
 923    memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
 924    memcpy(fpu.xmm, env->xmm_regs, sizeof env->xmm_regs);
 925    fpu.mxcsr = env->mxcsr;
 926
 927    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
 928}
 929
 930#define XSAVE_FCW_FSW     0
 931#define XSAVE_FTW_FOP     1
 932#define XSAVE_CWD_RIP     2
 933#define XSAVE_CWD_RDP     4
 934#define XSAVE_MXCSR       6
 935#define XSAVE_ST_SPACE    8
 936#define XSAVE_XMM_SPACE   40
 937#define XSAVE_XSTATE_BV   128
 938#define XSAVE_YMMH_SPACE  144
 939
 940static int kvm_put_xsave(X86CPU *cpu)
 941{
 942    CPUX86State *env = &cpu->env;
 943    struct kvm_xsave* xsave = env->kvm_xsave_buf;
 944    uint16_t cwd, swd, twd;
 945    int i, r;
 946
 947    if (!kvm_has_xsave()) {
 948        return kvm_put_fpu(cpu);
 949    }
 950
 951    memset(xsave, 0, sizeof(struct kvm_xsave));
 952    twd = 0;
 953    swd = env->fpus & ~(7 << 11);
 954    swd |= (env->fpstt & 7) << 11;
 955    cwd = env->fpuc;
 956    for (i = 0; i < 8; ++i) {
 957        twd |= (!env->fptags[i]) << i;
 958    }
 959    xsave->region[XSAVE_FCW_FSW] = (uint32_t)(swd << 16) + cwd;
 960    xsave->region[XSAVE_FTW_FOP] = (uint32_t)(env->fpop << 16) + twd;
 961    memcpy(&xsave->region[XSAVE_CWD_RIP], &env->fpip, sizeof(env->fpip));
 962    memcpy(&xsave->region[XSAVE_CWD_RDP], &env->fpdp, sizeof(env->fpdp));
 963    memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,
 964            sizeof env->fpregs);
 965    memcpy(&xsave->region[XSAVE_XMM_SPACE], env->xmm_regs,
 966            sizeof env->xmm_regs);
 967    xsave->region[XSAVE_MXCSR] = env->mxcsr;
 968    *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;
 969    memcpy(&xsave->region[XSAVE_YMMH_SPACE], env->ymmh_regs,
 970            sizeof env->ymmh_regs);
 971    r = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
 972    return r;
 973}
 974
 975static int kvm_put_xcrs(X86CPU *cpu)
 976{
 977    CPUX86State *env = &cpu->env;
 978    struct kvm_xcrs xcrs;
 979
 980    if (!kvm_has_xcrs()) {
 981        return 0;
 982    }
 983
 984    xcrs.nr_xcrs = 1;
 985    xcrs.flags = 0;
 986    xcrs.xcrs[0].xcr = 0;
 987    xcrs.xcrs[0].value = env->xcr0;
 988    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
 989}
 990
 991static int kvm_put_sregs(X86CPU *cpu)
 992{
 993    CPUX86State *env = &cpu->env;
 994    struct kvm_sregs sregs;
 995
 996    memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
 997    if (env->interrupt_injected >= 0) {
 998        sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
 999                (uint64_t)1 << (env->interrupt_injected % 64);
1000    }
1001
1002    if ((env->eflags & VM_MASK)) {
1003        set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
1004        set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
1005        set_v8086_seg(&sregs.es, &env->segs[R_ES]);
1006        set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
1007        set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
1008        set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
1009    } else {
1010        set_seg(&sregs.cs, &env->segs[R_CS]);
1011        set_seg(&sregs.ds, &env->segs[R_DS]);
1012        set_seg(&sregs.es, &env->segs[R_ES]);
1013        set_seg(&sregs.fs, &env->segs[R_FS]);
1014        set_seg(&sregs.gs, &env->segs[R_GS]);
1015        set_seg(&sregs.ss, &env->segs[R_SS]);
1016    }
1017
1018    set_seg(&sregs.tr, &env->tr);
1019    set_seg(&sregs.ldt, &env->ldt);
1020
1021    sregs.idt.limit = env->idt.limit;
1022    sregs.idt.base = env->idt.base;
1023    memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
1024    sregs.gdt.limit = env->gdt.limit;
1025    sregs.gdt.base = env->gdt.base;
1026    memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
1027
1028    sregs.cr0 = env->cr[0];
1029    sregs.cr2 = env->cr[2];
1030    sregs.cr3 = env->cr[3];
1031    sregs.cr4 = env->cr[4];
1032
1033    sregs.cr8 = cpu_get_apic_tpr(env->apic_state);
1034    sregs.apic_base = cpu_get_apic_base(env->apic_state);
1035
1036    sregs.efer = env->efer;
1037
1038    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
1039}
1040
1041static void kvm_msr_entry_set(struct kvm_msr_entry *entry,
1042                              uint32_t index, uint64_t value)
1043{
1044    entry->index = index;
1045    entry->data = value;
1046}
1047
1048static int kvm_put_msrs(X86CPU *cpu, int level)
1049{
1050    CPUX86State *env = &cpu->env;
1051    struct {
1052        struct kvm_msrs info;
1053        struct kvm_msr_entry entries[100];
1054    } msr_data;
1055    struct kvm_msr_entry *msrs = msr_data.entries;
1056    int n = 0;
1057
1058    kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_CS, env->sysenter_cs);
1059    kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
1060    kvm_msr_entry_set(&msrs[n++], MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
1061    kvm_msr_entry_set(&msrs[n++], MSR_PAT, env->pat);
1062    if (has_msr_star) {
1063        kvm_msr_entry_set(&msrs[n++], MSR_STAR, env->star);
1064    }
1065    if (has_msr_hsave_pa) {
1066        kvm_msr_entry_set(&msrs[n++], MSR_VM_HSAVE_PA, env->vm_hsave);
1067    }
1068    if (has_msr_tsc_adjust) {
1069        kvm_msr_entry_set(&msrs[n++], MSR_TSC_ADJUST, env->tsc_adjust);
1070    }
1071    if (has_msr_tsc_deadline) {
1072        kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1073    }
1074    if (has_msr_misc_enable) {
1075        kvm_msr_entry_set(&msrs[n++], MSR_IA32_MISC_ENABLE,
1076                          env->msr_ia32_misc_enable);
1077    }
1078#ifdef TARGET_X86_64
1079    if (lm_capable_kernel) {
1080        kvm_msr_entry_set(&msrs[n++], MSR_CSTAR, env->cstar);
1081        kvm_msr_entry_set(&msrs[n++], MSR_KERNELGSBASE, env->kernelgsbase);
1082        kvm_msr_entry_set(&msrs[n++], MSR_FMASK, env->fmask);
1083        kvm_msr_entry_set(&msrs[n++], MSR_LSTAR, env->lstar);
1084    }
1085#endif
1086    if (level == KVM_PUT_FULL_STATE) {
1087        /*
1088         * KVM is yet unable to synchronize TSC values of multiple VCPUs on
1089         * writeback. Until this is fixed, we only write the offset to SMP
1090         * guests after migration, desynchronizing the VCPUs, but avoiding
1091         * huge jump-backs that would occur without any writeback at all.
1092         */
1093        if (smp_cpus == 1 || env->tsc != 0) {
1094            kvm_msr_entry_set(&msrs[n++], MSR_IA32_TSC, env->tsc);
1095        }
1096    }
1097    /*
1098     * The following paravirtual MSRs have side effects on the guest or are
1099     * too heavy for normal writeback. Limit them to reset or full state
1100     * updates.
1101     */
1102    if (level >= KVM_PUT_RESET_STATE) {
1103        kvm_msr_entry_set(&msrs[n++], MSR_KVM_SYSTEM_TIME,
1104                          env->system_time_msr);
1105        kvm_msr_entry_set(&msrs[n++], MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1106        if (has_msr_async_pf_en) {
1107            kvm_msr_entry_set(&msrs[n++], MSR_KVM_ASYNC_PF_EN,
1108                              env->async_pf_en_msr);
1109        }
1110        if (has_msr_pv_eoi_en) {
1111            kvm_msr_entry_set(&msrs[n++], MSR_KVM_PV_EOI_EN,
1112                              env->pv_eoi_en_msr);
1113        }
1114        if (has_msr_kvm_steal_time) {
1115            kvm_msr_entry_set(&msrs[n++], MSR_KVM_STEAL_TIME,
1116                              env->steal_time_msr);
1117        }
1118        if (hyperv_hypercall_available()) {
1119            kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_GUEST_OS_ID, 0);
1120            kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_HYPERCALL, 0);
1121        }
1122        if (hyperv_vapic_recommended()) {
1123            kvm_msr_entry_set(&msrs[n++], HV_X64_MSR_APIC_ASSIST_PAGE, 0);
1124        }
1125    }
1126    if (env->mcg_cap) {
1127        int i;
1128
1129        kvm_msr_entry_set(&msrs[n++], MSR_MCG_STATUS, env->mcg_status);
1130        kvm_msr_entry_set(&msrs[n++], MSR_MCG_CTL, env->mcg_ctl);
1131        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1132            kvm_msr_entry_set(&msrs[n++], MSR_MC0_CTL + i, env->mce_banks[i]);
1133        }
1134    }
1135
1136    msr_data.info.nmsrs = n;
1137
1138    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);
1139
1140}
1141
1142
1143static int kvm_get_fpu(X86CPU *cpu)
1144{
1145    CPUX86State *env = &cpu->env;
1146    struct kvm_fpu fpu;
1147    int i, ret;
1148
1149    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1150    if (ret < 0) {
1151        return ret;
1152    }
1153
1154    env->fpstt = (fpu.fsw >> 11) & 7;
1155    env->fpus = fpu.fsw;
1156    env->fpuc = fpu.fcw;
1157    env->fpop = fpu.last_opcode;
1158    env->fpip = fpu.last_ip;
1159    env->fpdp = fpu.last_dp;
1160    for (i = 0; i < 8; ++i) {
1161        env->fptags[i] = !((fpu.ftwx >> i) & 1);
1162    }
1163    memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1164    memcpy(env->xmm_regs, fpu.xmm, sizeof env->xmm_regs);
1165    env->mxcsr = fpu.mxcsr;
1166
1167    return 0;
1168}
1169
1170static int kvm_get_xsave(X86CPU *cpu)
1171{
1172    CPUX86State *env = &cpu->env;
1173    struct kvm_xsave* xsave = env->kvm_xsave_buf;
1174    int ret, i;
1175    uint16_t cwd, swd, twd;
1176
1177    if (!kvm_has_xsave()) {
1178        return kvm_get_fpu(cpu);
1179    }
1180
1181    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1182    if (ret < 0) {
1183        return ret;
1184    }
1185
1186    cwd = (uint16_t)xsave->region[XSAVE_FCW_FSW];
1187    swd = (uint16_t)(xsave->region[XSAVE_FCW_FSW] >> 16);
1188    twd = (uint16_t)xsave->region[XSAVE_FTW_FOP];
1189    env->fpop = (uint16_t)(xsave->region[XSAVE_FTW_FOP] >> 16);
1190    env->fpstt = (swd >> 11) & 7;
1191    env->fpus = swd;
1192    env->fpuc = cwd;
1193    for (i = 0; i < 8; ++i) {
1194        env->fptags[i] = !((twd >> i) & 1);
1195    }
1196    memcpy(&env->fpip, &xsave->region[XSAVE_CWD_RIP], sizeof(env->fpip));
1197    memcpy(&env->fpdp, &xsave->region[XSAVE_CWD_RDP], sizeof(env->fpdp));
1198    env->mxcsr = xsave->region[XSAVE_MXCSR];
1199    memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],
1200            sizeof env->fpregs);
1201    memcpy(env->xmm_regs, &xsave->region[XSAVE_XMM_SPACE],
1202            sizeof env->xmm_regs);
1203    env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];
1204    memcpy(env->ymmh_regs, &xsave->region[XSAVE_YMMH_SPACE],
1205            sizeof env->ymmh_regs);
1206    return 0;
1207}
1208
1209static int kvm_get_xcrs(X86CPU *cpu)
1210{
1211    CPUX86State *env = &cpu->env;
1212    int i, ret;
1213    struct kvm_xcrs xcrs;
1214
1215    if (!kvm_has_xcrs()) {
1216        return 0;
1217    }
1218
1219    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1220    if (ret < 0) {
1221        return ret;
1222    }
1223
1224    for (i = 0; i < xcrs.nr_xcrs; i++) {
1225        /* Only support xcr0 now */
1226        if (xcrs.xcrs[0].xcr == 0) {
1227            env->xcr0 = xcrs.xcrs[0].value;
1228            break;
1229        }
1230    }
1231    return 0;
1232}
1233
1234static int kvm_get_sregs(X86CPU *cpu)
1235{
1236    CPUX86State *env = &cpu->env;
1237    struct kvm_sregs sregs;
1238    uint32_t hflags;
1239    int bit, i, ret;
1240
1241    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1242    if (ret < 0) {
1243        return ret;
1244    }
1245
1246    /* There can only be one pending IRQ set in the bitmap at a time, so try
1247       to find it and save its number instead (-1 for none). */
1248    env->interrupt_injected = -1;
1249    for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
1250        if (sregs.interrupt_bitmap[i]) {
1251            bit = ctz64(sregs.interrupt_bitmap[i]);
1252            env->interrupt_injected = i * 64 + bit;
1253            break;
1254        }
1255    }
1256
1257    get_seg(&env->segs[R_CS], &sregs.cs);
1258    get_seg(&env->segs[R_DS], &sregs.ds);
1259    get_seg(&env->segs[R_ES], &sregs.es);
1260    get_seg(&env->segs[R_FS], &sregs.fs);
1261    get_seg(&env->segs[R_GS], &sregs.gs);
1262    get_seg(&env->segs[R_SS], &sregs.ss);
1263
1264    get_seg(&env->tr, &sregs.tr);
1265    get_seg(&env->ldt, &sregs.ldt);
1266
1267    env->idt.limit = sregs.idt.limit;
1268    env->idt.base = sregs.idt.base;
1269    env->gdt.limit = sregs.gdt.limit;
1270    env->gdt.base = sregs.gdt.base;
1271
1272    env->cr[0] = sregs.cr0;
1273    env->cr[2] = sregs.cr2;
1274    env->cr[3] = sregs.cr3;
1275    env->cr[4] = sregs.cr4;
1276
1277    env->efer = sregs.efer;
1278
1279    /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
1280
1281#define HFLAG_COPY_MASK \
1282    ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
1283       HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
1284       HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
1285       HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
1286
1287    hflags = (env->segs[R_CS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
1288    hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
1289    hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1290                (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
1291    hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1292    hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<
1293                (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);
1294
1295    if (env->efer & MSR_EFER_LMA) {
1296        hflags |= HF_LMA_MASK;
1297    }
1298
1299    if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
1300        hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
1301    } else {
1302        hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1303                    (DESC_B_SHIFT - HF_CS32_SHIFT);
1304        hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1305                    (DESC_B_SHIFT - HF_SS32_SHIFT);
1306        if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
1307            !(hflags & HF_CS32_MASK)) {
1308            hflags |= HF_ADDSEG_MASK;
1309        } else {
1310            hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
1311                        env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
1312        }
1313    }
1314    env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;
1315
1316    return 0;
1317}
1318
1319static int kvm_get_msrs(X86CPU *cpu)
1320{
1321    CPUX86State *env = &cpu->env;
1322    struct {
1323        struct kvm_msrs info;
1324        struct kvm_msr_entry entries[100];
1325    } msr_data;
1326    struct kvm_msr_entry *msrs = msr_data.entries;
1327    int ret, i, n;
1328
1329    n = 0;
1330    msrs[n++].index = MSR_IA32_SYSENTER_CS;
1331    msrs[n++].index = MSR_IA32_SYSENTER_ESP;
1332    msrs[n++].index = MSR_IA32_SYSENTER_EIP;
1333    msrs[n++].index = MSR_PAT;
1334    if (has_msr_star) {
1335        msrs[n++].index = MSR_STAR;
1336    }
1337    if (has_msr_hsave_pa) {
1338        msrs[n++].index = MSR_VM_HSAVE_PA;
1339    }
1340    if (has_msr_tsc_adjust) {
1341        msrs[n++].index = MSR_TSC_ADJUST;
1342    }
1343    if (has_msr_tsc_deadline) {
1344        msrs[n++].index = MSR_IA32_TSCDEADLINE;
1345    }
1346    if (has_msr_misc_enable) {
1347        msrs[n++].index = MSR_IA32_MISC_ENABLE;
1348    }
1349
1350    if (!env->tsc_valid) {
1351        msrs[n++].index = MSR_IA32_TSC;
1352        env->tsc_valid = !runstate_is_running();
1353    }
1354
1355#ifdef TARGET_X86_64
1356    if (lm_capable_kernel) {
1357        msrs[n++].index = MSR_CSTAR;
1358        msrs[n++].index = MSR_KERNELGSBASE;
1359        msrs[n++].index = MSR_FMASK;
1360        msrs[n++].index = MSR_LSTAR;
1361    }
1362#endif
1363    msrs[n++].index = MSR_KVM_SYSTEM_TIME;
1364    msrs[n++].index = MSR_KVM_WALL_CLOCK;
1365    if (has_msr_async_pf_en) {
1366        msrs[n++].index = MSR_KVM_ASYNC_PF_EN;
1367    }
1368    if (has_msr_pv_eoi_en) {
1369        msrs[n++].index = MSR_KVM_PV_EOI_EN;
1370    }
1371    if (has_msr_kvm_steal_time) {
1372        msrs[n++].index = MSR_KVM_STEAL_TIME;
1373    }
1374
1375    if (env->mcg_cap) {
1376        msrs[n++].index = MSR_MCG_STATUS;
1377        msrs[n++].index = MSR_MCG_CTL;
1378        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1379            msrs[n++].index = MSR_MC0_CTL + i;
1380        }
1381    }
1382
1383    msr_data.info.nmsrs = n;
1384    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
1385    if (ret < 0) {
1386        return ret;
1387    }
1388
1389    for (i = 0; i < ret; i++) {
1390        switch (msrs[i].index) {
1391        case MSR_IA32_SYSENTER_CS:
1392            env->sysenter_cs = msrs[i].data;
1393            break;
1394        case MSR_IA32_SYSENTER_ESP:
1395            env->sysenter_esp = msrs[i].data;
1396            break;
1397        case MSR_IA32_SYSENTER_EIP:
1398            env->sysenter_eip = msrs[i].data;
1399            break;
1400        case MSR_PAT:
1401            env->pat = msrs[i].data;
1402            break;
1403        case MSR_STAR:
1404            env->star = msrs[i].data;
1405            break;
1406#ifdef TARGET_X86_64
1407        case MSR_CSTAR:
1408            env->cstar = msrs[i].data;
1409            break;
1410        case MSR_KERNELGSBASE:
1411            env->kernelgsbase = msrs[i].data;
1412            break;
1413        case MSR_FMASK:
1414            env->fmask = msrs[i].data;
1415            break;
1416        case MSR_LSTAR:
1417            env->lstar = msrs[i].data;
1418            break;
1419#endif
1420        case MSR_IA32_TSC:
1421            env->tsc = msrs[i].data;
1422            break;
1423        case MSR_TSC_ADJUST:
1424            env->tsc_adjust = msrs[i].data;
1425            break;
1426        case MSR_IA32_TSCDEADLINE:
1427            env->tsc_deadline = msrs[i].data;
1428            break;
1429        case MSR_VM_HSAVE_PA:
1430            env->vm_hsave = msrs[i].data;
1431            break;
1432        case MSR_KVM_SYSTEM_TIME:
1433            env->system_time_msr = msrs[i].data;
1434            break;
1435        case MSR_KVM_WALL_CLOCK:
1436            env->wall_clock_msr = msrs[i].data;
1437            break;
1438        case MSR_MCG_STATUS:
1439            env->mcg_status = msrs[i].data;
1440            break;
1441        case MSR_MCG_CTL:
1442            env->mcg_ctl = msrs[i].data;
1443            break;
1444        case MSR_IA32_MISC_ENABLE:
1445            env->msr_ia32_misc_enable = msrs[i].data;
1446            break;
1447        default:
1448            if (msrs[i].index >= MSR_MC0_CTL &&
1449                msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
1450                env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
1451            }
1452            break;
1453        case MSR_KVM_ASYNC_PF_EN:
1454            env->async_pf_en_msr = msrs[i].data;
1455            break;
1456        case MSR_KVM_PV_EOI_EN:
1457            env->pv_eoi_en_msr = msrs[i].data;
1458            break;
1459        case MSR_KVM_STEAL_TIME:
1460            env->steal_time_msr = msrs[i].data;
1461            break;
1462        }
1463    }
1464
1465    return 0;
1466}
1467
1468static int kvm_put_mp_state(X86CPU *cpu)
1469{
1470    struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
1471
1472    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
1473}
1474
1475static int kvm_get_mp_state(X86CPU *cpu)
1476{
1477    CPUState *cs = CPU(cpu);
1478    CPUX86State *env = &cpu->env;
1479    struct kvm_mp_state mp_state;
1480    int ret;
1481
1482    ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
1483    if (ret < 0) {
1484        return ret;
1485    }
1486    env->mp_state = mp_state.mp_state;
1487    if (kvm_irqchip_in_kernel()) {
1488        cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
1489    }
1490    return 0;
1491}
1492
1493static int kvm_get_apic(X86CPU *cpu)
1494{
1495    CPUX86State *env = &cpu->env;
1496    DeviceState *apic = env->apic_state;
1497    struct kvm_lapic_state kapic;
1498    int ret;
1499
1500    if (apic && kvm_irqchip_in_kernel()) {
1501        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
1502        if (ret < 0) {
1503            return ret;
1504        }
1505
1506        kvm_get_apic_state(apic, &kapic);
1507    }
1508    return 0;
1509}
1510
1511static int kvm_put_apic(X86CPU *cpu)
1512{
1513    CPUX86State *env = &cpu->env;
1514    DeviceState *apic = env->apic_state;
1515    struct kvm_lapic_state kapic;
1516
1517    if (apic && kvm_irqchip_in_kernel()) {
1518        kvm_put_apic_state(apic, &kapic);
1519
1520        return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
1521    }
1522    return 0;
1523}
1524
1525static int kvm_put_vcpu_events(X86CPU *cpu, int level)
1526{
1527    CPUX86State *env = &cpu->env;
1528    struct kvm_vcpu_events events;
1529
1530    if (!kvm_has_vcpu_events()) {
1531        return 0;
1532    }
1533
1534    events.exception.injected = (env->exception_injected >= 0);
1535    events.exception.nr = env->exception_injected;
1536    events.exception.has_error_code = env->has_error_code;
1537    events.exception.error_code = env->error_code;
1538    events.exception.pad = 0;
1539
1540    events.interrupt.injected = (env->interrupt_injected >= 0);
1541    events.interrupt.nr = env->interrupt_injected;
1542    events.interrupt.soft = env->soft_interrupt;
1543
1544    events.nmi.injected = env->nmi_injected;
1545    events.nmi.pending = env->nmi_pending;
1546    events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
1547    events.nmi.pad = 0;
1548
1549    events.sipi_vector = env->sipi_vector;
1550
1551    events.flags = 0;
1552    if (level >= KVM_PUT_RESET_STATE) {
1553        events.flags |=
1554            KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
1555    }
1556
1557    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
1558}
1559
1560static int kvm_get_vcpu_events(X86CPU *cpu)
1561{
1562    CPUX86State *env = &cpu->env;
1563    struct kvm_vcpu_events events;
1564    int ret;
1565
1566    if (!kvm_has_vcpu_events()) {
1567        return 0;
1568    }
1569
1570    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
1571    if (ret < 0) {
1572       return ret;
1573    }
1574    env->exception_injected =
1575       events.exception.injected ? events.exception.nr : -1;
1576    env->has_error_code = events.exception.has_error_code;
1577    env->error_code = events.exception.error_code;
1578
1579    env->interrupt_injected =
1580        events.interrupt.injected ? events.interrupt.nr : -1;
1581    env->soft_interrupt = events.interrupt.soft;
1582
1583    env->nmi_injected = events.nmi.injected;
1584    env->nmi_pending = events.nmi.pending;
1585    if (events.nmi.masked) {
1586        env->hflags2 |= HF2_NMI_MASK;
1587    } else {
1588        env->hflags2 &= ~HF2_NMI_MASK;
1589    }
1590
1591    env->sipi_vector = events.sipi_vector;
1592
1593    return 0;
1594}
1595
1596static int kvm_guest_debug_workarounds(X86CPU *cpu)
1597{
1598    CPUX86State *env = &cpu->env;
1599    int ret = 0;
1600    unsigned long reinject_trap = 0;
1601
1602    if (!kvm_has_vcpu_events()) {
1603        if (env->exception_injected == 1) {
1604            reinject_trap = KVM_GUESTDBG_INJECT_DB;
1605        } else if (env->exception_injected == 3) {
1606            reinject_trap = KVM_GUESTDBG_INJECT_BP;
1607        }
1608        env->exception_injected = -1;
1609    }
1610
1611    /*
1612     * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
1613     * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
1614     * by updating the debug state once again if single-stepping is on.
1615     * Another reason to call kvm_update_guest_debug here is a pending debug
1616     * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
1617     * reinject them via SET_GUEST_DEBUG.
1618     */
1619    if (reinject_trap ||
1620        (!kvm_has_robust_singlestep() && env->singlestep_enabled)) {
1621        ret = kvm_update_guest_debug(env, reinject_trap);
1622    }
1623    return ret;
1624}
1625
1626static int kvm_put_debugregs(X86CPU *cpu)
1627{
1628    CPUX86State *env = &cpu->env;
1629    struct kvm_debugregs dbgregs;
1630    int i;
1631
1632    if (!kvm_has_debugregs()) {
1633        return 0;
1634    }
1635
1636    for (i = 0; i < 4; i++) {
1637        dbgregs.db[i] = env->dr[i];
1638    }
1639    dbgregs.dr6 = env->dr[6];
1640    dbgregs.dr7 = env->dr[7];
1641    dbgregs.flags = 0;
1642
1643    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
1644}
1645
1646static int kvm_get_debugregs(X86CPU *cpu)
1647{
1648    CPUX86State *env = &cpu->env;
1649    struct kvm_debugregs dbgregs;
1650    int i, ret;
1651
1652    if (!kvm_has_debugregs()) {
1653        return 0;
1654    }
1655
1656    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
1657    if (ret < 0) {
1658        return ret;
1659    }
1660    for (i = 0; i < 4; i++) {
1661        env->dr[i] = dbgregs.db[i];
1662    }
1663    env->dr[4] = env->dr[6] = dbgregs.dr6;
1664    env->dr[5] = env->dr[7] = dbgregs.dr7;
1665
1666    return 0;
1667}
1668
1669int kvm_arch_put_registers(CPUState *cpu, int level)
1670{
1671    X86CPU *x86_cpu = X86_CPU(cpu);
1672    int ret;
1673
1674    assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
1675
1676    ret = kvm_getput_regs(x86_cpu, 1);
1677    if (ret < 0) {
1678        return ret;
1679    }
1680    ret = kvm_put_xsave(x86_cpu);
1681    if (ret < 0) {
1682        return ret;
1683    }
1684    ret = kvm_put_xcrs(x86_cpu);
1685    if (ret < 0) {
1686        return ret;
1687    }
1688    ret = kvm_put_sregs(x86_cpu);
1689    if (ret < 0) {
1690        return ret;
1691    }
1692    /* must be before kvm_put_msrs */
1693    ret = kvm_inject_mce_oldstyle(x86_cpu);
1694    if (ret < 0) {
1695        return ret;
1696    }
1697    ret = kvm_put_msrs(x86_cpu, level);
1698    if (ret < 0) {
1699        return ret;
1700    }
1701    if (level >= KVM_PUT_RESET_STATE) {
1702        ret = kvm_put_mp_state(x86_cpu);
1703        if (ret < 0) {
1704            return ret;
1705        }
1706        ret = kvm_put_apic(x86_cpu);
1707        if (ret < 0) {
1708            return ret;
1709        }
1710    }
1711    ret = kvm_put_vcpu_events(x86_cpu, level);
1712    if (ret < 0) {
1713        return ret;
1714    }
1715    ret = kvm_put_debugregs(x86_cpu);
1716    if (ret < 0) {
1717        return ret;
1718    }
1719    /* must be last */
1720    ret = kvm_guest_debug_workarounds(x86_cpu);
1721    if (ret < 0) {
1722        return ret;
1723    }
1724    return 0;
1725}
1726
1727int kvm_arch_get_registers(CPUState *cs)
1728{
1729    X86CPU *cpu = X86_CPU(cs);
1730    int ret;
1731
1732    assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
1733
1734    ret = kvm_getput_regs(cpu, 0);
1735    if (ret < 0) {
1736        return ret;
1737    }
1738    ret = kvm_get_xsave(cpu);
1739    if (ret < 0) {
1740        return ret;
1741    }
1742    ret = kvm_get_xcrs(cpu);
1743    if (ret < 0) {
1744        return ret;
1745    }
1746    ret = kvm_get_sregs(cpu);
1747    if (ret < 0) {
1748        return ret;
1749    }
1750    ret = kvm_get_msrs(cpu);
1751    if (ret < 0) {
1752        return ret;
1753    }
1754    ret = kvm_get_mp_state(cpu);
1755    if (ret < 0) {
1756        return ret;
1757    }
1758    ret = kvm_get_apic(cpu);
1759    if (ret < 0) {
1760        return ret;
1761    }
1762    ret = kvm_get_vcpu_events(cpu);
1763    if (ret < 0) {
1764        return ret;
1765    }
1766    ret = kvm_get_debugregs(cpu);
1767    if (ret < 0) {
1768        return ret;
1769    }
1770    return 0;
1771}
1772
1773void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
1774{
1775    X86CPU *x86_cpu = X86_CPU(cpu);
1776    CPUX86State *env = &x86_cpu->env;
1777    int ret;
1778
1779    /* Inject NMI */
1780    if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
1781        cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
1782        DPRINTF("injected NMI\n");
1783        ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
1784        if (ret < 0) {
1785            fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
1786                    strerror(-ret));
1787        }
1788    }
1789
1790    if (!kvm_irqchip_in_kernel()) {
1791        /* Force the VCPU out of its inner loop to process any INIT requests
1792         * or pending TPR access reports. */
1793        if (cpu->interrupt_request &
1794            (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
1795            cpu->exit_request = 1;
1796        }
1797
1798        /* Try to inject an interrupt if the guest can accept it */
1799        if (run->ready_for_interrupt_injection &&
1800            (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
1801            (env->eflags & IF_MASK)) {
1802            int irq;
1803
1804            cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
1805            irq = cpu_get_pic_interrupt(env);
1806            if (irq >= 0) {
1807                struct kvm_interrupt intr;
1808
1809                intr.irq = irq;
1810                DPRINTF("injected interrupt %d\n", irq);
1811                ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
1812                if (ret < 0) {
1813                    fprintf(stderr,
1814                            "KVM: injection failed, interrupt lost (%s)\n",
1815                            strerror(-ret));
1816                }
1817            }
1818        }
1819
1820        /* If we have an interrupt but the guest is not ready to receive an
1821         * interrupt, request an interrupt window exit.  This will
1822         * cause a return to userspace as soon as the guest is ready to
1823         * receive interrupts. */
1824        if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
1825            run->request_interrupt_window = 1;
1826        } else {
1827            run->request_interrupt_window = 0;
1828        }
1829
1830        DPRINTF("setting tpr\n");
1831        run->cr8 = cpu_get_apic_tpr(env->apic_state);
1832    }
1833}
1834
1835void kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
1836{
1837    X86CPU *x86_cpu = X86_CPU(cpu);
1838    CPUX86State *env = &x86_cpu->env;
1839
1840    if (run->if_flag) {
1841        env->eflags |= IF_MASK;
1842    } else {
1843        env->eflags &= ~IF_MASK;
1844    }
1845    cpu_set_apic_tpr(env->apic_state, run->cr8);
1846    cpu_set_apic_base(env->apic_state, run->apic_base);
1847}
1848
1849int kvm_arch_process_async_events(CPUState *cs)
1850{
1851    X86CPU *cpu = X86_CPU(cs);
1852    CPUX86State *env = &cpu->env;
1853
1854    if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
1855        /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
1856        assert(env->mcg_cap);
1857
1858        cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
1859
1860        kvm_cpu_synchronize_state(env);
1861
1862        if (env->exception_injected == EXCP08_DBLE) {
1863            /* this means triple fault */
1864            qemu_system_reset_request();
1865            cs->exit_request = 1;
1866            return 0;
1867        }
1868        env->exception_injected = EXCP12_MCHK;
1869        env->has_error_code = 0;
1870
1871        cs->halted = 0;
1872        if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
1873            env->mp_state = KVM_MP_STATE_RUNNABLE;
1874        }
1875    }
1876
1877    if (kvm_irqchip_in_kernel()) {
1878        return 0;
1879    }
1880
1881    if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
1882        cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
1883        apic_poll_irq(env->apic_state);
1884    }
1885    if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
1886         (env->eflags & IF_MASK)) ||
1887        (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
1888        cs->halted = 0;
1889    }
1890    if (cs->interrupt_request & CPU_INTERRUPT_INIT) {
1891        kvm_cpu_synchronize_state(env);
1892        do_cpu_init(cpu);
1893    }
1894    if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
1895        kvm_cpu_synchronize_state(env);
1896        do_cpu_sipi(cpu);
1897    }
1898    if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
1899        cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
1900        kvm_cpu_synchronize_state(env);
1901        apic_handle_tpr_access_report(env->apic_state, env->eip,
1902                                      env->tpr_access_type);
1903    }
1904
1905    return cs->halted;
1906}
1907
1908static int kvm_handle_halt(X86CPU *cpu)
1909{
1910    CPUState *cs = CPU(cpu);
1911    CPUX86State *env = &cpu->env;
1912
1913    if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
1914          (env->eflags & IF_MASK)) &&
1915        !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
1916        cs->halted = 1;
1917        return EXCP_HLT;
1918    }
1919
1920    return 0;
1921}
1922
1923static int kvm_handle_tpr_access(X86CPU *cpu)
1924{
1925    CPUX86State *env = &cpu->env;
1926    CPUState *cs = CPU(cpu);
1927    struct kvm_run *run = cs->kvm_run;
1928
1929    apic_handle_tpr_access_report(env->apic_state, run->tpr_access.rip,
1930                                  run->tpr_access.is_write ? TPR_ACCESS_WRITE
1931                                                           : TPR_ACCESS_READ);
1932    return 1;
1933}
1934
1935int kvm_arch_insert_sw_breakpoint(CPUState *cpu, struct kvm_sw_breakpoint *bp)
1936{
1937    CPUX86State *env = &X86_CPU(cpu)->env;
1938    static const uint8_t int3 = 0xcc;
1939
1940    if (cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
1941        cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&int3, 1, 1)) {
1942        return -EINVAL;
1943    }
1944    return 0;
1945}
1946
1947int kvm_arch_remove_sw_breakpoint(CPUState *cpu, struct kvm_sw_breakpoint *bp)
1948{
1949    CPUX86State *env = &X86_CPU(cpu)->env;
1950    uint8_t int3;
1951
1952    if (cpu_memory_rw_debug(env, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
1953        cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
1954        return -EINVAL;
1955    }
1956    return 0;
1957}
1958
1959static struct {
1960    target_ulong addr;
1961    int len;
1962    int type;
1963} hw_breakpoint[4];
1964
1965static int nb_hw_breakpoint;
1966
1967static int find_hw_breakpoint(target_ulong addr, int len, int type)
1968{
1969    int n;
1970
1971    for (n = 0; n < nb_hw_breakpoint; n++) {
1972        if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
1973            (hw_breakpoint[n].len == len || len == -1)) {
1974            return n;
1975        }
1976    }
1977    return -1;
1978}
1979
1980int kvm_arch_insert_hw_breakpoint(target_ulong addr,
1981                                  target_ulong len, int type)
1982{
1983    switch (type) {
1984    case GDB_BREAKPOINT_HW:
1985        len = 1;
1986        break;
1987    case GDB_WATCHPOINT_WRITE:
1988    case GDB_WATCHPOINT_ACCESS:
1989        switch (len) {
1990        case 1:
1991            break;
1992        case 2:
1993        case 4:
1994        case 8:
1995            if (addr & (len - 1)) {
1996                return -EINVAL;
1997            }
1998            break;
1999        default:
2000            return -EINVAL;
2001        }
2002        break;
2003    default:
2004        return -ENOSYS;
2005    }
2006
2007    if (nb_hw_breakpoint == 4) {
2008        return -ENOBUFS;
2009    }
2010    if (find_hw_breakpoint(addr, len, type) >= 0) {
2011        return -EEXIST;
2012    }
2013    hw_breakpoint[nb_hw_breakpoint].addr = addr;
2014    hw_breakpoint[nb_hw_breakpoint].len = len;
2015    hw_breakpoint[nb_hw_breakpoint].type = type;
2016    nb_hw_breakpoint++;
2017
2018    return 0;
2019}
2020
2021int kvm_arch_remove_hw_breakpoint(target_ulong addr,
2022                                  target_ulong len, int type)
2023{
2024    int n;
2025
2026    n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2027    if (n < 0) {
2028        return -ENOENT;
2029    }
2030    nb_hw_breakpoint--;
2031    hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];
2032
2033    return 0;
2034}
2035
2036void kvm_arch_remove_all_hw_breakpoints(void)
2037{
2038    nb_hw_breakpoint = 0;
2039}
2040
2041static CPUWatchpoint hw_watchpoint;
2042
2043static int kvm_handle_debug(X86CPU *cpu,
2044                            struct kvm_debug_exit_arch *arch_info)
2045{
2046    CPUX86State *env = &cpu->env;
2047    int ret = 0;
2048    int n;
2049
2050    if (arch_info->exception == 1) {
2051        if (arch_info->dr6 & (1 << 14)) {
2052            if (env->singlestep_enabled) {
2053                ret = EXCP_DEBUG;
2054            }
2055        } else {
2056            for (n = 0; n < 4; n++) {
2057                if (arch_info->dr6 & (1 << n)) {
2058                    switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
2059                    case 0x0:
2060                        ret = EXCP_DEBUG;
2061                        break;
2062                    case 0x1:
2063                        ret = EXCP_DEBUG;
2064                        env->watchpoint_hit = &hw_watchpoint;
2065                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2066                        hw_watchpoint.flags = BP_MEM_WRITE;
2067                        break;
2068                    case 0x3:
2069                        ret = EXCP_DEBUG;
2070                        env->watchpoint_hit = &hw_watchpoint;
2071                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;
2072                        hw_watchpoint.flags = BP_MEM_ACCESS;
2073                        break;
2074                    }
2075                }
2076            }
2077        }
2078    } else if (kvm_find_sw_breakpoint(CPU(cpu), arch_info->pc)) {
2079        ret = EXCP_DEBUG;
2080    }
2081    if (ret == 0) {
2082        cpu_synchronize_state(env);
2083        assert(env->exception_injected == -1);
2084
2085        /* pass to guest */
2086        env->exception_injected = arch_info->exception;
2087        env->has_error_code = 0;
2088    }
2089
2090    return ret;
2091}
2092
2093void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
2094{
2095    const uint8_t type_code[] = {
2096        [GDB_BREAKPOINT_HW] = 0x0,
2097        [GDB_WATCHPOINT_WRITE] = 0x1,
2098        [GDB_WATCHPOINT_ACCESS] = 0x3
2099    };
2100    const uint8_t len_code[] = {
2101        [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
2102    };
2103    int n;
2104
2105    if (kvm_sw_breakpoints_active(cpu)) {
2106        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
2107    }
2108    if (nb_hw_breakpoint > 0) {
2109        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
2110        dbg->arch.debugreg[7] = 0x0600;
2111        for (n = 0; n < nb_hw_breakpoint; n++) {
2112            dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
2113            dbg->arch.debugreg[7] |= (2 << (n * 2)) |
2114                (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
2115                ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
2116        }
2117    }
2118}
2119
2120static bool host_supports_vmx(void)
2121{
2122    uint32_t ecx, unused;
2123
2124    host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
2125    return ecx & CPUID_EXT_VMX;
2126}
2127
2128#define VMX_INVALID_GUEST_STATE 0x80000021
2129
2130int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
2131{
2132    X86CPU *cpu = X86_CPU(cs);
2133    uint64_t code;
2134    int ret;
2135
2136    switch (run->exit_reason) {
2137    case KVM_EXIT_HLT:
2138        DPRINTF("handle_hlt\n");
2139        ret = kvm_handle_halt(cpu);
2140        break;
2141    case KVM_EXIT_SET_TPR:
2142        ret = 0;
2143        break;
2144    case KVM_EXIT_TPR_ACCESS:
2145        ret = kvm_handle_tpr_access(cpu);
2146        break;
2147    case KVM_EXIT_FAIL_ENTRY:
2148        code = run->fail_entry.hardware_entry_failure_reason;
2149        fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
2150                code);
2151        if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
2152            fprintf(stderr,
2153                    "\nIf you're running a guest on an Intel machine without "
2154                        "unrestricted mode\n"
2155                    "support, the failure can be most likely due to the guest "
2156                        "entering an invalid\n"
2157                    "state for Intel VT. For example, the guest maybe running "
2158                        "in big real mode\n"
2159                    "which is not supported on less recent Intel processors."
2160                        "\n\n");
2161        }
2162        ret = -1;
2163        break;
2164    case KVM_EXIT_EXCEPTION:
2165        fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
2166                run->ex.exception, run->ex.error_code);
2167        ret = -1;
2168        break;
2169    case KVM_EXIT_DEBUG:
2170        DPRINTF("kvm_exit_debug\n");
2171        ret = kvm_handle_debug(cpu, &run->debug.arch);
2172        break;
2173    default:
2174        fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
2175        ret = -1;
2176        break;
2177    }
2178
2179    return ret;
2180}
2181
2182bool kvm_arch_stop_on_emulation_error(CPUState *cs)
2183{
2184    X86CPU *cpu = X86_CPU(cs);
2185    CPUX86State *env = &cpu->env;
2186
2187    kvm_cpu_synchronize_state(env);
2188    return !(env->cr[0] & CR0_PE_MASK) ||
2189           ((env->segs[R_CS].selector  & 3) != 3);
2190}
2191
2192void kvm_arch_init_irq_routing(KVMState *s)
2193{
2194    if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
2195        /* If kernel can't do irq routing, interrupt source
2196         * override 0->2 cannot be set up as required by HPET.
2197         * So we have to disable it.
2198         */
2199        no_hpet = 1;
2200    }
2201    /* We know at this point that we're using the in-kernel
2202     * irqchip, so we can use irqfds, and on x86 we know
2203     * we can use msi via irqfd and GSI routing.
2204     */
2205    kvm_irqfds_allowed = true;
2206    kvm_msi_via_irqfd_allowed = true;
2207    kvm_gsi_routing_allowed = true;
2208}
2209
2210/* Classic KVM device assignment interface. Will remain x86 only. */
2211int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
2212                          uint32_t flags, uint32_t *dev_id)
2213{
2214    struct kvm_assigned_pci_dev dev_data = {
2215        .segnr = dev_addr->domain,
2216        .busnr = dev_addr->bus,
2217        .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
2218        .flags = flags,
2219    };
2220    int ret;
2221
2222    dev_data.assigned_dev_id =
2223        (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;
2224
2225    ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
2226    if (ret < 0) {
2227        return ret;
2228    }
2229
2230    *dev_id = dev_data.assigned_dev_id;
2231
2232    return 0;
2233}
2234
2235int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
2236{
2237    struct kvm_assigned_pci_dev dev_data = {
2238        .assigned_dev_id = dev_id,
2239    };
2240
2241    return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
2242}
2243
2244static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
2245                                   uint32_t irq_type, uint32_t guest_irq)
2246{
2247    struct kvm_assigned_irq assigned_irq = {
2248        .assigned_dev_id = dev_id,
2249        .guest_irq = guest_irq,
2250        .flags = irq_type,
2251    };
2252
2253    if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
2254        return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
2255    } else {
2256        return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
2257    }
2258}
2259
2260int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
2261                           uint32_t guest_irq)
2262{
2263    uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
2264        (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);
2265
2266    return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
2267}
2268
2269int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
2270{
2271    struct kvm_assigned_pci_dev dev_data = {
2272        .assigned_dev_id = dev_id,
2273        .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
2274    };
2275
2276    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
2277}
2278
2279static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
2280                                     uint32_t type)
2281{
2282    struct kvm_assigned_irq assigned_irq = {
2283        .assigned_dev_id = dev_id,
2284        .flags = type,
2285    };
2286
2287    return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
2288}
2289
2290int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
2291{
2292    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
2293        (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
2294}
2295
2296int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
2297{
2298    return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
2299                                              KVM_DEV_IRQ_GUEST_MSI, virq);
2300}
2301
2302int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
2303{
2304    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
2305                                                KVM_DEV_IRQ_HOST_MSI);
2306}
2307
2308bool kvm_device_msix_supported(KVMState *s)
2309{
2310    /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
2311     * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
2312    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
2313}
2314
2315int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
2316                                 uint32_t nr_vectors)
2317{
2318    struct kvm_assigned_msix_nr msix_nr = {
2319        .assigned_dev_id = dev_id,
2320        .entry_nr = nr_vectors,
2321    };
2322
2323    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
2324}
2325
2326int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
2327                               int virq)
2328{
2329    struct kvm_assigned_msix_entry msix_entry = {
2330        .assigned_dev_id = dev_id,
2331        .gsi = virq,
2332        .entry = vector,
2333    };
2334
2335    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
2336}
2337
2338int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
2339{
2340    return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
2341                                              KVM_DEV_IRQ_GUEST_MSIX, 0);
2342}
2343
2344int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
2345{
2346    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
2347                                                KVM_DEV_IRQ_HOST_MSIX);
2348}
2349