kvm.c 99.0 KB
Newer Older
A
aliguori 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * QEMU KVM support
 *
 * Copyright (C) 2006-2008 Qumranet Technologies
 * Copyright IBM, Corp. 2008
 *
 * Authors:
 *  Anthony Liguori   <aliguori@us.ibm.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 *
 */

P
Peter Maydell 已提交
15
#include "qemu/osdep.h"
16
#include "qapi/error.h"
A
aliguori 已提交
17 18
#include <sys/ioctl.h>
#include <sys/mman.h>
19
#include <sys/utsname.h>
A
aliguori 已提交
20 21

#include <linux/kvm.h>
J
Jan Kiszka 已提交
22
#include <linux/kvm_para.h>
A
aliguori 已提交
23 24

#include "qemu-common.h"
25
#include "cpu.h"
26
#include "sysemu/sysemu.h"
27
#include "sysemu/kvm_int.h"
28
#include "kvm_i386.h"
29 30
#include "hyperv.h"

31
#include "exec/gdbstub.h"
32 33
#include "qemu/host-utils.h"
#include "qemu/config-file.h"
34
#include "qemu/error-report.h"
P
Paolo Bonzini 已提交
35 36
#include "hw/i386/pc.h"
#include "hw/i386/apic.h"
37 38
#include "hw/i386/apic_internal.h"
#include "hw/i386/apic-msidef.h"
39

40
#include "exec/ioport.h"
41
#include "standard-headers/asm-x86/hyperv.h"
42
#include "hw/pci/pci.h"
43
#include "hw/pci/msi.h"
44
#include "migration/migration.h"
45
#include "exec/memattrs.h"
A
aliguori 已提交
46 47 48 49

//#define DEBUG_KVM

#ifdef DEBUG_KVM
50
#define DPRINTF(fmt, ...) \
A
aliguori 已提交
51 52
    do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
#else
53
#define DPRINTF(fmt, ...) \
A
aliguori 已提交
54 55 56
    do { } while (0)
#endif

57 58 59
#define MSR_KVM_WALL_CLOCK  0x11
#define MSR_KVM_SYSTEM_TIME 0x12

60 61 62
/* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
 * 255 kvm_msr_entry structs */
#define MSR_BUF_SIZE 4096
63

M
Marcelo Tosatti 已提交
64 65 66 67 68 69 70
#ifndef BUS_MCEERR_AR
#define BUS_MCEERR_AR 4
#endif
#ifndef BUS_MCEERR_AO
#define BUS_MCEERR_AO 5
#endif

71 72 73 74 75 76
const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
    KVM_CAP_INFO(SET_TSS_ADDR),
    KVM_CAP_INFO(EXT_CPUID),
    KVM_CAP_INFO(MP_STATE),
    KVM_CAP_LAST_INFO
};
77

78 79
static bool has_msr_star;
static bool has_msr_hsave_pa;
80
static bool has_msr_tsc_aux;
81
static bool has_msr_tsc_adjust;
82
static bool has_msr_tsc_deadline;
83
static bool has_msr_feature_control;
84
static bool has_msr_async_pf_en;
M
Michael S. Tsirkin 已提交
85
static bool has_msr_pv_eoi_en;
A
Avi Kivity 已提交
86
static bool has_msr_misc_enable;
87
static bool has_msr_smbase;
L
Liu Jinsong 已提交
88
static bool has_msr_bndcfgs;
89
static bool has_msr_kvm_steal_time;
90
static int lm_capable_kernel;
91 92
static bool has_msr_hv_hypercall;
static bool has_msr_hv_vapic;
93
static bool has_msr_hv_tsc;
94
static bool has_msr_hv_crash;
95
static bool has_msr_hv_reset;
96
static bool has_msr_hv_vpindex;
97
static bool has_msr_hv_runtime;
98
static bool has_msr_hv_synic;
99
static bool has_msr_hv_stimer;
100
static bool has_msr_mtrr;
101
static bool has_msr_xss;
102

P
Paolo Bonzini 已提交
103 104 105
static bool has_msr_architectural_pmu;
static uint32_t num_architectural_pmu_counters;

106 107 108 109 110 111 112 113 114
static int has_xsave;
static int has_xcrs;
static int has_pit_state2;

int kvm_has_pit_state2(void)
{
    return has_pit_state2;
}

P
Paolo Bonzini 已提交
115 116 117 118 119
bool kvm_has_smm(void)
{
    return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
}

120 121 122 123 124
bool kvm_allows_irq0_override(void)
{
    return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
static int kvm_get_tsc(CPUState *cs)
{
    X86CPU *cpu = X86_CPU(cs);
    CPUX86State *env = &cpu->env;
    struct {
        struct kvm_msrs info;
        struct kvm_msr_entry entries[1];
    } msr_data;
    int ret;

    if (env->tsc_valid) {
        return 0;
    }

    msr_data.info.nmsrs = 1;
    msr_data.entries[0].index = MSR_IA32_TSC;
    env->tsc_valid = !runstate_is_running();

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
    if (ret < 0) {
        return ret;
    }

148
    assert(ret == 1);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    env->tsc = msr_data.entries[0].data;
    return 0;
}

static inline void do_kvm_synchronize_tsc(void *arg)
{
    CPUState *cpu = arg;

    kvm_get_tsc(cpu);
}

void kvm_synchronize_all_tsc(void)
{
    CPUState *cpu;

    if (kvm_enabled()) {
        CPU_FOREACH(cpu) {
            run_on_cpu(cpu, do_kvm_synchronize_tsc, cpu);
        }
    }
}

171 172 173 174 175 176
static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
{
    struct kvm_cpuid2 *cpuid;
    int r, size;

    size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
177
    cpuid = g_malloc0(size);
178 179
    cpuid->nent = max;
    r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
180 181 182
    if (r == 0 && cpuid->nent >= max) {
        r = -E2BIG;
    }
183 184
    if (r < 0) {
        if (r == -E2BIG) {
185
            g_free(cpuid);
186 187 188 189 190 191 192 193 194 195
            return NULL;
        } else {
            fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
                    strerror(-r));
            exit(1);
        }
    }
    return cpuid;
}

196 197 198 199 200 201 202 203 204 205 206 207 208
/* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
 * for all entries.
 */
static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
{
    struct kvm_cpuid2 *cpuid;
    int max = 1;
    while ((cpuid = try_get_cpuid(s, max)) == NULL) {
        max *= 2;
    }
    return cpuid;
}

209
static const struct kvm_para_features {
210 211 212 213 214 215 216 217 218
    int cap;
    int feature;
} para_features[] = {
    { KVM_CAP_CLOCKSOURCE, KVM_FEATURE_CLOCKSOURCE },
    { KVM_CAP_NOP_IO_DELAY, KVM_FEATURE_NOP_IO_DELAY },
    { KVM_CAP_PV_MMU, KVM_FEATURE_MMU_OP },
    { KVM_CAP_ASYNC_PF, KVM_FEATURE_ASYNC_PF },
};

219
static int get_para_features(KVMState *s)
220 221 222
{
    int i, features = 0;

223
    for (i = 0; i < ARRAY_SIZE(para_features); i++) {
224
        if (kvm_check_extension(s, para_features[i].cap)) {
225 226 227 228 229 230 231 232
            features |= (1 << para_features[i].feature);
        }
    }

    return features;
}


233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
/* Returns the value for a specific register on the cpuid entry
 */
static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
{
    uint32_t ret = 0;
    switch (reg) {
    case R_EAX:
        ret = entry->eax;
        break;
    case R_EBX:
        ret = entry->ebx;
        break;
    case R_ECX:
        ret = entry->ecx;
        break;
    case R_EDX:
        ret = entry->edx;
        break;
    }
    return ret;
}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
/* Find matching entry for function/index on kvm_cpuid2 struct
 */
static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
                                                 uint32_t function,
                                                 uint32_t index)
{
    int i;
    for (i = 0; i < cpuid->nent; ++i) {
        if (cpuid->entries[i].function == function &&
            cpuid->entries[i].index == index) {
            return &cpuid->entries[i];
        }
    }
    /* not found: */
    return NULL;
}

272
uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
273
                                      uint32_t index, int reg)
274 275 276 277
{
    struct kvm_cpuid2 *cpuid;
    uint32_t ret = 0;
    uint32_t cpuid_1_edx;
278
    bool found = false;
279

280
    cpuid = get_supported_cpuid(s);
281

282 283 284 285
    struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
    if (entry) {
        found = true;
        ret = cpuid_entry_get_reg(entry, reg);
286 287
    }

288 289
    /* Fixups for the data returned by KVM, below */

290 291 292
    if (function == 1 && reg == R_EDX) {
        /* KVM before 2.6.30 misreports the following features */
        ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
293 294 295 296 297
    } else if (function == 1 && reg == R_ECX) {
        /* We can set the hypervisor flag, even if KVM does not return it on
         * GET_SUPPORTED_CPUID
         */
        ret |= CPUID_EXT_HYPERVISOR;
298 299 300 301 302 303 304 305
        /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
         * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
         * and the irqchip is in the kernel.
         */
        if (kvm_irqchip_in_kernel() &&
                kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
            ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
        }
306 307 308 309 310 311

        /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
         * without the in-kernel irqchip
         */
        if (!kvm_irqchip_in_kernel()) {
            ret &= ~CPUID_EXT_X2APIC;
312
        }
J
Jan Kiszka 已提交
313 314
    } else if (function == 6 && reg == R_EAX) {
        ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
315 316 317 318 319 320
    } else if (function == 0x80000001 && reg == R_EDX) {
        /* On Intel, kvm returns cpuid according to the Intel spec,
         * so add missing bits according to the AMD spec:
         */
        cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
        ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
321 322
    }

323
    g_free(cpuid);
324

325
    /* fallback for older kernels */
326
    if ((function == KVM_CPUID_FEATURES) && !found) {
327
        ret = get_para_features(s);
328
    }
329 330

    return ret;
G
Gleb Natapov 已提交
331 332
}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
typedef struct HWPoisonPage {
    ram_addr_t ram_addr;
    QLIST_ENTRY(HWPoisonPage) list;
} HWPoisonPage;

static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
    QLIST_HEAD_INITIALIZER(hwpoison_page_list);

static void kvm_unpoison_all(void *param)
{
    HWPoisonPage *page, *next_page;

    QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
        QLIST_REMOVE(page, list);
        qemu_ram_remap(page->ram_addr, TARGET_PAGE_SIZE);
348
        g_free(page);
349 350 351 352 353 354 355 356 357 358 359 360
    }
}

static void kvm_hwpoison_page_add(ram_addr_t ram_addr)
{
    HWPoisonPage *page;

    QLIST_FOREACH(page, &hwpoison_page_list, list) {
        if (page->ram_addr == ram_addr) {
            return;
        }
    }
361
    page = g_new(HWPoisonPage, 1);
362 363 364 365
    page->ram_addr = ram_addr;
    QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
}

M
Marcelo Tosatti 已提交
366 367 368 369 370
static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
                                     int *max_banks)
{
    int r;

371
    r = kvm_check_extension(s, KVM_CAP_MCE);
M
Marcelo Tosatti 已提交
372 373 374 375 376 377 378
    if (r > 0) {
        *max_banks = r;
        return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
    }
    return -ENOSYS;
}

379
static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
M
Marcelo Tosatti 已提交
380
{
381
    CPUX86State *env = &cpu->env;
382 383 384
    uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
                      MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
    uint64_t mcg_status = MCG_STATUS_MCIP;
M
Marcelo Tosatti 已提交
385

386 387 388 389 390 391
    if (code == BUS_MCEERR_AR) {
        status |= MCI_STATUS_AR | 0x134;
        mcg_status |= MCG_STATUS_EIPV;
    } else {
        status |= 0xc0;
        mcg_status |= MCG_STATUS_RIPV;
392
    }
393
    cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
394 395 396
                       (MCM_ADDR_PHYS << 6) | 0xc,
                       cpu_x86_support_mca_broadcast(env) ?
                       MCE_INJECT_BROADCAST : 0);
397 398 399 400 401 402 403 404
}

static void hardware_memory_error(void)
{
    fprintf(stderr, "Hardware memory error!\n");
    exit(1);
}

A
Andreas Färber 已提交
405
int kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
406
{
A
Andreas Färber 已提交
407 408
    X86CPU *cpu = X86_CPU(c);
    CPUX86State *env = &cpu->env;
409
    ram_addr_t ram_addr;
A
Avi Kivity 已提交
410
    hwaddr paddr;
411 412

    if ((env->mcg_cap & MCG_SER_P) && addr
413
        && (code == BUS_MCEERR_AR || code == BUS_MCEERR_AO)) {
414 415
        ram_addr = qemu_ram_addr_from_host(addr);
        if (ram_addr == RAM_ADDR_INVALID ||
416
            !kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
417 418 419 420 421 422 423 424 425
            fprintf(stderr, "Hardware memory error for memory used by "
                    "QEMU itself instead of guest system!\n");
            /* Hope we are lucky for AO MCE */
            if (code == BUS_MCEERR_AO) {
                return 0;
            } else {
                hardware_memory_error();
            }
        }
426
        kvm_hwpoison_page_add(ram_addr);
427
        kvm_mce_inject(cpu, paddr, code);
428
    } else {
429 430 431 432 433 434 435 436 437 438 439 440 441
        if (code == BUS_MCEERR_AO) {
            return 0;
        } else if (code == BUS_MCEERR_AR) {
            hardware_memory_error();
        } else {
            return 1;
        }
    }
    return 0;
}

int kvm_arch_on_sigbus(int code, void *addr)
{
442 443 444
    X86CPU *cpu = X86_CPU(first_cpu);

    if ((cpu->env.mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {
445
        ram_addr_t ram_addr;
A
Avi Kivity 已提交
446
        hwaddr paddr;
447 448

        /* Hope we are lucky for AO MCE */
449 450
        ram_addr = qemu_ram_addr_from_host(addr);
        if (ram_addr == RAM_ADDR_INVALID ||
451
            !kvm_physical_memory_addr_from_host(first_cpu->kvm_state,
452
                                                addr, &paddr)) {
453 454 455 456
            fprintf(stderr, "Hardware memory error for memory used by "
                    "QEMU itself instead of guest system!: %p\n", addr);
            return 0;
        }
457
        kvm_hwpoison_page_add(ram_addr);
458
        kvm_mce_inject(X86_CPU(first_cpu), paddr, code);
459
    } else {
460 461 462 463 464 465 466 467 468 469
        if (code == BUS_MCEERR_AO) {
            return 0;
        } else if (code == BUS_MCEERR_AR) {
            hardware_memory_error();
        } else {
            return 1;
        }
    }
    return 0;
}
M
Marcelo Tosatti 已提交
470

471
static int kvm_inject_mce_oldstyle(X86CPU *cpu)
472
{
473 474
    CPUX86State *env = &cpu->env;

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    if (!kvm_has_vcpu_events() && env->exception_injected == EXCP12_MCHK) {
        unsigned int bank, bank_num = env->mcg_cap & 0xff;
        struct kvm_x86_mce mce;

        env->exception_injected = -1;

        /*
         * There must be at least one bank in use if an MCE is pending.
         * Find it and use its values for the event injection.
         */
        for (bank = 0; bank < bank_num; bank++) {
            if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
                break;
            }
        }
        assert(bank < bank_num);

        mce.bank = bank;
        mce.status = env->mce_banks[bank * 4 + 1];
        mce.mcg_status = env->mcg_status;
        mce.addr = env->mce_banks[bank * 4 + 2];
        mce.misc = env->mce_banks[bank * 4 + 3];

498
        return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
499 500 501 502
    }
    return 0;
}

503
static void cpu_update_state(void *opaque, int running, RunState state)
504
{
505
    CPUX86State *env = opaque;
506 507 508 509 510 511

    if (running) {
        env->tsc_valid = false;
    }
}

512
unsigned long kvm_arch_vcpu_id(CPUState *cs)
513
{
514
    X86CPU *cpu = X86_CPU(cs);
515
    return cpu->apic_id;
516 517
}

518 519 520 521 522 523 524 525 526 527 528 529
#ifndef KVM_CPUID_SIGNATURE_NEXT
#define KVM_CPUID_SIGNATURE_NEXT                0x40000100
#endif

static bool hyperv_hypercall_available(X86CPU *cpu)
{
    return cpu->hyperv_vapic ||
           (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_RETRY);
}

static bool hyperv_enabled(X86CPU *cpu)
{
530 531 532
    CPUState *cs = CPU(cpu);
    return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
           (hyperv_hypercall_available(cpu) ||
533
            cpu->hyperv_time  ||
534
            cpu->hyperv_relaxed_timing ||
535
            cpu->hyperv_crash ||
536
            cpu->hyperv_reset ||
537
            cpu->hyperv_vpindex ||
538
            cpu->hyperv_runtime ||
539 540
            cpu->hyperv_synic ||
            cpu->hyperv_stimer);
541 542
}

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
static int kvm_arch_set_tsc_khz(CPUState *cs)
{
    X86CPU *cpu = X86_CPU(cs);
    CPUX86State *env = &cpu->env;
    int r;

    if (!env->tsc_khz) {
        return 0;
    }

    r = kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL) ?
        kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
        -ENOTSUP;
    if (r < 0) {
        /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
         * TSC frequency doesn't match the one we want.
         */
        int cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
                       kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
                       -ENOTSUP;
        if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
            error_report("warning: TSC frequency mismatch between "
                         "VM and host, and TSC scaling unavailable");
            return r;
        }
    }

    return 0;
}

573 574
static Error *invtsc_mig_blocker;

575
#define KVM_MAX_CPUID_ENTRIES  100
576

A
Andreas Färber 已提交
577
int kvm_arch_init_vcpu(CPUState *cs)
A
aliguori 已提交
578 579
{
    struct {
580
        struct kvm_cpuid2 cpuid;
581
        struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
582
    } QEMU_PACKED cpuid_data;
A
Andreas Färber 已提交
583 584
    X86CPU *cpu = X86_CPU(cs);
    CPUX86State *env = &cpu->env;
585
    uint32_t limit, i, j, cpuid_i;
586
    uint32_t unused;
G
Gleb Natapov 已提交
587 588
    struct kvm_cpuid_entry2 *c;
    uint32_t signature[3];
589
    int kvm_base = KVM_CPUID_SIGNATURE;
590
    int r;
A
aliguori 已提交
591

S
Stefan Weil 已提交
592 593
    memset(&cpuid_data, 0, sizeof(cpuid_data));

A
aliguori 已提交
594 595
    cpuid_i = 0;

G
Gleb Natapov 已提交
596
    /* Paravirtualization CPUIDs */
597 598 599
    if (hyperv_enabled(cpu)) {
        c = &cpuid_data.entries[cpuid_i++];
        c->function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
600 601 602 603 604 605 606 607 608 609 610 611
        if (!cpu->hyperv_vendor_id) {
            memcpy(signature, "Microsoft Hv", 12);
        } else {
            size_t len = strlen(cpu->hyperv_vendor_id);

            if (len > 12) {
                error_report("hv-vendor-id truncated to 12 characters");
                len = 12;
            }
            memset(signature, 0, 12);
            memcpy(signature, cpu->hyperv_vendor_id, len);
        }
612
        c->eax = HYPERV_CPUID_MIN;
613 614 615
        c->ebx = signature[0];
        c->ecx = signature[1];
        c->edx = signature[2];
616

617 618
        c = &cpuid_data.entries[cpuid_i++];
        c->function = HYPERV_CPUID_INTERFACE;
619 620
        memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
        c->eax = signature[0];
621 622 623
        c->ebx = 0;
        c->ecx = 0;
        c->edx = 0;
624 625 626 627 628 629 630 631

        c = &cpuid_data.entries[cpuid_i++];
        c->function = HYPERV_CPUID_VERSION;
        c->eax = 0x00001bbc;
        c->ebx = 0x00060001;

        c = &cpuid_data.entries[cpuid_i++];
        c->function = HYPERV_CPUID_FEATURES;
632
        if (cpu->hyperv_relaxed_timing) {
633 634
            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
        }
635
        if (cpu->hyperv_vapic) {
636 637
            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
            c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
638
            has_msr_hv_vapic = true;
639
        }
640 641 642 643 644 645 646
        if (cpu->hyperv_time &&
            kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
            c->eax |= HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
            c->eax |= 0x200;
            has_msr_hv_tsc = true;
        }
647 648 649
        if (cpu->hyperv_crash && has_msr_hv_crash) {
            c->edx |= HV_X64_GUEST_CRASH_MSR_AVAILABLE;
        }
650
        c->edx |= HV_X64_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
651 652 653
        if (cpu->hyperv_reset && has_msr_hv_reset) {
            c->eax |= HV_X64_MSR_RESET_AVAILABLE;
        }
654 655 656
        if (cpu->hyperv_vpindex && has_msr_hv_vpindex) {
            c->eax |= HV_X64_MSR_VP_INDEX_AVAILABLE;
        }
657 658 659
        if (cpu->hyperv_runtime && has_msr_hv_runtime) {
            c->eax |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
        }
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
        if (cpu->hyperv_synic) {
            int sint;

            if (!has_msr_hv_synic ||
                kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC, 0)) {
                fprintf(stderr, "Hyper-V SynIC is not supported by kernel\n");
                return -ENOSYS;
            }

            c->eax |= HV_X64_MSR_SYNIC_AVAILABLE;
            env->msr_hv_synic_version = HV_SYNIC_VERSION_1;
            for (sint = 0; sint < ARRAY_SIZE(env->msr_hv_synic_sint); sint++) {
                env->msr_hv_synic_sint[sint] = HV_SYNIC_SINT_MASKED;
            }
        }
675 676 677 678 679 680 681
        if (cpu->hyperv_stimer) {
            if (!has_msr_hv_stimer) {
                fprintf(stderr, "Hyper-V timers aren't supported by kernel\n");
                return -ENOSYS;
            }
            c->eax |= HV_X64_MSR_SYNTIMER_AVAILABLE;
        }
682 683
        c = &cpuid_data.entries[cpuid_i++];
        c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;
684
        if (cpu->hyperv_relaxed_timing) {
685 686
            c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
        }
687
        if (has_msr_hv_vapic) {
688 689
            c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
        }
690
        c->ebx = cpu->hyperv_spinlock_attempts;
691 692 693 694 695 696

        c = &cpuid_data.entries[cpuid_i++];
        c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;
        c->eax = 0x40;
        c->ebx = 0x40;

697
        kvm_base = KVM_CPUID_SIGNATURE_NEXT;
698
        has_msr_hv_hypercall = true;
699 700
    }

701 702 703 704
    if (cpu->expose_kvm) {
        memcpy(signature, "KVMKVMKVM\0\0\0", 12);
        c = &cpuid_data.entries[cpuid_i++];
        c->function = KVM_CPUID_SIGNATURE | kvm_base;
705
        c->eax = KVM_CPUID_FEATURES | kvm_base;
706 707 708
        c->ebx = signature[0];
        c->ecx = signature[1];
        c->edx = signature[2];
709

710 711 712
        c = &cpuid_data.entries[cpuid_i++];
        c->function = KVM_CPUID_FEATURES | kvm_base;
        c->eax = env->features[FEAT_KVM];
713

714
        has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);
G
Gleb Natapov 已提交
715

716
        has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);
M
Michael S. Tsirkin 已提交
717

718 719
        has_msr_kvm_steal_time = c->eax & (1 << KVM_FEATURE_STEAL_TIME);
    }
720

721
    cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
A
aliguori 已提交
722 723

    for (i = 0; i <= limit; i++) {
724 725 726 727
        if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
            fprintf(stderr, "unsupported level value: 0x%x\n", limit);
            abort();
        }
G
Gleb Natapov 已提交
728
        c = &cpuid_data.entries[cpuid_i++];
729 730

        switch (i) {
731 732 733 734 735
        case 2: {
            /* Keep reading function 2 till all the input is received */
            int times;

            c->function = i;
736 737 738 739
            c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
                       KVM_CPUID_FLAG_STATE_READ_NEXT;
            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
            times = c->eax & 0xff;
740 741

            for (j = 1; j < times; ++j) {
742 743 744 745 746
                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
                    fprintf(stderr, "cpuid_data is full, no space for "
                            "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
                    abort();
                }
747
                c = &cpuid_data.entries[cpuid_i++];
748
                c->function = i;
749 750
                c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
                cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
751 752 753
            }
            break;
        }
754 755 756 757
        case 4:
        case 0xb:
        case 0xd:
            for (j = 0; ; j++) {
758 759 760
                if (i == 0xd && j == 64) {
                    break;
                }
761 762 763
                c->function = i;
                c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
                c->index = j;
764
                cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
765

766
                if (i == 4 && c->eax == 0) {
767
                    break;
768 769
                }
                if (i == 0xb && !(c->ecx & 0xff00)) {
770
                    break;
771 772
                }
                if (i == 0xd && c->eax == 0) {
773
                    continue;
774
                }
775 776 777 778 779
                if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
                    fprintf(stderr, "cpuid_data is full, no space for "
                            "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
                    abort();
                }
780
                c = &cpuid_data.entries[cpuid_i++];
781 782 783 784
            }
            break;
        default:
            c->function = i;
785 786
            c->flags = 0;
            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
787 788
            break;
        }
A
aliguori 已提交
789
    }
P
Paolo Bonzini 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

    if (limit >= 0x0a) {
        uint32_t ver;

        cpu_x86_cpuid(env, 0x0a, 0, &ver, &unused, &unused, &unused);
        if ((ver & 0xff) > 0) {
            has_msr_architectural_pmu = true;
            num_architectural_pmu_counters = (ver & 0xff00) >> 8;

            /* Shouldn't be more than 32, since that's the number of bits
             * available in EBX to tell us _which_ counters are available.
             * Play it safe.
             */
            if (num_architectural_pmu_counters > MAX_GP_COUNTERS) {
                num_architectural_pmu_counters = MAX_GP_COUNTERS;
            }
        }
    }

809
    cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
A
aliguori 已提交
810 811

    for (i = 0x80000000; i <= limit; i++) {
812 813 814 815
        if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
            fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
            abort();
        }
G
Gleb Natapov 已提交
816
        c = &cpuid_data.entries[cpuid_i++];
A
aliguori 已提交
817 818

        c->function = i;
819 820
        c->flags = 0;
        cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
A
aliguori 已提交
821 822
    }

823 824 825 826 827
    /* Call Centaur's CPUID instructions they are supported. */
    if (env->cpuid_xlevel2 > 0) {
        cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);

        for (i = 0xC0000000; i <= limit; i++) {
828 829 830 831
            if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
                fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
                abort();
            }
832 833 834 835 836 837 838 839
            c = &cpuid_data.entries[cpuid_i++];

            c->function = i;
            c->flags = 0;
            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
        }
    }

A
aliguori 已提交
840 841
    cpuid_data.cpuid.nent = cpuid_i;

M
Marcelo Tosatti 已提交
842
    if (((env->cpuid_version >> 8)&0xF) >= 6
843
        && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
844
           (CPUID_MCE | CPUID_MCA)
845
        && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
846
        uint64_t mcg_cap, unsupported_caps;
M
Marcelo Tosatti 已提交
847
        int banks;
J
Jan Kiszka 已提交
848
        int ret;
M
Marcelo Tosatti 已提交
849

850
        ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
851 852 853
        if (ret < 0) {
            fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
            return ret;
M
Marcelo Tosatti 已提交
854
        }
855

856
        if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
857
            error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
858
                         (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
859
            return -ENOTSUP;
860
        }
861

862 863 864 865 866 867
        unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
        if (unsupported_caps) {
            error_report("warning: Unsupported MCG_CAP bits: 0x%" PRIx64,
                         unsupported_caps);
        }

868 869
        env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
        ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
870 871 872 873
        if (ret < 0) {
            fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
            return ret;
        }
M
Marcelo Tosatti 已提交
874 875
    }

876 877
    qemu_add_vm_change_state_handler(cpu_update_state, env);

878 879 880 881 882 883
    c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
    if (c) {
        has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
                                  !!(c->ecx & CPUID_EXT_SMX);
    }

884 885 886 887 888 889 890 891 892 893 894
    c = cpuid_find_entry(&cpuid_data.cpuid, 0x80000007, 0);
    if (c && (c->edx & 1<<8) && invtsc_mig_blocker == NULL) {
        /* for migration */
        error_setg(&invtsc_mig_blocker,
                   "State blocked by non-migratable CPU device"
                   " (invtsc flag)");
        migrate_add_blocker(invtsc_mig_blocker);
        /* for savevm */
        vmstate_x86_cpu.unmigratable = 1;
    }

895
    cpuid_data.cpuid.padding = 0;
896
    r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
897 898 899
    if (r) {
        return r;
    }
900

901 902 903
    r = kvm_arch_set_tsc_khz(cs);
    if (r < 0) {
        return r;
904 905
    }

906 907 908 909 910 911 912 913 914 915 916 917 918 919
    /* vcpu's TSC frequency is either specified by user, or following
     * the value used by KVM if the former is not present. In the
     * latter case, we query it from KVM and record in env->tsc_khz,
     * so that vcpu's TSC frequency can be migrated later via this field.
     */
    if (!env->tsc_khz) {
        r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
            kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
            -ENOTSUP;
        if (r > 0) {
            env->tsc_khz = r;
        }
    }

920
    if (has_xsave) {
921 922
        env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
    }
923
    cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
924

925 926 927
    if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
        has_msr_mtrr = true;
    }
928 929 930
    if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
        has_msr_tsc_aux = false;
    }
931

932
    return 0;
A
aliguori 已提交
933 934
}

935
void kvm_arch_reset_vcpu(X86CPU *cpu)
J
Jan Kiszka 已提交
936
{
A
Andreas Färber 已提交
937
    CPUX86State *env = &cpu->env;
938

939
    env->exception_injected = -1;
940
    env->interrupt_injected = -1;
J
Jan Kiszka 已提交
941
    env->xcr0 = 1;
M
Marcelo Tosatti 已提交
942
    if (kvm_irqchip_in_kernel()) {
943
        env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
M
Marcelo Tosatti 已提交
944 945 946 947
                                          KVM_MP_STATE_UNINITIALIZED;
    } else {
        env->mp_state = KVM_MP_STATE_RUNNABLE;
    }
J
Jan Kiszka 已提交
948 949
}

950 951 952 953 954 955 956 957 958 959
void kvm_arch_do_init_vcpu(X86CPU *cpu)
{
    CPUX86State *env = &cpu->env;

    /* APs get directly into wait-for-SIPI state.  */
    if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
        env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
    }
}

960
static int kvm_get_supported_msrs(KVMState *s)
A
aliguori 已提交
961
{
M
Marcelo Tosatti 已提交
962
    static int kvm_supported_msrs;
963
    int ret = 0;
A
aliguori 已提交
964 965

    /* first time */
M
Marcelo Tosatti 已提交
966
    if (kvm_supported_msrs == 0) {
A
aliguori 已提交
967 968
        struct kvm_msr_list msr_list, *kvm_msr_list;

M
Marcelo Tosatti 已提交
969
        kvm_supported_msrs = -1;
A
aliguori 已提交
970 971 972

        /* Obtain MSR list from KVM.  These are the MSRs that we must
         * save/restore */
A
aliguori 已提交
973
        msr_list.nmsrs = 0;
974
        ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
975
        if (ret < 0 && ret != -E2BIG) {
976
            return ret;
977
        }
978 979
        /* Old kernel modules had a bug and could write beyond the provided
           memory. Allocate at least a safe amount of 1K. */
980
        kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
981 982
                                              msr_list.nmsrs *
                                              sizeof(msr_list.indices[0])));
A
aliguori 已提交
983

984
        kvm_msr_list->nmsrs = msr_list.nmsrs;
985
        ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
A
aliguori 已提交
986 987 988 989 990
        if (ret >= 0) {
            int i;

            for (i = 0; i < kvm_msr_list->nmsrs; i++) {
                if (kvm_msr_list->indices[i] == MSR_STAR) {
991
                    has_msr_star = true;
M
Marcelo Tosatti 已提交
992 993 994
                    continue;
                }
                if (kvm_msr_list->indices[i] == MSR_VM_HSAVE_PA) {
995
                    has_msr_hsave_pa = true;
M
Marcelo Tosatti 已提交
996
                    continue;
A
aliguori 已提交
997
                }
998 999 1000 1001
                if (kvm_msr_list->indices[i] == MSR_TSC_AUX) {
                    has_msr_tsc_aux = true;
                    continue;
                }
1002 1003 1004 1005
                if (kvm_msr_list->indices[i] == MSR_TSC_ADJUST) {
                    has_msr_tsc_adjust = true;
                    continue;
                }
1006 1007 1008 1009
                if (kvm_msr_list->indices[i] == MSR_IA32_TSCDEADLINE) {
                    has_msr_tsc_deadline = true;
                    continue;
                }
1010 1011 1012 1013
                if (kvm_msr_list->indices[i] == MSR_IA32_SMBASE) {
                    has_msr_smbase = true;
                    continue;
                }
A
Avi Kivity 已提交
1014 1015 1016 1017
                if (kvm_msr_list->indices[i] == MSR_IA32_MISC_ENABLE) {
                    has_msr_misc_enable = true;
                    continue;
                }
L
Liu Jinsong 已提交
1018 1019 1020 1021
                if (kvm_msr_list->indices[i] == MSR_IA32_BNDCFGS) {
                    has_msr_bndcfgs = true;
                    continue;
                }
1022 1023 1024 1025
                if (kvm_msr_list->indices[i] == MSR_IA32_XSS) {
                    has_msr_xss = true;
                    continue;
                }
1026 1027 1028 1029
                if (kvm_msr_list->indices[i] == HV_X64_MSR_CRASH_CTL) {
                    has_msr_hv_crash = true;
                    continue;
                }
1030 1031 1032 1033
                if (kvm_msr_list->indices[i] == HV_X64_MSR_RESET) {
                    has_msr_hv_reset = true;
                    continue;
                }
1034 1035 1036 1037
                if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_INDEX) {
                    has_msr_hv_vpindex = true;
                    continue;
                }
1038 1039 1040 1041
                if (kvm_msr_list->indices[i] == HV_X64_MSR_VP_RUNTIME) {
                    has_msr_hv_runtime = true;
                    continue;
                }
1042 1043 1044 1045
                if (kvm_msr_list->indices[i] == HV_X64_MSR_SCONTROL) {
                    has_msr_hv_synic = true;
                    continue;
                }
1046 1047 1048 1049
                if (kvm_msr_list->indices[i] == HV_X64_MSR_STIMER0_CONFIG) {
                    has_msr_hv_stimer = true;
                    continue;
                }
A
aliguori 已提交
1050 1051 1052
            }
        }

1053
        g_free(kvm_msr_list);
A
aliguori 已提交
1054 1055
    }

1056
    return ret;
A
aliguori 已提交
1057 1058
}

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
static Notifier smram_machine_done;
static KVMMemoryListener smram_listener;
static AddressSpace smram_address_space;
static MemoryRegion smram_as_root;
static MemoryRegion smram_as_mem;

static void register_smram_listener(Notifier *n, void *unused)
{
    MemoryRegion *smram =
        (MemoryRegion *) object_resolve_path("/machine/smram", NULL);

    /* Outer container... */
    memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
    memory_region_set_enabled(&smram_as_root, true);

    /* ... with two regions inside: normal system memory with low
     * priority, and...
     */
    memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
                             get_system_memory(), 0, ~0ull);
    memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
    memory_region_set_enabled(&smram_as_mem, true);

    if (smram) {
        /* ... SMRAM with higher priority */
        memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
        memory_region_set_enabled(smram, true);
    }

    address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
    kvm_memory_listener_register(kvm_state, &smram_listener,
                                 &smram_address_space, 1);
}

1093
int kvm_arch_init(MachineState *ms, KVMState *s)
1094
{
1095
    uint64_t identity_base = 0xfffbc000;
J
Jan Kiszka 已提交
1096
    uint64_t shadow_mem;
1097
    int ret;
1098
    struct utsname utsname;
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
#ifdef KVM_CAP_XSAVE
    has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
#endif

#ifdef KVM_CAP_XCRS
    has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
#endif

#ifdef KVM_CAP_PIT_STATE2
    has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
#endif

1112
    ret = kvm_get_supported_msrs(s);
1113 1114 1115
    if (ret < 0) {
        return ret;
    }
1116 1117 1118 1119

    uname(&utsname);
    lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;

J
Jes Sorensen 已提交
1120
    /*
1121 1122 1123 1124 1125 1126 1127 1128 1129
     * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
     * In order to use vm86 mode, an EPT identity map and a TSS  are needed.
     * Since these must be part of guest physical memory, we need to allocate
     * them, both by setting their start addresses in the kernel and by
     * creating a corresponding e820 entry. We need 4 pages before the BIOS.
     *
     * Older KVM versions may not support setting the identity map base. In
     * that case we need to stick with the default, i.e. a 256K maximum BIOS
     * size.
J
Jes Sorensen 已提交
1130
     */
1131 1132 1133 1134 1135 1136 1137 1138
    if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
        /* Allows up to 16M BIOSes. */
        identity_base = 0xfeffc000;

        ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
        if (ret < 0) {
            return ret;
        }
J
Jes Sorensen 已提交
1139
    }
1140

1141 1142
    /* Set TSS base one page after EPT identity map. */
    ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
1143 1144 1145 1146
    if (ret < 0) {
        return ret;
    }

1147 1148
    /* Tell fw_cfg to notify the BIOS to reserve the range. */
    ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
1149
    if (ret < 0) {
1150
        fprintf(stderr, "e820_add_entry() table is full\n");
1151 1152
        return ret;
    }
1153
    qemu_register_reset(kvm_unpoison_all, NULL);
1154

1155
    shadow_mem = machine_kvm_shadow_mem(ms);
1156 1157 1158 1159 1160
    if (shadow_mem != -1) {
        shadow_mem /= 4096;
        ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
        if (ret < 0) {
            return ret;
J
Jan Kiszka 已提交
1161 1162
        }
    }
1163 1164 1165 1166 1167

    if (kvm_check_extension(s, KVM_CAP_X86_SMM)) {
        smram_machine_done.notify = register_smram_listener;
        qemu_add_machine_init_done_notifier(&smram_machine_done);
    }
1168
    return 0;
A
aliguori 已提交
1169
}
1170

A
aliguori 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
{
    lhs->selector = rhs->selector;
    lhs->base = rhs->base;
    lhs->limit = rhs->limit;
    lhs->type = 3;
    lhs->present = 1;
    lhs->dpl = 3;
    lhs->db = 0;
    lhs->s = 1;
    lhs->l = 0;
    lhs->g = 0;
    lhs->avl = 0;
    lhs->unusable = 0;
}

static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
{
    unsigned flags = rhs->flags;
    lhs->selector = rhs->selector;
    lhs->base = rhs->base;
    lhs->limit = rhs->limit;
    lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
    lhs->present = (flags & DESC_P_MASK) != 0;
1195
    lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
A
aliguori 已提交
1196 1197 1198 1199 1200
    lhs->db = (flags >> DESC_B_SHIFT) & 1;
    lhs->s = (flags & DESC_S_MASK) != 0;
    lhs->l = (flags >> DESC_L_SHIFT) & 1;
    lhs->g = (flags & DESC_G_MASK) != 0;
    lhs->avl = (flags & DESC_AVL_MASK) != 0;
1201
    lhs->unusable = !lhs->present;
1202
    lhs->padding = 0;
A
aliguori 已提交
1203 1204 1205 1206 1207 1208 1209
}

static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
{
    lhs->selector = rhs->selector;
    lhs->base = rhs->base;
    lhs->limit = rhs->limit;
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    if (rhs->unusable) {
        lhs->flags = 0;
    } else {
        lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
                     (rhs->present * DESC_P_MASK) |
                     (rhs->dpl << DESC_DPL_SHIFT) |
                     (rhs->db << DESC_B_SHIFT) |
                     (rhs->s * DESC_S_MASK) |
                     (rhs->l << DESC_L_SHIFT) |
                     (rhs->g * DESC_G_MASK) |
                     (rhs->avl * DESC_AVL_MASK);
    }
A
aliguori 已提交
1222 1223 1224 1225
}

static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
{
1226
    if (set) {
A
aliguori 已提交
1227
        *kvm_reg = *qemu_reg;
1228
    } else {
A
aliguori 已提交
1229
        *qemu_reg = *kvm_reg;
1230
    }
A
aliguori 已提交
1231 1232
}

1233
static int kvm_getput_regs(X86CPU *cpu, int set)
A
aliguori 已提交
1234
{
1235
    CPUX86State *env = &cpu->env;
A
aliguori 已提交
1236 1237 1238 1239
    struct kvm_regs regs;
    int ret = 0;

    if (!set) {
1240
        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
1241
        if (ret < 0) {
A
aliguori 已提交
1242
            return ret;
1243
        }
A
aliguori 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    }

    kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
    kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
    kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
    kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
    kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
    kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
    kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
    kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
#ifdef TARGET_X86_64
    kvm_getput_reg(&regs.r8, &env->regs[8], set);
    kvm_getput_reg(&regs.r9, &env->regs[9], set);
    kvm_getput_reg(&regs.r10, &env->regs[10], set);
    kvm_getput_reg(&regs.r11, &env->regs[11], set);
    kvm_getput_reg(&regs.r12, &env->regs[12], set);
    kvm_getput_reg(&regs.r13, &env->regs[13], set);
    kvm_getput_reg(&regs.r14, &env->regs[14], set);
    kvm_getput_reg(&regs.r15, &env->regs[15], set);
#endif

    kvm_getput_reg(&regs.rflags, &env->eflags, set);
    kvm_getput_reg(&regs.rip, &env->eip, set);

1268
    if (set) {
1269
        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
1270
    }
A
aliguori 已提交
1271 1272 1273 1274

    return ret;
}

1275
static int kvm_put_fpu(X86CPU *cpu)
A
aliguori 已提交
1276
{
1277
    CPUX86State *env = &cpu->env;
A
aliguori 已提交
1278 1279 1280 1281 1282 1283 1284
    struct kvm_fpu fpu;
    int i;

    memset(&fpu, 0, sizeof fpu);
    fpu.fsw = env->fpus & ~(7 << 11);
    fpu.fsw |= (env->fpstt & 7) << 11;
    fpu.fcw = env->fpuc;
1285 1286 1287
    fpu.last_opcode = env->fpop;
    fpu.last_ip = env->fpip;
    fpu.last_dp = env->fpdp;
1288 1289 1290
    for (i = 0; i < 8; ++i) {
        fpu.ftwx |= (!env->fptags[i]) << i;
    }
A
aliguori 已提交
1291
    memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
1292
    for (i = 0; i < CPU_NB_REGS; i++) {
1293 1294
        stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
        stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
1295
    }
A
aliguori 已提交
1296 1297
    fpu.mxcsr = env->mxcsr;

1298
    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
A
aliguori 已提交
1299 1300
}

1301 1302
#define XSAVE_FCW_FSW     0
#define XSAVE_FTW_FOP     1
1303 1304 1305 1306 1307 1308 1309
#define XSAVE_CWD_RIP     2
#define XSAVE_CWD_RDP     4
#define XSAVE_MXCSR       6
#define XSAVE_ST_SPACE    8
#define XSAVE_XMM_SPACE   40
#define XSAVE_XSTATE_BV   128
#define XSAVE_YMMH_SPACE  144
L
Liu Jinsong 已提交
1310 1311
#define XSAVE_BNDREGS     240
#define XSAVE_BNDCSR      256
C
Chao Peng 已提交
1312 1313 1314
#define XSAVE_OPMASK      272
#define XSAVE_ZMM_Hi256   288
#define XSAVE_Hi16_ZMM    416
1315
#define XSAVE_PKRU        672
1316

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
#define XSAVE_BYTE_OFFSET(word_offset) \
    ((word_offset) * sizeof(((struct kvm_xsave *)0)->region[0]))

#define ASSERT_OFFSET(word_offset, field) \
    QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
                      offsetof(X86XSaveArea, field))

ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
ASSERT_OFFSET(XSAVE_PKRU, pkru_state);

1340
static int kvm_put_xsave(X86CPU *cpu)
1341
{
1342
    CPUX86State *env = &cpu->env;
1343
    X86XSaveArea *xsave = env->kvm_xsave_buf;
1344
    uint16_t cwd, swd, twd;
1345
    int i, r;
1346

1347
    if (!has_xsave) {
1348
        return kvm_put_fpu(cpu);
1349
    }
1350 1351

    memset(xsave, 0, sizeof(struct kvm_xsave));
B
Blue Swirl 已提交
1352
    twd = 0;
1353 1354 1355
    swd = env->fpus & ~(7 << 11);
    swd |= (env->fpstt & 7) << 11;
    cwd = env->fpuc;
1356
    for (i = 0; i < 8; ++i) {
1357
        twd |= (!env->fptags[i]) << i;
1358
    }
1359 1360 1361 1362 1363 1364 1365
    xsave->legacy.fcw = cwd;
    xsave->legacy.fsw = swd;
    xsave->legacy.ftw = twd;
    xsave->legacy.fpop = env->fpop;
    xsave->legacy.fpip = env->fpip;
    xsave->legacy.fpdp = env->fpdp;
    memcpy(&xsave->legacy.fpregs, env->fpregs,
1366
            sizeof env->fpregs);
1367 1368 1369
    xsave->legacy.mxcsr = env->mxcsr;
    xsave->header.xstate_bv = env->xstate_bv;
    memcpy(&xsave->bndreg_state.bnd_regs, env->bnd_regs,
L
Liu Jinsong 已提交
1370
            sizeof env->bnd_regs);
1371 1372
    xsave->bndcsr_state.bndcsr = env->bndcs_regs;
    memcpy(&xsave->opmask_state.opmask_regs, env->opmask_regs,
C
Chao Peng 已提交
1373
            sizeof env->opmask_regs);
1374

1375 1376 1377 1378
    for (i = 0; i < CPU_NB_REGS; i++) {
        uint8_t *xmm = xsave->legacy.xmm_regs[i];
        uint8_t *ymmh = xsave->avx_state.ymmh[i];
        uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1379 1380 1381 1382 1383 1384 1385 1386
        stq_p(xmm,     env->xmm_regs[i].ZMM_Q(0));
        stq_p(xmm+8,   env->xmm_regs[i].ZMM_Q(1));
        stq_p(ymmh,    env->xmm_regs[i].ZMM_Q(2));
        stq_p(ymmh+8,  env->xmm_regs[i].ZMM_Q(3));
        stq_p(zmmh,    env->xmm_regs[i].ZMM_Q(4));
        stq_p(zmmh+8,  env->xmm_regs[i].ZMM_Q(5));
        stq_p(zmmh+16, env->xmm_regs[i].ZMM_Q(6));
        stq_p(zmmh+24, env->xmm_regs[i].ZMM_Q(7));
1387 1388
    }

C
Chao Peng 已提交
1389
#ifdef TARGET_X86_64
1390
    memcpy(&xsave->hi16_zmm_state.hi16_zmm, &env->xmm_regs[16],
1391
            16 * sizeof env->xmm_regs[16]);
1392
    memcpy(&xsave->pkru_state, &env->pkru, sizeof env->pkru);
C
Chao Peng 已提交
1393
#endif
1394
    r = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
1395
    return r;
1396 1397
}

1398
static int kvm_put_xcrs(X86CPU *cpu)
1399
{
1400
    CPUX86State *env = &cpu->env;
1401
    struct kvm_xcrs xcrs = {};
1402

1403
    if (!has_xcrs) {
1404
        return 0;
1405
    }
1406 1407 1408 1409 1410

    xcrs.nr_xcrs = 1;
    xcrs.flags = 0;
    xcrs.xcrs[0].xcr = 0;
    xcrs.xcrs[0].value = env->xcr0;
1411
    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
1412 1413
}

1414
static int kvm_put_sregs(X86CPU *cpu)
A
aliguori 已提交
1415
{
1416
    CPUX86State *env = &cpu->env;
A
aliguori 已提交
1417 1418
    struct kvm_sregs sregs;

1419 1420 1421 1422 1423
    memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
    if (env->interrupt_injected >= 0) {
        sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
                (uint64_t)1 << (env->interrupt_injected % 64);
    }
A
aliguori 已提交
1424 1425

    if ((env->eflags & VM_MASK)) {
1426 1427 1428 1429 1430 1431
        set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
        set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
        set_v8086_seg(&sregs.es, &env->segs[R_ES]);
        set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
        set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
        set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
A
aliguori 已提交
1432
    } else {
1433 1434 1435 1436 1437 1438
        set_seg(&sregs.cs, &env->segs[R_CS]);
        set_seg(&sregs.ds, &env->segs[R_DS]);
        set_seg(&sregs.es, &env->segs[R_ES]);
        set_seg(&sregs.fs, &env->segs[R_FS]);
        set_seg(&sregs.gs, &env->segs[R_GS]);
        set_seg(&sregs.ss, &env->segs[R_SS]);
A
aliguori 已提交
1439 1440 1441 1442 1443 1444 1445
    }

    set_seg(&sregs.tr, &env->tr);
    set_seg(&sregs.ldt, &env->ldt);

    sregs.idt.limit = env->idt.limit;
    sregs.idt.base = env->idt.base;
1446
    memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
A
aliguori 已提交
1447 1448
    sregs.gdt.limit = env->gdt.limit;
    sregs.gdt.base = env->gdt.base;
1449
    memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
A
aliguori 已提交
1450 1451 1452 1453 1454 1455

    sregs.cr0 = env->cr[0];
    sregs.cr2 = env->cr[2];
    sregs.cr3 = env->cr[3];
    sregs.cr4 = env->cr[4];

1456 1457
    sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
    sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
A
aliguori 已提交
1458 1459 1460

    sregs.efer = env->efer;

1461
    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
A
aliguori 已提交
1462 1463
}

1464 1465 1466 1467 1468
static void kvm_msr_buf_reset(X86CPU *cpu)
{
    memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
}

1469 1470 1471 1472 1473 1474 1475 1476
static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
{
    struct kvm_msrs *msrs = cpu->kvm_msr_buf;
    void *limit = ((void *)msrs) + MSR_BUF_SIZE;
    struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];

    assert((void *)(entry + 1) <= limit);

1477 1478 1479
    entry->index = index;
    entry->reserved = 0;
    entry->data = value;
1480 1481 1482
    msrs->nmsrs++;
}

1483 1484 1485
static int kvm_put_tscdeadline_msr(X86CPU *cpu)
{
    CPUX86State *env = &cpu->env;
1486
    int ret;
1487 1488 1489 1490 1491

    if (!has_msr_tsc_deadline) {
        return 0;
    }

1492 1493
    kvm_msr_buf_reset(cpu);
    kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
1494

1495
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1496 1497 1498 1499 1500 1501
    if (ret < 0) {
        return ret;
    }

    assert(ret == 1);
    return 0;
1502 1503
}

1504 1505 1506 1507 1508 1509 1510 1511
/*
 * Provide a separate write service for the feature control MSR in order to
 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
 * before writing any other state because forcibly leaving nested mode
 * invalidates the VCPU state.
 */
static int kvm_put_msr_feature_control(X86CPU *cpu)
{
1512 1513 1514 1515 1516
    int ret;

    if (!has_msr_feature_control) {
        return 0;
    }
1517

1518 1519
    kvm_msr_buf_reset(cpu);
    kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL,
1520
                      cpu->env.msr_ia32_feature_control);
1521

1522
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1523 1524 1525 1526 1527 1528
    if (ret < 0) {
        return ret;
    }

    assert(ret == 1);
    return 0;
1529 1530
}

1531
static int kvm_put_msrs(X86CPU *cpu, int level)
A
aliguori 已提交
1532
{
1533
    CPUX86State *env = &cpu->env;
1534
    int i;
1535
    int ret;
A
aliguori 已提交
1536

1537 1538
    kvm_msr_buf_reset(cpu);

1539 1540 1541 1542
    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
    kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
1543
    if (has_msr_star) {
1544
        kvm_msr_entry_add(cpu, MSR_STAR, env->star);
1545
    }
1546
    if (has_msr_hsave_pa) {
1547
        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
1548
    }
1549
    if (has_msr_tsc_aux) {
1550
        kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
1551
    }
1552
    if (has_msr_tsc_adjust) {
1553
        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
1554
    }
A
Avi Kivity 已提交
1555
    if (has_msr_misc_enable) {
1556
        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
A
Avi Kivity 已提交
1557 1558
                          env->msr_ia32_misc_enable);
    }
1559
    if (has_msr_smbase) {
1560
        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
1561
    }
1562
    if (has_msr_bndcfgs) {
1563
        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
1564
    }
1565
    if (has_msr_xss) {
1566
        kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
1567
    }
A
aliguori 已提交
1568
#ifdef TARGET_X86_64
1569
    if (lm_capable_kernel) {
1570 1571 1572 1573
        kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
        kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
        kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
1574
    }
A
aliguori 已提交
1575
#endif
J
Jan Kiszka 已提交
1576
    /*
P
Paolo Bonzini 已提交
1577 1578
     * The following MSRs have side effects on the guest or are too heavy
     * for normal writeback. Limit them to reset or full state updates.
J
Jan Kiszka 已提交
1579 1580
     */
    if (level >= KVM_PUT_RESET_STATE) {
1581 1582 1583
        kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
        kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
        kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
1584
        if (has_msr_async_pf_en) {
1585
            kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
1586
        }
M
Michael S. Tsirkin 已提交
1587
        if (has_msr_pv_eoi_en) {
1588
            kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
M
Michael S. Tsirkin 已提交
1589
        }
1590
        if (has_msr_kvm_steal_time) {
1591
            kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
1592
        }
P
Paolo Bonzini 已提交
1593 1594
        if (has_msr_architectural_pmu) {
            /* Stop the counter.  */
1595 1596
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
P
Paolo Bonzini 已提交
1597 1598 1599

            /* Set the counter values.  */
            for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1600
                kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
P
Paolo Bonzini 已提交
1601 1602 1603
                                  env->msr_fixed_counters[i]);
            }
            for (i = 0; i < num_architectural_pmu_counters; i++) {
1604
                kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
P
Paolo Bonzini 已提交
1605
                                  env->msr_gp_counters[i]);
1606
                kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
P
Paolo Bonzini 已提交
1607 1608
                                  env->msr_gp_evtsel[i]);
            }
1609
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
P
Paolo Bonzini 已提交
1610
                              env->msr_global_status);
1611
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
P
Paolo Bonzini 已提交
1612 1613 1614
                              env->msr_global_ovf_ctrl);

            /* Now start the PMU.  */
1615
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
P
Paolo Bonzini 已提交
1616
                              env->msr_fixed_ctr_ctrl);
1617
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
P
Paolo Bonzini 已提交
1618 1619
                              env->msr_global_ctrl);
        }
1620
        if (has_msr_hv_hypercall) {
1621
            kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
1622
                              env->msr_hv_guest_os_id);
1623
            kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
1624
                              env->msr_hv_hypercall);
1625
        }
1626
        if (has_msr_hv_vapic) {
1627
            kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
1628
                              env->msr_hv_vapic);
1629
        }
1630
        if (has_msr_hv_tsc) {
1631
            kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, env->msr_hv_tsc);
1632
        }
1633 1634 1635 1636
        if (has_msr_hv_crash) {
            int j;

            for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++)
1637
                kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
1638 1639
                                  env->msr_hv_crash_params[j]);

1640
            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL,
1641 1642
                              HV_X64_MSR_CRASH_CTL_NOTIFY);
        }
1643
        if (has_msr_hv_runtime) {
1644
            kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
1645
        }
1646 1647 1648
        if (cpu->hyperv_synic) {
            int j;

1649
            kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
1650
                              env->msr_hv_synic_control);
1651
            kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION,
1652
                              env->msr_hv_synic_version);
1653
            kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
1654
                              env->msr_hv_synic_evt_page);
1655
            kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
1656 1657 1658
                              env->msr_hv_synic_msg_page);

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
1659
                kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
1660 1661 1662
                                  env->msr_hv_synic_sint[j]);
            }
        }
1663 1664 1665 1666
        if (has_msr_hv_stimer) {
            int j;

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
1667
                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
1668 1669 1670 1671
                                env->msr_hv_stimer_config[j]);
            }

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
1672
                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
1673 1674 1675
                                env->msr_hv_stimer_count[j]);
            }
        }
1676
        if (has_msr_mtrr) {
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
            kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
            kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
1689
            for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
1690 1691 1692 1693
                kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
                                  env->mtrr_var[i].base);
                kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i),
                                  env->mtrr_var[i].mask);
1694 1695
            }
        }
1696 1697 1698

        /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
         *       kvm_put_msr_feature_control. */
1699
    }
1700
    if (env->mcg_cap) {
H
Hidetoshi Seto 已提交
1701
        int i;
1702

1703 1704
        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
        kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
1705
        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
1706
            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
1707 1708
        }
    }
1709

1710
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
1711 1712 1713
    if (ret < 0) {
        return ret;
    }
A
aliguori 已提交
1714

1715
    assert(ret == cpu->kvm_msr_buf->nmsrs);
1716
    return 0;
A
aliguori 已提交
1717 1718 1719
}


1720
static int kvm_get_fpu(X86CPU *cpu)
A
aliguori 已提交
1721
{
1722
    CPUX86State *env = &cpu->env;
A
aliguori 已提交
1723 1724 1725
    struct kvm_fpu fpu;
    int i, ret;

1726
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
1727
    if (ret < 0) {
A
aliguori 已提交
1728
        return ret;
1729
    }
A
aliguori 已提交
1730 1731 1732 1733

    env->fpstt = (fpu.fsw >> 11) & 7;
    env->fpus = fpu.fsw;
    env->fpuc = fpu.fcw;
1734 1735 1736
    env->fpop = fpu.last_opcode;
    env->fpip = fpu.last_ip;
    env->fpdp = fpu.last_dp;
1737 1738 1739
    for (i = 0; i < 8; ++i) {
        env->fptags[i] = !((fpu.ftwx >> i) & 1);
    }
A
aliguori 已提交
1740
    memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
1741
    for (i = 0; i < CPU_NB_REGS; i++) {
1742 1743
        env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
        env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
1744
    }
A
aliguori 已提交
1745 1746 1747 1748 1749
    env->mxcsr = fpu.mxcsr;

    return 0;
}

1750
static int kvm_get_xsave(X86CPU *cpu)
1751
{
1752
    CPUX86State *env = &cpu->env;
1753
    X86XSaveArea *xsave = env->kvm_xsave_buf;
1754
    int ret, i;
1755
    uint16_t cwd, swd, twd;
1756

1757
    if (!has_xsave) {
1758
        return kvm_get_fpu(cpu);
1759
    }
1760

1761
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
1762
    if (ret < 0) {
1763
        return ret;
1764
    }
1765

1766 1767 1768 1769
    cwd = xsave->legacy.fcw;
    swd = xsave->legacy.fsw;
    twd = xsave->legacy.ftw;
    env->fpop = xsave->legacy.fpop;
1770 1771 1772
    env->fpstt = (swd >> 11) & 7;
    env->fpus = swd;
    env->fpuc = cwd;
1773
    for (i = 0; i < 8; ++i) {
1774
        env->fptags[i] = !((twd >> i) & 1);
1775
    }
1776 1777 1778 1779
    env->fpip = xsave->legacy.fpip;
    env->fpdp = xsave->legacy.fpdp;
    env->mxcsr = xsave->legacy.mxcsr;
    memcpy(env->fpregs, &xsave->legacy.fpregs,
1780
            sizeof env->fpregs);
1781 1782
    env->xstate_bv = xsave->header.xstate_bv;
    memcpy(env->bnd_regs, &xsave->bndreg_state.bnd_regs,
L
Liu Jinsong 已提交
1783
            sizeof env->bnd_regs);
1784 1785
    env->bndcs_regs = xsave->bndcsr_state.bndcsr;
    memcpy(env->opmask_regs, &xsave->opmask_state.opmask_regs,
C
Chao Peng 已提交
1786
            sizeof env->opmask_regs);
1787

1788 1789 1790 1791
    for (i = 0; i < CPU_NB_REGS; i++) {
        uint8_t *xmm = xsave->legacy.xmm_regs[i];
        uint8_t *ymmh = xsave->avx_state.ymmh[i];
        uint8_t *zmmh = xsave->zmm_hi256_state.zmm_hi256[i];
1792 1793 1794 1795 1796 1797 1798 1799
        env->xmm_regs[i].ZMM_Q(0) = ldq_p(xmm);
        env->xmm_regs[i].ZMM_Q(1) = ldq_p(xmm+8);
        env->xmm_regs[i].ZMM_Q(2) = ldq_p(ymmh);
        env->xmm_regs[i].ZMM_Q(3) = ldq_p(ymmh+8);
        env->xmm_regs[i].ZMM_Q(4) = ldq_p(zmmh);
        env->xmm_regs[i].ZMM_Q(5) = ldq_p(zmmh+8);
        env->xmm_regs[i].ZMM_Q(6) = ldq_p(zmmh+16);
        env->xmm_regs[i].ZMM_Q(7) = ldq_p(zmmh+24);
1800 1801
    }

C
Chao Peng 已提交
1802
#ifdef TARGET_X86_64
1803
    memcpy(&env->xmm_regs[16], &xsave->hi16_zmm_state.hi16_zmm,
1804
           16 * sizeof env->xmm_regs[16]);
1805
    memcpy(&env->pkru, &xsave->pkru_state, sizeof env->pkru);
C
Chao Peng 已提交
1806
#endif
1807 1808 1809
    return 0;
}

1810
static int kvm_get_xcrs(X86CPU *cpu)
1811
{
1812
    CPUX86State *env = &cpu->env;
1813 1814 1815
    int i, ret;
    struct kvm_xcrs xcrs;

1816
    if (!has_xcrs) {
1817
        return 0;
1818
    }
1819

1820
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
1821
    if (ret < 0) {
1822
        return ret;
1823
    }
1824

1825
    for (i = 0; i < xcrs.nr_xcrs; i++) {
1826
        /* Only support xcr0 now */
P
Paolo Bonzini 已提交
1827 1828
        if (xcrs.xcrs[i].xcr == 0) {
            env->xcr0 = xcrs.xcrs[i].value;
1829 1830
            break;
        }
1831
    }
1832 1833 1834
    return 0;
}

1835
static int kvm_get_sregs(X86CPU *cpu)
A
aliguori 已提交
1836
{
1837
    CPUX86State *env = &cpu->env;
A
aliguori 已提交
1838 1839
    struct kvm_sregs sregs;
    uint32_t hflags;
1840
    int bit, i, ret;
A
aliguori 已提交
1841

1842
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
1843
    if (ret < 0) {
A
aliguori 已提交
1844
        return ret;
1845
    }
A
aliguori 已提交
1846

1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    /* There can only be one pending IRQ set in the bitmap at a time, so try
       to find it and save its number instead (-1 for none). */
    env->interrupt_injected = -1;
    for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
        if (sregs.interrupt_bitmap[i]) {
            bit = ctz64(sregs.interrupt_bitmap[i]);
            env->interrupt_injected = i * 64 + bit;
            break;
        }
    }
A
aliguori 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

    get_seg(&env->segs[R_CS], &sregs.cs);
    get_seg(&env->segs[R_DS], &sregs.ds);
    get_seg(&env->segs[R_ES], &sregs.es);
    get_seg(&env->segs[R_FS], &sregs.fs);
    get_seg(&env->segs[R_GS], &sregs.gs);
    get_seg(&env->segs[R_SS], &sregs.ss);

    get_seg(&env->tr, &sregs.tr);
    get_seg(&env->ldt, &sregs.ldt);

    env->idt.limit = sregs.idt.limit;
    env->idt.base = sregs.idt.base;
    env->gdt.limit = sregs.gdt.limit;
    env->gdt.base = sregs.gdt.base;

    env->cr[0] = sregs.cr0;
    env->cr[2] = sregs.cr2;
    env->cr[3] = sregs.cr3;
    env->cr[4] = sregs.cr4;

    env->efer = sregs.efer;
1879 1880

    /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
A
aliguori 已提交
1881

1882 1883 1884 1885 1886
#define HFLAG_COPY_MASK \
    ~( HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \
       HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \
       HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \
       HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)
A
aliguori 已提交
1887

1888 1889
    hflags = env->hflags & HFLAG_COPY_MASK;
    hflags |= (env->segs[R_SS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;
A
aliguori 已提交
1890 1891
    hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);
    hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &
1892
                (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);
A
aliguori 已提交
1893
    hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));
1894 1895 1896 1897

    if (env->cr[4] & CR4_OSFXSR_MASK) {
        hflags |= HF_OSFXSR_MASK;
    }
A
aliguori 已提交
1898 1899 1900 1901 1902 1903 1904 1905 1906

    if (env->efer & MSR_EFER_LMA) {
        hflags |= HF_LMA_MASK;
    }

    if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {
        hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;
    } else {
        hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>
1907
                    (DESC_B_SHIFT - HF_CS32_SHIFT);
A
aliguori 已提交
1908
        hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>
1909 1910 1911 1912 1913 1914 1915 1916
                    (DESC_B_SHIFT - HF_SS32_SHIFT);
        if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK) ||
            !(hflags & HF_CS32_MASK)) {
            hflags |= HF_ADDSEG_MASK;
        } else {
            hflags |= ((env->segs[R_DS].base | env->segs[R_ES].base |
                        env->segs[R_SS].base) != 0) << HF_ADDSEG_SHIFT;
        }
A
aliguori 已提交
1917
    }
1918
    env->hflags = hflags;
A
aliguori 已提交
1919 1920 1921 1922

    return 0;
}

1923
static int kvm_get_msrs(X86CPU *cpu)
A
aliguori 已提交
1924
{
1925
    CPUX86State *env = &cpu->env;
1926
    struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
1927
    int ret, i;
A
aliguori 已提交
1928

1929 1930
    kvm_msr_buf_reset(cpu);

1931 1932 1933 1934
    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
    kvm_msr_entry_add(cpu, MSR_PAT, 0);
1935
    if (has_msr_star) {
1936
        kvm_msr_entry_add(cpu, MSR_STAR, 0);
1937
    }
1938
    if (has_msr_hsave_pa) {
1939
        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
1940
    }
1941
    if (has_msr_tsc_aux) {
1942
        kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
1943
    }
1944
    if (has_msr_tsc_adjust) {
1945
        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
1946
    }
1947
    if (has_msr_tsc_deadline) {
1948
        kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
1949
    }
A
Avi Kivity 已提交
1950
    if (has_msr_misc_enable) {
1951
        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
A
Avi Kivity 已提交
1952
    }
1953
    if (has_msr_smbase) {
1954
        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
1955
    }
1956
    if (has_msr_feature_control) {
1957
        kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
1958
    }
L
Liu Jinsong 已提交
1959
    if (has_msr_bndcfgs) {
1960
        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
L
Liu Jinsong 已提交
1961
    }
1962
    if (has_msr_xss) {
1963
        kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
1964 1965
    }

1966 1967

    if (!env->tsc_valid) {
1968
        kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
1969
        env->tsc_valid = !runstate_is_running();
1970 1971
    }

A
aliguori 已提交
1972
#ifdef TARGET_X86_64
1973
    if (lm_capable_kernel) {
1974 1975 1976 1977
        kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
        kvm_msr_entry_add(cpu, MSR_FMASK, 0);
        kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
1978
    }
A
aliguori 已提交
1979
#endif
1980 1981
    kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
    kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
1982
    if (has_msr_async_pf_en) {
1983
        kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
1984
    }
M
Michael S. Tsirkin 已提交
1985
    if (has_msr_pv_eoi_en) {
1986
        kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
M
Michael S. Tsirkin 已提交
1987
    }
1988
    if (has_msr_kvm_steal_time) {
1989
        kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
1990
    }
P
Paolo Bonzini 已提交
1991
    if (has_msr_architectural_pmu) {
1992 1993 1994 1995
        kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
P
Paolo Bonzini 已提交
1996
        for (i = 0; i < MAX_FIXED_COUNTERS; i++) {
1997
            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
P
Paolo Bonzini 已提交
1998 1999
        }
        for (i = 0; i < num_architectural_pmu_counters; i++) {
2000 2001
            kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
            kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
P
Paolo Bonzini 已提交
2002 2003
        }
    }
2004

2005
    if (env->mcg_cap) {
2006 2007
        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
        kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
2008
        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2009
            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
2010
        }
2011 2012
    }

2013
    if (has_msr_hv_hypercall) {
2014 2015
        kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
        kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
2016
    }
2017
    if (has_msr_hv_vapic) {
2018
        kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
2019
    }
2020
    if (has_msr_hv_tsc) {
2021
        kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
2022
    }
2023 2024 2025 2026
    if (has_msr_hv_crash) {
        int j;

        for (j = 0; j < HV_X64_MSR_CRASH_PARAMS; j++) {
2027
            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
2028 2029
        }
    }
2030
    if (has_msr_hv_runtime) {
2031
        kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
2032
    }
2033 2034 2035
    if (cpu->hyperv_synic) {
        uint32_t msr;

2036 2037 2038 2039
        kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
        kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, 0);
        kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
        kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
2040
        for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
2041
            kvm_msr_entry_add(cpu, msr, 0);
2042 2043
        }
    }
2044 2045 2046 2047 2048
    if (has_msr_hv_stimer) {
        uint32_t msr;

        for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
             msr++) {
2049
            kvm_msr_entry_add(cpu, msr, 0);
2050 2051
        }
    }
2052
    if (has_msr_mtrr) {
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
        kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
2065
        for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2066 2067
            kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
            kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
2068 2069
        }
    }
2070

2071
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
2072
    if (ret < 0) {
A
aliguori 已提交
2073
        return ret;
2074
    }
A
aliguori 已提交
2075

2076
    assert(ret == cpu->kvm_msr_buf->nmsrs);
A
aliguori 已提交
2077
    for (i = 0; i < ret; i++) {
P
Paolo Bonzini 已提交
2078 2079
        uint32_t index = msrs[i].index;
        switch (index) {
A
aliguori 已提交
2080 2081 2082 2083 2084 2085 2086 2087 2088
        case MSR_IA32_SYSENTER_CS:
            env->sysenter_cs = msrs[i].data;
            break;
        case MSR_IA32_SYSENTER_ESP:
            env->sysenter_esp = msrs[i].data;
            break;
        case MSR_IA32_SYSENTER_EIP:
            env->sysenter_eip = msrs[i].data;
            break;
2089 2090 2091
        case MSR_PAT:
            env->pat = msrs[i].data;
            break;
A
aliguori 已提交
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
        case MSR_STAR:
            env->star = msrs[i].data;
            break;
#ifdef TARGET_X86_64
        case MSR_CSTAR:
            env->cstar = msrs[i].data;
            break;
        case MSR_KERNELGSBASE:
            env->kernelgsbase = msrs[i].data;
            break;
        case MSR_FMASK:
            env->fmask = msrs[i].data;
            break;
        case MSR_LSTAR:
            env->lstar = msrs[i].data;
            break;
#endif
        case MSR_IA32_TSC:
            env->tsc = msrs[i].data;
            break;
2112 2113 2114
        case MSR_TSC_AUX:
            env->tsc_aux = msrs[i].data;
            break;
2115 2116 2117
        case MSR_TSC_ADJUST:
            env->tsc_adjust = msrs[i].data;
            break;
2118 2119 2120
        case MSR_IA32_TSCDEADLINE:
            env->tsc_deadline = msrs[i].data;
            break;
2121 2122 2123
        case MSR_VM_HSAVE_PA:
            env->vm_hsave = msrs[i].data;
            break;
2124 2125 2126 2127 2128 2129
        case MSR_KVM_SYSTEM_TIME:
            env->system_time_msr = msrs[i].data;
            break;
        case MSR_KVM_WALL_CLOCK:
            env->wall_clock_msr = msrs[i].data;
            break;
2130 2131 2132 2133 2134 2135
        case MSR_MCG_STATUS:
            env->mcg_status = msrs[i].data;
            break;
        case MSR_MCG_CTL:
            env->mcg_ctl = msrs[i].data;
            break;
A
Avi Kivity 已提交
2136 2137 2138
        case MSR_IA32_MISC_ENABLE:
            env->msr_ia32_misc_enable = msrs[i].data;
            break;
2139 2140 2141
        case MSR_IA32_SMBASE:
            env->smbase = msrs[i].data;
            break;
2142 2143
        case MSR_IA32_FEATURE_CONTROL:
            env->msr_ia32_feature_control = msrs[i].data;
2144
            break;
L
Liu Jinsong 已提交
2145 2146 2147
        case MSR_IA32_BNDCFGS:
            env->msr_bndcfgs = msrs[i].data;
            break;
2148 2149 2150
        case MSR_IA32_XSS:
            env->xss = msrs[i].data;
            break;
2151 2152 2153 2154 2155
        default:
            if (msrs[i].index >= MSR_MC0_CTL &&
                msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {
                env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;
            }
H
Hidetoshi Seto 已提交
2156
            break;
2157 2158 2159
        case MSR_KVM_ASYNC_PF_EN:
            env->async_pf_en_msr = msrs[i].data;
            break;
M
Michael S. Tsirkin 已提交
2160 2161 2162
        case MSR_KVM_PV_EOI_EN:
            env->pv_eoi_en_msr = msrs[i].data;
            break;
2163 2164 2165
        case MSR_KVM_STEAL_TIME:
            env->steal_time_msr = msrs[i].data;
            break;
P
Paolo Bonzini 已提交
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
        case MSR_CORE_PERF_FIXED_CTR_CTRL:
            env->msr_fixed_ctr_ctrl = msrs[i].data;
            break;
        case MSR_CORE_PERF_GLOBAL_CTRL:
            env->msr_global_ctrl = msrs[i].data;
            break;
        case MSR_CORE_PERF_GLOBAL_STATUS:
            env->msr_global_status = msrs[i].data;
            break;
        case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
            env->msr_global_ovf_ctrl = msrs[i].data;
            break;
        case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:
            env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;
            break;
        case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:
            env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;
            break;
        case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:
            env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;
            break;
2187 2188 2189 2190 2191 2192
        case HV_X64_MSR_HYPERCALL:
            env->msr_hv_hypercall = msrs[i].data;
            break;
        case HV_X64_MSR_GUEST_OS_ID:
            env->msr_hv_guest_os_id = msrs[i].data;
            break;
2193 2194 2195
        case HV_X64_MSR_APIC_ASSIST_PAGE:
            env->msr_hv_vapic = msrs[i].data;
            break;
2196 2197 2198
        case HV_X64_MSR_REFERENCE_TSC:
            env->msr_hv_tsc = msrs[i].data;
            break;
2199 2200 2201
        case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
            env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;
            break;
2202 2203 2204
        case HV_X64_MSR_VP_RUNTIME:
            env->msr_hv_runtime = msrs[i].data;
            break;
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
        case HV_X64_MSR_SCONTROL:
            env->msr_hv_synic_control = msrs[i].data;
            break;
        case HV_X64_MSR_SVERSION:
            env->msr_hv_synic_version = msrs[i].data;
            break;
        case HV_X64_MSR_SIEFP:
            env->msr_hv_synic_evt_page = msrs[i].data;
            break;
        case HV_X64_MSR_SIMP:
            env->msr_hv_synic_msg_page = msrs[i].data;
            break;
        case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
            env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
            break;
        case HV_X64_MSR_STIMER0_CONFIG:
        case HV_X64_MSR_STIMER1_CONFIG:
        case HV_X64_MSR_STIMER2_CONFIG:
        case HV_X64_MSR_STIMER3_CONFIG:
            env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =
                                msrs[i].data;
            break;
        case HV_X64_MSR_STIMER0_COUNT:
        case HV_X64_MSR_STIMER1_COUNT:
        case HV_X64_MSR_STIMER2_COUNT:
        case HV_X64_MSR_STIMER3_COUNT:
            env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =
                                msrs[i].data;
2233
            break;
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
        case MSR_MTRRdefType:
            env->mtrr_deftype = msrs[i].data;
            break;
        case MSR_MTRRfix64K_00000:
            env->mtrr_fixed[0] = msrs[i].data;
            break;
        case MSR_MTRRfix16K_80000:
            env->mtrr_fixed[1] = msrs[i].data;
            break;
        case MSR_MTRRfix16K_A0000:
            env->mtrr_fixed[2] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_C0000:
            env->mtrr_fixed[3] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_C8000:
            env->mtrr_fixed[4] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_D0000:
            env->mtrr_fixed[5] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_D8000:
            env->mtrr_fixed[6] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_E0000:
            env->mtrr_fixed[7] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_E8000:
            env->mtrr_fixed[8] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_F0000:
            env->mtrr_fixed[9] = msrs[i].data;
            break;
        case MSR_MTRRfix4K_F8000:
            env->mtrr_fixed[10] = msrs[i].data;
            break;
        case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):
            if (index & 1) {
                env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data;
            } else {
                env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;
            }
            break;
A
aliguori 已提交
2277 2278 2279 2280 2281 2282
        }
    }

    return 0;
}

2283
static int kvm_put_mp_state(X86CPU *cpu)
2284
{
2285
    struct kvm_mp_state mp_state = { .mp_state = cpu->env.mp_state };
2286

2287
    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MP_STATE, &mp_state);
2288 2289
}

2290
static int kvm_get_mp_state(X86CPU *cpu)
2291
{
2292
    CPUState *cs = CPU(cpu);
2293
    CPUX86State *env = &cpu->env;
2294 2295 2296
    struct kvm_mp_state mp_state;
    int ret;

2297
    ret = kvm_vcpu_ioctl(cs, KVM_GET_MP_STATE, &mp_state);
2298 2299 2300 2301
    if (ret < 0) {
        return ret;
    }
    env->mp_state = mp_state.mp_state;
2302
    if (kvm_irqchip_in_kernel()) {
2303
        cs->halted = (mp_state.mp_state == KVM_MP_STATE_HALTED);
2304
    }
2305 2306 2307
    return 0;
}

2308
static int kvm_get_apic(X86CPU *cpu)
2309
{
2310
    DeviceState *apic = cpu->apic_state;
2311 2312 2313
    struct kvm_lapic_state kapic;
    int ret;

2314
    if (apic && kvm_irqchip_in_kernel()) {
2315
        ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_LAPIC, &kapic);
2316 2317 2318 2319 2320 2321 2322 2323 2324
        if (ret < 0) {
            return ret;
        }

        kvm_get_apic_state(apic, &kapic);
    }
    return 0;
}

2325
static int kvm_put_apic(X86CPU *cpu)
2326
{
2327
    DeviceState *apic = cpu->apic_state;
2328 2329
    struct kvm_lapic_state kapic;

2330
    if (apic && kvm_irqchip_in_kernel()) {
2331 2332
        kvm_put_apic_state(apic, &kapic);

2333
        return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_LAPIC, &kapic);
2334 2335 2336 2337
    }
    return 0;
}

2338
static int kvm_put_vcpu_events(X86CPU *cpu, int level)
2339
{
2340
    CPUState *cs = CPU(cpu);
2341
    CPUX86State *env = &cpu->env;
2342
    struct kvm_vcpu_events events = {};
2343 2344 2345 2346 2347

    if (!kvm_has_vcpu_events()) {
        return 0;
    }

2348 2349
    events.exception.injected = (env->exception_injected >= 0);
    events.exception.nr = env->exception_injected;
2350 2351
    events.exception.has_error_code = env->has_error_code;
    events.exception.error_code = env->error_code;
2352
    events.exception.pad = 0;
2353 2354 2355 2356 2357 2358 2359 2360

    events.interrupt.injected = (env->interrupt_injected >= 0);
    events.interrupt.nr = env->interrupt_injected;
    events.interrupt.soft = env->soft_interrupt;

    events.nmi.injected = env->nmi_injected;
    events.nmi.pending = env->nmi_pending;
    events.nmi.masked = !!(env->hflags2 & HF2_NMI_MASK);
2361
    events.nmi.pad = 0;
2362 2363 2364

    events.sipi_vector = env->sipi_vector;

2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    if (has_msr_smbase) {
        events.smi.smm = !!(env->hflags & HF_SMM_MASK);
        events.smi.smm_inside_nmi = !!(env->hflags2 & HF2_SMM_INSIDE_NMI_MASK);
        if (kvm_irqchip_in_kernel()) {
            /* As soon as these are moved to the kernel, remove them
             * from cs->interrupt_request.
             */
            events.smi.pending = cs->interrupt_request & CPU_INTERRUPT_SMI;
            events.smi.latched_init = cs->interrupt_request & CPU_INTERRUPT_INIT;
            cs->interrupt_request &= ~(CPU_INTERRUPT_INIT | CPU_INTERRUPT_SMI);
        } else {
            /* Keep these in cs->interrupt_request.  */
            events.smi.pending = 0;
            events.smi.latched_init = 0;
        }
        events.flags |= KVM_VCPUEVENT_VALID_SMM;
    }

2383 2384 2385 2386 2387
    events.flags = 0;
    if (level >= KVM_PUT_RESET_STATE) {
        events.flags |=
            KVM_VCPUEVENT_VALID_NMI_PENDING | KVM_VCPUEVENT_VALID_SIPI_VECTOR;
    }
2388

2389
    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_VCPU_EVENTS, &events);
2390 2391
}

2392
static int kvm_get_vcpu_events(X86CPU *cpu)
2393
{
2394
    CPUX86State *env = &cpu->env;
2395 2396 2397 2398 2399 2400 2401
    struct kvm_vcpu_events events;
    int ret;

    if (!kvm_has_vcpu_events()) {
        return 0;
    }

2402
    memset(&events, 0, sizeof(events));
2403
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_VCPU_EVENTS, &events);
2404 2405 2406
    if (ret < 0) {
       return ret;
    }
2407
    env->exception_injected =
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
       events.exception.injected ? events.exception.nr : -1;
    env->has_error_code = events.exception.has_error_code;
    env->error_code = events.exception.error_code;

    env->interrupt_injected =
        events.interrupt.injected ? events.interrupt.nr : -1;
    env->soft_interrupt = events.interrupt.soft;

    env->nmi_injected = events.nmi.injected;
    env->nmi_pending = events.nmi.pending;
    if (events.nmi.masked) {
        env->hflags2 |= HF2_NMI_MASK;
    } else {
        env->hflags2 &= ~HF2_NMI_MASK;
    }

2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
    if (events.flags & KVM_VCPUEVENT_VALID_SMM) {
        if (events.smi.smm) {
            env->hflags |= HF_SMM_MASK;
        } else {
            env->hflags &= ~HF_SMM_MASK;
        }
        if (events.smi.pending) {
            cpu_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
        } else {
            cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_SMI);
        }
        if (events.smi.smm_inside_nmi) {
            env->hflags2 |= HF2_SMM_INSIDE_NMI_MASK;
        } else {
            env->hflags2 &= ~HF2_SMM_INSIDE_NMI_MASK;
        }
        if (events.smi.latched_init) {
            cpu_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
        } else {
            cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_INIT);
        }
    }

2447 2448 2449 2450 2451
    env->sipi_vector = events.sipi_vector;

    return 0;
}

2452
static int kvm_guest_debug_workarounds(X86CPU *cpu)
2453
{
2454
    CPUState *cs = CPU(cpu);
2455
    CPUX86State *env = &cpu->env;
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
    int ret = 0;
    unsigned long reinject_trap = 0;

    if (!kvm_has_vcpu_events()) {
        if (env->exception_injected == 1) {
            reinject_trap = KVM_GUESTDBG_INJECT_DB;
        } else if (env->exception_injected == 3) {
            reinject_trap = KVM_GUESTDBG_INJECT_BP;
        }
        env->exception_injected = -1;
    }

    /*
     * Kernels before KVM_CAP_X86_ROBUST_SINGLESTEP overwrote flags.TF
     * injected via SET_GUEST_DEBUG while updating GP regs. Work around this
     * by updating the debug state once again if single-stepping is on.
     * Another reason to call kvm_update_guest_debug here is a pending debug
     * trap raise by the guest. On kernels without SET_VCPU_EVENTS we have to
     * reinject them via SET_GUEST_DEBUG.
     */
    if (reinject_trap ||
2477
        (!kvm_has_robust_singlestep() && cs->singlestep_enabled)) {
2478
        ret = kvm_update_guest_debug(cs, reinject_trap);
2479 2480 2481 2482
    }
    return ret;
}

2483
static int kvm_put_debugregs(X86CPU *cpu)
2484
{
2485
    CPUX86State *env = &cpu->env;
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
    struct kvm_debugregs dbgregs;
    int i;

    if (!kvm_has_debugregs()) {
        return 0;
    }

    for (i = 0; i < 4; i++) {
        dbgregs.db[i] = env->dr[i];
    }
    dbgregs.dr6 = env->dr[6];
    dbgregs.dr7 = env->dr[7];
    dbgregs.flags = 0;

2500
    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_DEBUGREGS, &dbgregs);
2501 2502
}

2503
static int kvm_get_debugregs(X86CPU *cpu)
2504
{
2505
    CPUX86State *env = &cpu->env;
2506 2507 2508 2509 2510 2511 2512
    struct kvm_debugregs dbgregs;
    int i, ret;

    if (!kvm_has_debugregs()) {
        return 0;
    }

2513
    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_DEBUGREGS, &dbgregs);
2514
    if (ret < 0) {
2515
        return ret;
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
    }
    for (i = 0; i < 4; i++) {
        env->dr[i] = dbgregs.db[i];
    }
    env->dr[4] = env->dr[6] = dbgregs.dr6;
    env->dr[5] = env->dr[7] = dbgregs.dr7;

    return 0;
}

A
Andreas Färber 已提交
2526
int kvm_arch_put_registers(CPUState *cpu, int level)
A
aliguori 已提交
2527
{
A
Andreas Färber 已提交
2528
    X86CPU *x86_cpu = X86_CPU(cpu);
A
aliguori 已提交
2529 2530
    int ret;

2531
    assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
2532

2533
    if (level >= KVM_PUT_RESET_STATE) {
2534 2535 2536 2537 2538 2539
        ret = kvm_put_msr_feature_control(x86_cpu);
        if (ret < 0) {
            return ret;
        }
    }

2540 2541 2542 2543 2544 2545 2546 2547 2548
    if (level == KVM_PUT_FULL_STATE) {
        /* We don't check for kvm_arch_set_tsc_khz() errors here,
         * because TSC frequency mismatch shouldn't abort migration,
         * unless the user explicitly asked for a more strict TSC
         * setting (e.g. using an explicit "tsc-freq" option).
         */
        kvm_arch_set_tsc_khz(cpu);
    }

2549
    ret = kvm_getput_regs(x86_cpu, 1);
2550
    if (ret < 0) {
A
aliguori 已提交
2551
        return ret;
2552
    }
2553
    ret = kvm_put_xsave(x86_cpu);
2554
    if (ret < 0) {
2555
        return ret;
2556
    }
2557
    ret = kvm_put_xcrs(x86_cpu);
2558
    if (ret < 0) {
A
aliguori 已提交
2559
        return ret;
2560
    }
2561
    ret = kvm_put_sregs(x86_cpu);
2562
    if (ret < 0) {
A
aliguori 已提交
2563
        return ret;
2564
    }
2565
    /* must be before kvm_put_msrs */
2566
    ret = kvm_inject_mce_oldstyle(x86_cpu);
2567 2568 2569
    if (ret < 0) {
        return ret;
    }
2570
    ret = kvm_put_msrs(x86_cpu, level);
2571
    if (ret < 0) {
A
aliguori 已提交
2572
        return ret;
2573
    }
2574
    if (level >= KVM_PUT_RESET_STATE) {
2575
        ret = kvm_put_mp_state(x86_cpu);
2576
        if (ret < 0) {
2577
            return ret;
2578
        }
2579
        ret = kvm_put_apic(x86_cpu);
2580 2581 2582
        if (ret < 0) {
            return ret;
        }
2583
    }
2584 2585 2586 2587 2588 2589

    ret = kvm_put_tscdeadline_msr(x86_cpu);
    if (ret < 0) {
        return ret;
    }

2590
    ret = kvm_put_vcpu_events(x86_cpu, level);
2591
    if (ret < 0) {
2592
        return ret;
2593
    }
2594
    ret = kvm_put_debugregs(x86_cpu);
2595
    if (ret < 0) {
2596
        return ret;
2597
    }
2598
    /* must be last */
2599
    ret = kvm_guest_debug_workarounds(x86_cpu);
2600
    if (ret < 0) {
2601
        return ret;
2602
    }
A
aliguori 已提交
2603 2604 2605
    return 0;
}

A
Andreas Färber 已提交
2606
int kvm_arch_get_registers(CPUState *cs)
A
aliguori 已提交
2607
{
A
Andreas Färber 已提交
2608
    X86CPU *cpu = X86_CPU(cs);
A
aliguori 已提交
2609 2610
    int ret;

A
Andreas Färber 已提交
2611
    assert(cpu_is_stopped(cs) || qemu_cpu_is_self(cs));
2612

2613
    ret = kvm_getput_regs(cpu, 0);
2614
    if (ret < 0) {
2615
        goto out;
2616
    }
2617
    ret = kvm_get_xsave(cpu);
2618
    if (ret < 0) {
2619
        goto out;
2620
    }
2621
    ret = kvm_get_xcrs(cpu);
2622
    if (ret < 0) {
2623
        goto out;
2624
    }
2625
    ret = kvm_get_sregs(cpu);
2626
    if (ret < 0) {
2627
        goto out;
2628
    }
2629
    ret = kvm_get_msrs(cpu);
2630
    if (ret < 0) {
2631
        goto out;
2632
    }
2633
    ret = kvm_get_mp_state(cpu);
2634
    if (ret < 0) {
2635
        goto out;
2636
    }
2637
    ret = kvm_get_apic(cpu);
2638
    if (ret < 0) {
2639
        goto out;
2640
    }
2641
    ret = kvm_get_vcpu_events(cpu);
2642
    if (ret < 0) {
2643
        goto out;
2644
    }
2645
    ret = kvm_get_debugregs(cpu);
2646
    if (ret < 0) {
2647
        goto out;
2648
    }
2649 2650 2651 2652
    ret = 0;
 out:
    cpu_sync_bndcs_hflags(&cpu->env);
    return ret;
A
aliguori 已提交
2653 2654
}

A
Andreas Färber 已提交
2655
void kvm_arch_pre_run(CPUState *cpu, struct kvm_run *run)
A
aliguori 已提交
2656
{
A
Andreas Färber 已提交
2657 2658
    X86CPU *x86_cpu = X86_CPU(cpu);
    CPUX86State *env = &x86_cpu->env;
2659 2660
    int ret;

2661
    /* Inject NMI */
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
    if (cpu->interrupt_request & (CPU_INTERRUPT_NMI | CPU_INTERRUPT_SMI)) {
        if (cpu->interrupt_request & CPU_INTERRUPT_NMI) {
            qemu_mutex_lock_iothread();
            cpu->interrupt_request &= ~CPU_INTERRUPT_NMI;
            qemu_mutex_unlock_iothread();
            DPRINTF("injected NMI\n");
            ret = kvm_vcpu_ioctl(cpu, KVM_NMI);
            if (ret < 0) {
                fprintf(stderr, "KVM: injection failed, NMI lost (%s)\n",
                        strerror(-ret));
            }
        }
        if (cpu->interrupt_request & CPU_INTERRUPT_SMI) {
            qemu_mutex_lock_iothread();
            cpu->interrupt_request &= ~CPU_INTERRUPT_SMI;
            qemu_mutex_unlock_iothread();
            DPRINTF("injected SMI\n");
            ret = kvm_vcpu_ioctl(cpu, KVM_SMI);
            if (ret < 0) {
                fprintf(stderr, "KVM: injection failed, SMI lost (%s)\n",
                        strerror(-ret));
            }
2684
        }
2685 2686
    }

2687
    if (!kvm_pic_in_kernel()) {
2688 2689 2690
        qemu_mutex_lock_iothread();
    }

2691 2692 2693 2694 2695
    /* Force the VCPU out of its inner loop to process any INIT requests
     * or (for userspace APIC, but it is cheap to combine the checks here)
     * pending TPR access reports.
     */
    if (cpu->interrupt_request & (CPU_INTERRUPT_INIT | CPU_INTERRUPT_TPR)) {
2696 2697 2698 2699 2700 2701 2702
        if ((cpu->interrupt_request & CPU_INTERRUPT_INIT) &&
            !(env->hflags & HF_SMM_MASK)) {
            cpu->exit_request = 1;
        }
        if (cpu->interrupt_request & CPU_INTERRUPT_TPR) {
            cpu->exit_request = 1;
        }
2703
    }
A
aliguori 已提交
2704

2705
    if (!kvm_pic_in_kernel()) {
2706 2707
        /* Try to inject an interrupt if the guest can accept it */
        if (run->ready_for_interrupt_injection &&
2708
            (cpu->interrupt_request & CPU_INTERRUPT_HARD) &&
2709 2710 2711
            (env->eflags & IF_MASK)) {
            int irq;

2712
            cpu->interrupt_request &= ~CPU_INTERRUPT_HARD;
2713 2714 2715 2716 2717 2718
            irq = cpu_get_pic_interrupt(env);
            if (irq >= 0) {
                struct kvm_interrupt intr;

                intr.irq = irq;
                DPRINTF("injected interrupt %d\n", irq);
2719
                ret = kvm_vcpu_ioctl(cpu, KVM_INTERRUPT, &intr);
2720 2721 2722 2723 2724
                if (ret < 0) {
                    fprintf(stderr,
                            "KVM: injection failed, interrupt lost (%s)\n",
                            strerror(-ret));
                }
2725 2726
            }
        }
A
aliguori 已提交
2727

2728 2729 2730 2731
        /* If we have an interrupt but the guest is not ready to receive an
         * interrupt, request an interrupt window exit.  This will
         * cause a return to userspace as soon as the guest is ready to
         * receive interrupts. */
2732
        if ((cpu->interrupt_request & CPU_INTERRUPT_HARD)) {
2733 2734 2735 2736 2737 2738
            run->request_interrupt_window = 1;
        } else {
            run->request_interrupt_window = 0;
        }

        DPRINTF("setting tpr\n");
2739
        run->cr8 = cpu_get_apic_tpr(x86_cpu->apic_state);
2740 2741

        qemu_mutex_unlock_iothread();
2742
    }
A
aliguori 已提交
2743 2744
}

2745
MemTxAttrs kvm_arch_post_run(CPUState *cpu, struct kvm_run *run)
A
aliguori 已提交
2746
{
A
Andreas Färber 已提交
2747 2748 2749
    X86CPU *x86_cpu = X86_CPU(cpu);
    CPUX86State *env = &x86_cpu->env;

2750 2751 2752 2753 2754
    if (run->flags & KVM_RUN_X86_SMM) {
        env->hflags |= HF_SMM_MASK;
    } else {
        env->hflags &= HF_SMM_MASK;
    }
2755
    if (run->if_flag) {
A
aliguori 已提交
2756
        env->eflags |= IF_MASK;
2757
    } else {
A
aliguori 已提交
2758
        env->eflags &= ~IF_MASK;
2759
    }
2760 2761 2762 2763 2764 2765

    /* We need to protect the apic state against concurrent accesses from
     * different threads in case the userspace irqchip is used. */
    if (!kvm_irqchip_in_kernel()) {
        qemu_mutex_lock_iothread();
    }
2766 2767
    cpu_set_apic_tpr(x86_cpu->apic_state, run->cr8);
    cpu_set_apic_base(x86_cpu->apic_state, run->apic_base);
2768 2769 2770
    if (!kvm_irqchip_in_kernel()) {
        qemu_mutex_unlock_iothread();
    }
2771
    return cpu_get_mem_attrs(env);
A
aliguori 已提交
2772 2773
}

A
Andreas Färber 已提交
2774
int kvm_arch_process_async_events(CPUState *cs)
M
Marcelo Tosatti 已提交
2775
{
A
Andreas Färber 已提交
2776 2777
    X86CPU *cpu = X86_CPU(cs);
    CPUX86State *env = &cpu->env;
2778

2779
    if (cs->interrupt_request & CPU_INTERRUPT_MCE) {
2780 2781 2782
        /* We must not raise CPU_INTERRUPT_MCE if it's not supported. */
        assert(env->mcg_cap);

2783
        cs->interrupt_request &= ~CPU_INTERRUPT_MCE;
2784

2785
        kvm_cpu_synchronize_state(cs);
2786 2787 2788 2789

        if (env->exception_injected == EXCP08_DBLE) {
            /* this means triple fault */
            qemu_system_reset_request();
2790
            cs->exit_request = 1;
2791 2792 2793 2794 2795
            return 0;
        }
        env->exception_injected = EXCP12_MCHK;
        env->has_error_code = 0;

2796
        cs->halted = 0;
2797 2798 2799 2800 2801
        if (kvm_irqchip_in_kernel() && env->mp_state == KVM_MP_STATE_HALTED) {
            env->mp_state = KVM_MP_STATE_RUNNABLE;
        }
    }

2802 2803
    if ((cs->interrupt_request & CPU_INTERRUPT_INIT) &&
        !(env->hflags & HF_SMM_MASK)) {
2804 2805 2806 2807
        kvm_cpu_synchronize_state(cs);
        do_cpu_init(cpu);
    }

2808 2809 2810 2811
    if (kvm_irqchip_in_kernel()) {
        return 0;
    }

2812 2813
    if (cs->interrupt_request & CPU_INTERRUPT_POLL) {
        cs->interrupt_request &= ~CPU_INTERRUPT_POLL;
2814
        apic_poll_irq(cpu->apic_state);
2815
    }
2816
    if (((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
2817
         (env->eflags & IF_MASK)) ||
2818 2819
        (cs->interrupt_request & CPU_INTERRUPT_NMI)) {
        cs->halted = 0;
2820
    }
2821
    if (cs->interrupt_request & CPU_INTERRUPT_SIPI) {
2822
        kvm_cpu_synchronize_state(cs);
2823
        do_cpu_sipi(cpu);
M
Marcelo Tosatti 已提交
2824
    }
2825 2826
    if (cs->interrupt_request & CPU_INTERRUPT_TPR) {
        cs->interrupt_request &= ~CPU_INTERRUPT_TPR;
2827
        kvm_cpu_synchronize_state(cs);
2828
        apic_handle_tpr_access_report(cpu->apic_state, env->eip,
2829 2830
                                      env->tpr_access_type);
    }
M
Marcelo Tosatti 已提交
2831

2832
    return cs->halted;
M
Marcelo Tosatti 已提交
2833 2834
}

2835
static int kvm_handle_halt(X86CPU *cpu)
A
aliguori 已提交
2836
{
2837
    CPUState *cs = CPU(cpu);
2838 2839
    CPUX86State *env = &cpu->env;

2840
    if (!((cs->interrupt_request & CPU_INTERRUPT_HARD) &&
A
aliguori 已提交
2841
          (env->eflags & IF_MASK)) &&
2842 2843
        !(cs->interrupt_request & CPU_INTERRUPT_NMI)) {
        cs->halted = 1;
2844
        return EXCP_HLT;
A
aliguori 已提交
2845 2846
    }

2847
    return 0;
A
aliguori 已提交
2848 2849
}

A
Andreas Färber 已提交
2850
static int kvm_handle_tpr_access(X86CPU *cpu)
2851
{
A
Andreas Färber 已提交
2852 2853
    CPUState *cs = CPU(cpu);
    struct kvm_run *run = cs->kvm_run;
2854

2855
    apic_handle_tpr_access_report(cpu->apic_state, run->tpr_access.rip,
2856 2857 2858 2859 2860
                                  run->tpr_access.is_write ? TPR_ACCESS_WRITE
                                                           : TPR_ACCESS_READ);
    return 1;
}

2861
int kvm_arch_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2862
{
2863
    static const uint8_t int3 = 0xcc;
2864

2865 2866
    if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 0) ||
        cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&int3, 1, 1)) {
2867
        return -EINVAL;
2868
    }
2869 2870 2871
    return 0;
}

2872
int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)
2873 2874 2875
{
    uint8_t int3;

2876 2877
    if (cpu_memory_rw_debug(cs, bp->pc, &int3, 1, 0) || int3 != 0xcc ||
        cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1)) {
2878
        return -EINVAL;
2879
    }
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
    return 0;
}

static struct {
    target_ulong addr;
    int len;
    int type;
} hw_breakpoint[4];

static int nb_hw_breakpoint;

static int find_hw_breakpoint(target_ulong addr, int len, int type)
{
    int n;

2895
    for (n = 0; n < nb_hw_breakpoint; n++) {
2896
        if (hw_breakpoint[n].addr == addr && hw_breakpoint[n].type == type &&
2897
            (hw_breakpoint[n].len == len || len == -1)) {
2898
            return n;
2899 2900
        }
    }
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
    return -1;
}

int kvm_arch_insert_hw_breakpoint(target_ulong addr,
                                  target_ulong len, int type)
{
    switch (type) {
    case GDB_BREAKPOINT_HW:
        len = 1;
        break;
    case GDB_WATCHPOINT_WRITE:
    case GDB_WATCHPOINT_ACCESS:
        switch (len) {
        case 1:
            break;
        case 2:
        case 4:
        case 8:
2919
            if (addr & (len - 1)) {
2920
                return -EINVAL;
2921
            }
2922 2923 2924 2925 2926 2927 2928 2929 2930
            break;
        default:
            return -EINVAL;
        }
        break;
    default:
        return -ENOSYS;
    }

2931
    if (nb_hw_breakpoint == 4) {
2932
        return -ENOBUFS;
2933 2934
    }
    if (find_hw_breakpoint(addr, len, type) >= 0) {
2935
        return -EEXIST;
2936
    }
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
    hw_breakpoint[nb_hw_breakpoint].addr = addr;
    hw_breakpoint[nb_hw_breakpoint].len = len;
    hw_breakpoint[nb_hw_breakpoint].type = type;
    nb_hw_breakpoint++;

    return 0;
}

int kvm_arch_remove_hw_breakpoint(target_ulong addr,
                                  target_ulong len, int type)
{
    int n;

    n = find_hw_breakpoint(addr, (type == GDB_BREAKPOINT_HW) ? 1 : len, type);
2951
    if (n < 0) {
2952
        return -ENOENT;
2953
    }
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
    nb_hw_breakpoint--;
    hw_breakpoint[n] = hw_breakpoint[nb_hw_breakpoint];

    return 0;
}

void kvm_arch_remove_all_hw_breakpoints(void)
{
    nb_hw_breakpoint = 0;
}

static CPUWatchpoint hw_watchpoint;

2967
static int kvm_handle_debug(X86CPU *cpu,
B
Blue Swirl 已提交
2968
                            struct kvm_debug_exit_arch *arch_info)
2969
{
2970
    CPUState *cs = CPU(cpu);
2971
    CPUX86State *env = &cpu->env;
2972
    int ret = 0;
2973 2974 2975 2976
    int n;

    if (arch_info->exception == 1) {
        if (arch_info->dr6 & (1 << 14)) {
2977
            if (cs->singlestep_enabled) {
2978
                ret = EXCP_DEBUG;
2979
            }
2980
        } else {
2981 2982
            for (n = 0; n < 4; n++) {
                if (arch_info->dr6 & (1 << n)) {
2983 2984
                    switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {
                    case 0x0:
2985
                        ret = EXCP_DEBUG;
2986 2987
                        break;
                    case 0x1:
2988
                        ret = EXCP_DEBUG;
2989
                        cs->watchpoint_hit = &hw_watchpoint;
2990 2991 2992 2993
                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;
                        hw_watchpoint.flags = BP_MEM_WRITE;
                        break;
                    case 0x3:
2994
                        ret = EXCP_DEBUG;
2995
                        cs->watchpoint_hit = &hw_watchpoint;
2996 2997 2998 2999
                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;
                        hw_watchpoint.flags = BP_MEM_ACCESS;
                        break;
                    }
3000 3001
                }
            }
3002
        }
3003
    } else if (kvm_find_sw_breakpoint(cs, arch_info->pc)) {
3004
        ret = EXCP_DEBUG;
3005
    }
3006
    if (ret == 0) {
3007
        cpu_synchronize_state(cs);
B
Blue Swirl 已提交
3008
        assert(env->exception_injected == -1);
3009

3010
        /* pass to guest */
B
Blue Swirl 已提交
3011 3012
        env->exception_injected = arch_info->exception;
        env->has_error_code = 0;
3013
    }
3014

3015
    return ret;
3016 3017
}

A
Andreas Färber 已提交
3018
void kvm_arch_update_guest_debug(CPUState *cpu, struct kvm_guest_debug *dbg)
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029
{
    const uint8_t type_code[] = {
        [GDB_BREAKPOINT_HW] = 0x0,
        [GDB_WATCHPOINT_WRITE] = 0x1,
        [GDB_WATCHPOINT_ACCESS] = 0x3
    };
    const uint8_t len_code[] = {
        [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2
    };
    int n;

3030
    if (kvm_sw_breakpoints_active(cpu)) {
3031
        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;
3032
    }
3033 3034 3035 3036 3037 3038 3039
    if (nb_hw_breakpoint > 0) {
        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
        dbg->arch.debugreg[7] = 0x0600;
        for (n = 0; n < nb_hw_breakpoint; n++) {
            dbg->arch.debugreg[n] = hw_breakpoint[n].addr;
            dbg->arch.debugreg[7] |= (2 << (n * 2)) |
                (type_code[hw_breakpoint[n].type] << (16 + n*4)) |
3040
                ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));
3041 3042 3043
        }
    }
}
3044

3045 3046 3047 3048 3049 3050 3051 3052 3053 3054
static bool host_supports_vmx(void)
{
    uint32_t ecx, unused;

    host_cpuid(1, 0, &unused, &unused, &ecx, &unused);
    return ecx & CPUID_EXT_VMX;
}

#define VMX_INVALID_GUEST_STATE 0x80000021

A
Andreas Färber 已提交
3055
int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)
3056
{
A
Andreas Färber 已提交
3057
    X86CPU *cpu = X86_CPU(cs);
3058 3059 3060 3061 3062 3063
    uint64_t code;
    int ret;

    switch (run->exit_reason) {
    case KVM_EXIT_HLT:
        DPRINTF("handle_hlt\n");
3064
        qemu_mutex_lock_iothread();
3065
        ret = kvm_handle_halt(cpu);
3066
        qemu_mutex_unlock_iothread();
3067 3068 3069 3070
        break;
    case KVM_EXIT_SET_TPR:
        ret = 0;
        break;
3071
    case KVM_EXIT_TPR_ACCESS:
3072
        qemu_mutex_lock_iothread();
A
Andreas Färber 已提交
3073
        ret = kvm_handle_tpr_access(cpu);
3074
        qemu_mutex_unlock_iothread();
3075
        break;
3076 3077 3078 3079 3080 3081
    case KVM_EXIT_FAIL_ENTRY:
        code = run->fail_entry.hardware_entry_failure_reason;
        fprintf(stderr, "KVM: entry failed, hardware error 0x%" PRIx64 "\n",
                code);
        if (host_supports_vmx() && code == VMX_INVALID_GUEST_STATE) {
            fprintf(stderr,
V
Vagrant Cascadian 已提交
3082
                    "\nIf you're running a guest on an Intel machine without "
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
                        "unrestricted mode\n"
                    "support, the failure can be most likely due to the guest "
                        "entering an invalid\n"
                    "state for Intel VT. For example, the guest maybe running "
                        "in big real mode\n"
                    "which is not supported on less recent Intel processors."
                        "\n\n");
        }
        ret = -1;
        break;
    case KVM_EXIT_EXCEPTION:
        fprintf(stderr, "KVM: exception %d exit (error code 0x%x)\n",
                run->ex.exception, run->ex.error_code);
        ret = -1;
        break;
3098 3099
    case KVM_EXIT_DEBUG:
        DPRINTF("kvm_exit_debug\n");
3100
        qemu_mutex_lock_iothread();
3101
        ret = kvm_handle_debug(cpu, &run->debug.arch);
3102
        qemu_mutex_unlock_iothread();
3103
        break;
3104 3105 3106
    case KVM_EXIT_HYPERV:
        ret = kvm_hv_handle_exit(cpu, &run->hyperv);
        break;
3107 3108 3109 3110
    case KVM_EXIT_IOAPIC_EOI:
        ioapic_eoi_broadcast(run->eoi.vector);
        ret = 0;
        break;
3111 3112 3113 3114 3115 3116 3117 3118 3119
    default:
        fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason);
        ret = -1;
        break;
    }

    return ret;
}

A
Andreas Färber 已提交
3120
bool kvm_arch_stop_on_emulation_error(CPUState *cs)
3121
{
A
Andreas Färber 已提交
3122 3123 3124
    X86CPU *cpu = X86_CPU(cs);
    CPUX86State *env = &cpu->env;

3125
    kvm_cpu_synchronize_state(cs);
3126 3127
    return !(env->cr[0] & CR0_PE_MASK) ||
           ((env->segs[R_CS].selector  & 3) != 3);
3128
}
3129 3130 3131 3132 3133 3134 3135 3136 3137 3138

void kvm_arch_init_irq_routing(KVMState *s)
{
    if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
        /* If kernel can't do irq routing, interrupt source
         * override 0->2 cannot be set up as required by HPET.
         * So we have to disable it.
         */
        no_hpet = 1;
    }
3139
    /* We know at this point that we're using the in-kernel
3140
     * irqchip, so we can use irqfds, and on x86 we know
3141
     * we can use msi via irqfd and GSI routing.
3142
     */
3143
    kvm_msi_via_irqfd_allowed = true;
3144
    kvm_gsi_routing_allowed = true;
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177

    if (kvm_irqchip_is_split()) {
        int i;

        /* If the ioapic is in QEMU and the lapics are in KVM, reserve
           MSI routes for signaling interrupts to the local apics. */
        for (i = 0; i < IOAPIC_NUM_PINS; i++) {
            struct MSIMessage msg = { 0x0, 0x0 };
            if (kvm_irqchip_add_msi_route(s, msg, NULL) < 0) {
                error_report("Could not enable split IRQ mode.");
                exit(1);
            }
        }
    }
}

int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)
{
    int ret;
    if (machine_kernel_irqchip_split(ms)) {
        ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);
        if (ret) {
            error_report("Could not enable split irqchip mode: %s\n",
                         strerror(-ret));
            exit(1);
        } else {
            DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");
            kvm_split_irqchip = true;
            return 1;
        }
    } else {
        return 0;
    }
3178
}
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318

/* Classic KVM device assignment interface. Will remain x86 only. */
int kvm_device_pci_assign(KVMState *s, PCIHostDeviceAddress *dev_addr,
                          uint32_t flags, uint32_t *dev_id)
{
    struct kvm_assigned_pci_dev dev_data = {
        .segnr = dev_addr->domain,
        .busnr = dev_addr->bus,
        .devfn = PCI_DEVFN(dev_addr->slot, dev_addr->function),
        .flags = flags,
    };
    int ret;

    dev_data.assigned_dev_id =
        (dev_addr->domain << 16) | (dev_addr->bus << 8) | dev_data.devfn;

    ret = kvm_vm_ioctl(s, KVM_ASSIGN_PCI_DEVICE, &dev_data);
    if (ret < 0) {
        return ret;
    }

    *dev_id = dev_data.assigned_dev_id;

    return 0;
}

int kvm_device_pci_deassign(KVMState *s, uint32_t dev_id)
{
    struct kvm_assigned_pci_dev dev_data = {
        .assigned_dev_id = dev_id,
    };

    return kvm_vm_ioctl(s, KVM_DEASSIGN_PCI_DEVICE, &dev_data);
}

static int kvm_assign_irq_internal(KVMState *s, uint32_t dev_id,
                                   uint32_t irq_type, uint32_t guest_irq)
{
    struct kvm_assigned_irq assigned_irq = {
        .assigned_dev_id = dev_id,
        .guest_irq = guest_irq,
        .flags = irq_type,
    };

    if (kvm_check_extension(s, KVM_CAP_ASSIGN_DEV_IRQ)) {
        return kvm_vm_ioctl(s, KVM_ASSIGN_DEV_IRQ, &assigned_irq);
    } else {
        return kvm_vm_ioctl(s, KVM_ASSIGN_IRQ, &assigned_irq);
    }
}

int kvm_device_intx_assign(KVMState *s, uint32_t dev_id, bool use_host_msi,
                           uint32_t guest_irq)
{
    uint32_t irq_type = KVM_DEV_IRQ_GUEST_INTX |
        (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX);

    return kvm_assign_irq_internal(s, dev_id, irq_type, guest_irq);
}

int kvm_device_intx_set_mask(KVMState *s, uint32_t dev_id, bool masked)
{
    struct kvm_assigned_pci_dev dev_data = {
        .assigned_dev_id = dev_id,
        .flags = masked ? KVM_DEV_ASSIGN_MASK_INTX : 0,
    };

    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_INTX_MASK, &dev_data);
}

static int kvm_deassign_irq_internal(KVMState *s, uint32_t dev_id,
                                     uint32_t type)
{
    struct kvm_assigned_irq assigned_irq = {
        .assigned_dev_id = dev_id,
        .flags = type,
    };

    return kvm_vm_ioctl(s, KVM_DEASSIGN_DEV_IRQ, &assigned_irq);
}

int kvm_device_intx_deassign(KVMState *s, uint32_t dev_id, bool use_host_msi)
{
    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_INTX |
        (use_host_msi ? KVM_DEV_IRQ_HOST_MSI : KVM_DEV_IRQ_HOST_INTX));
}

int kvm_device_msi_assign(KVMState *s, uint32_t dev_id, int virq)
{
    return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSI |
                                              KVM_DEV_IRQ_GUEST_MSI, virq);
}

int kvm_device_msi_deassign(KVMState *s, uint32_t dev_id)
{
    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSI |
                                                KVM_DEV_IRQ_HOST_MSI);
}

bool kvm_device_msix_supported(KVMState *s)
{
    /* The kernel lacks a corresponding KVM_CAP, so we probe by calling
     * KVM_ASSIGN_SET_MSIX_NR with an invalid parameter. */
    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, NULL) == -EFAULT;
}

int kvm_device_msix_init_vectors(KVMState *s, uint32_t dev_id,
                                 uint32_t nr_vectors)
{
    struct kvm_assigned_msix_nr msix_nr = {
        .assigned_dev_id = dev_id,
        .entry_nr = nr_vectors,
    };

    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_NR, &msix_nr);
}

int kvm_device_msix_set_vector(KVMState *s, uint32_t dev_id, uint32_t vector,
                               int virq)
{
    struct kvm_assigned_msix_entry msix_entry = {
        .assigned_dev_id = dev_id,
        .gsi = virq,
        .entry = vector,
    };

    return kvm_vm_ioctl(s, KVM_ASSIGN_SET_MSIX_ENTRY, &msix_entry);
}

int kvm_device_msix_assign(KVMState *s, uint32_t dev_id)
{
    return kvm_assign_irq_internal(s, dev_id, KVM_DEV_IRQ_HOST_MSIX |
                                              KVM_DEV_IRQ_GUEST_MSIX, 0);
}

int kvm_device_msix_deassign(KVMState *s, uint32_t dev_id)
{
    return kvm_deassign_irq_internal(s, dev_id, KVM_DEV_IRQ_GUEST_MSIX |
                                                KVM_DEV_IRQ_HOST_MSIX);
}
3319 3320

int kvm_arch_fixup_msi_route(struct kvm_irq_routing_entry *route,
3321
                             uint64_t address, uint32_t data, PCIDevice *dev)
3322 3323 3324
{
    return 0;
}
3325 3326 3327 3328 3329

int kvm_arch_msi_data_to_gsi(uint32_t data)
{
    abort();
}