blob: 9cf8e036698df1fe7f7680289cfd32c971ac3489 [file] [log] [blame]
/*
* 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.
*
*/
#include "qemu/osdep.h"
#include "qapi/qapi-events-run-state.h"
#include "qapi/error.h"
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <sys/syscall.h>
#include <linux/kvm.h>
#include "standard-headers/asm-x86/kvm_para.h"
#include "cpu.h"
#include "host-cpu.h"
#include "sysemu/sysemu.h"
#include "sysemu/hw_accel.h"
#include "sysemu/kvm_int.h"
#include "sysemu/runstate.h"
#include "kvm_i386.h"
#include "sev.h"
#include "hyperv.h"
#include "hyperv-proto.h"
#include "exec/gdbstub.h"
#include "qemu/host-utils.h"
#include "qemu/main-loop.h"
#include "qemu/config-file.h"
#include "qemu/error-report.h"
#include "qemu/memalign.h"
#include "hw/i386/x86.h"
#include "hw/i386/apic.h"
#include "hw/i386/apic_internal.h"
#include "hw/i386/apic-msidef.h"
#include "hw/i386/intel_iommu.h"
#include "hw/i386/x86-iommu.h"
#include "hw/i386/e820_memory_layout.h"
#include "hw/pci/pci.h"
#include "hw/pci/msi.h"
#include "hw/pci/msix.h"
#include "migration/blocker.h"
#include "exec/memattrs.h"
#include "trace.h"
//#define DEBUG_KVM
#ifdef DEBUG_KVM
#define DPRINTF(fmt, ...) \
do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
#else
#define DPRINTF(fmt, ...) \
do { } while (0)
#endif
/* From arch/x86/kvm/lapic.h */
#define KVM_APIC_BUS_CYCLE_NS 1
#define KVM_APIC_BUS_FREQUENCY (1000000000ULL / KVM_APIC_BUS_CYCLE_NS)
#define MSR_KVM_WALL_CLOCK 0x11
#define MSR_KVM_SYSTEM_TIME 0x12
/* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
* 255 kvm_msr_entry structs */
#define MSR_BUF_SIZE 4096
static void kvm_init_msrs(X86CPU *cpu);
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
};
static bool has_msr_star;
static bool has_msr_hsave_pa;
static bool has_msr_tsc_aux;
static bool has_msr_tsc_adjust;
static bool has_msr_tsc_deadline;
static bool has_msr_feature_control;
static bool has_msr_misc_enable;
static bool has_msr_smbase;
static bool has_msr_bndcfgs;
static int lm_capable_kernel;
static bool has_msr_hv_hypercall;
static bool has_msr_hv_crash;
static bool has_msr_hv_reset;
static bool has_msr_hv_vpindex;
static bool hv_vpindex_settable;
static bool has_msr_hv_runtime;
static bool has_msr_hv_synic;
static bool has_msr_hv_stimer;
static bool has_msr_hv_frequencies;
static bool has_msr_hv_reenlightenment;
static bool has_msr_xss;
static bool has_msr_umwait;
static bool has_msr_spec_ctrl;
static bool has_tsc_scale_msr;
static bool has_msr_tsx_ctrl;
static bool has_msr_virt_ssbd;
static bool has_msr_smi_count;
static bool has_msr_arch_capabs;
static bool has_msr_core_capabs;
static bool has_msr_vmx_vmfunc;
static bool has_msr_ucode_rev;
static bool has_msr_vmx_procbased_ctls2;
static bool has_msr_perf_capabs;
static bool has_msr_pkrs;
static uint32_t has_architectural_pmu_version;
static uint32_t num_architectural_pmu_gp_counters;
static uint32_t num_architectural_pmu_fixed_counters;
static int has_xsave;
static int has_xsave2;
static int has_xcrs;
static int has_pit_state2;
static int has_sregs2;
static int has_exception_payload;
static bool has_msr_mcg_ext_ctl;
static struct kvm_cpuid2 *cpuid_cache;
static struct kvm_cpuid2 *hv_cpuid_cache;
static struct kvm_msr_list *kvm_feature_msrs;
#define BUS_LOCK_SLICE_TIME 1000000000ULL /* ns */
static RateLimit bus_lock_ratelimit_ctrl;
int kvm_has_pit_state2(void)
{
return has_pit_state2;
}
bool kvm_has_smm(void)
{
return kvm_vm_check_extension(kvm_state, KVM_CAP_X86_SMM);
}
bool kvm_has_adjust_clock_stable(void)
{
int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
return (ret == KVM_CLOCK_TSC_STABLE);
}
bool kvm_has_adjust_clock(void)
{
return kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
}
bool kvm_has_exception_payload(void)
{
return has_exception_payload;
}
static bool kvm_x2apic_api_set_flags(uint64_t flags)
{
KVMState *s = KVM_STATE(current_accel());
return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
}
#define MEMORIZE(fn, _result) \
({ \
static bool _memorized; \
\
if (_memorized) { \
return _result; \
} \
_memorized = true; \
_result = fn; \
})
static bool has_x2apic_api;
bool kvm_has_x2apic_api(void)
{
return has_x2apic_api;
}
bool kvm_enable_x2apic(void)
{
return MEMORIZE(
kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
has_x2apic_api);
}
bool kvm_hv_vpindex_settable(void)
{
return hv_vpindex_settable;
}
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;
}
memset(&msr_data, 0, sizeof(msr_data));
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;
}
assert(ret == 1);
env->tsc = msr_data.entries[0].data;
return 0;
}
static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data 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, RUN_ON_CPU_NULL);
}
}
}
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);
cpuid = g_malloc0(size);
cpuid->nent = max;
r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
if (r == 0 && cpuid->nent >= max) {
r = -E2BIG;
}
if (r < 0) {
if (r == -E2BIG) {
g_free(cpuid);
return NULL;
} else {
fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
strerror(-r));
exit(1);
}
}
return cpuid;
}
/* 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;
if (cpuid_cache != NULL) {
return cpuid_cache;
}
while ((cpuid = try_get_cpuid(s, max)) == NULL) {
max *= 2;
}
cpuid_cache = cpuid;
return cpuid;
}
static bool host_tsx_broken(void)
{
int family, model, stepping;\
char vendor[CPUID_VENDOR_SZ + 1];
host_cpu_vendor_fms(vendor, &family, &model, &stepping);
/* Check if we are running on a Haswell host known to have broken TSX */
return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
(family == 6) &&
((model == 63 && stepping < 4) ||
model == 60 || model == 69 || model == 70);
}
/* 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;
}
/* 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;
}
uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
uint32_t index, int reg)
{
struct kvm_cpuid2 *cpuid;
uint32_t ret = 0;
uint32_t cpuid_1_edx;
uint64_t bitmask;
cpuid = get_supported_cpuid(s);
struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
if (entry) {
ret = cpuid_entry_get_reg(entry, reg);
}
/* Fixups for the data returned by KVM, below */
if (function == 1 && reg == R_EDX) {
/* KVM before 2.6.30 misreports the following features */
ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
} 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;
/* 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;
}
/* 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;
}
if (enable_cpu_pm) {
int disable_exits = kvm_check_extension(s,
KVM_CAP_X86_DISABLE_EXITS);
if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
ret |= CPUID_EXT_MONITOR;
}
}
} else if (function == 6 && reg == R_EAX) {
ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
} else if (function == 7 && index == 0 && reg == R_EBX) {
if (host_tsx_broken()) {
ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
}
} else if (function == 7 && index == 0 && reg == R_EDX) {
/*
* Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
* We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
* returned by KVM_GET_MSR_INDEX_LIST.
*/
if (!has_msr_arch_capabs) {
ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
}
} else if (function == 0xd && index == 0 &&
(reg == R_EAX || reg == R_EDX)) {
/*
* The value returned by KVM_GET_SUPPORTED_CPUID does not include
* features that still have to be enabled with the arch_prctl
* system call. QEMU needs the full value, which is retrieved
* with KVM_GET_DEVICE_ATTR.
*/
struct kvm_device_attr attr = {
.group = 0,
.attr = KVM_X86_XCOMP_GUEST_SUPP,
.addr = (unsigned long) &bitmask
};
bool sys_attr = kvm_check_extension(s, KVM_CAP_SYS_ATTRIBUTES);
if (!sys_attr) {
return ret;
}
int rc = kvm_ioctl(s, KVM_GET_DEVICE_ATTR, &attr);
if (rc < 0) {
if (rc != -ENXIO) {
warn_report("KVM_GET_DEVICE_ATTR(0, KVM_X86_XCOMP_GUEST_SUPP) "
"error: %d", rc);
}
return ret;
}
ret = (reg == R_EAX) ? bitmask : bitmask >> 32;
} else if (function == 0x80000001 && reg == R_ECX) {
/*
* It's safe to enable TOPOEXT even if it's not returned by
* GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
* us to keep CPU models including TOPOEXT runnable on older kernels.
*/
ret |= CPUID_EXT3_TOPOEXT;
} 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;
} else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
/* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
* be enabled without the in-kernel irqchip
*/
if (!kvm_irqchip_in_kernel()) {
ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
}
if (kvm_irqchip_is_split()) {
ret |= 1U << KVM_FEATURE_MSI_EXT_DEST_ID;
}
} else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
ret |= 1U << KVM_HINTS_REALTIME;
}
return ret;
}
uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
{
struct {
struct kvm_msrs info;
struct kvm_msr_entry entries[1];
} msr_data = {};
uint64_t value;
uint32_t ret, can_be_one, must_be_one;
if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
return 0;
}
/* Check if requested MSR is supported feature MSR */
int i;
for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
if (kvm_feature_msrs->indices[i] == index) {
break;
}
if (i == kvm_feature_msrs->nmsrs) {
return 0; /* if the feature MSR is not supported, simply return 0 */
}
msr_data.info.nmsrs = 1;
msr_data.entries[0].index = index;
ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
if (ret != 1) {
error_report("KVM get MSR (index=0x%x) feature failed, %s",
index, strerror(-ret));
exit(1);
}
value = msr_data.entries[0].data;
switch (index) {
case MSR_IA32_VMX_PROCBASED_CTLS2:
if (!has_msr_vmx_procbased_ctls2) {
/* KVM forgot to add these bits for some time, do this ourselves. */
if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) &
CPUID_XSAVE_XSAVES) {
value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
}
if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) &
CPUID_EXT_RDRAND) {
value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
}
if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
CPUID_7_0_EBX_INVPCID) {
value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
}
if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
CPUID_7_0_EBX_RDSEED) {
value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
}
if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) &
CPUID_EXT2_RDTSCP) {
value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
}
}
/* fall through */
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
/*
* Return true for bits that can be one, but do not have to be one.
* The SDM tells us which bits could have a "must be one" setting,
* so we can do the opposite transformation in make_vmx_msr_value.
*/
must_be_one = (uint32_t)value;
can_be_one = (uint32_t)(value >> 32);
return can_be_one & ~must_be_one;
default:
return value;
}
}
static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
int *max_banks)
{
int r;
r = kvm_check_extension(s, KVM_CAP_MCE);
if (r > 0) {
*max_banks = r;
return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
}
return -ENOSYS;
}
static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
{
CPUState *cs = CPU(cpu);
CPUX86State *env = &cpu->env;
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;
int flags = 0;
if (code == BUS_MCEERR_AR) {
status |= MCI_STATUS_AR | 0x134;
mcg_status |= MCG_STATUS_RIPV | MCG_STATUS_EIPV;
} else {
status |= 0xc0;
mcg_status |= MCG_STATUS_RIPV;
}
flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
/* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
* guest kernel back into env->mcg_ext_ctl.
*/
cpu_synchronize_state(cs);
if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
mcg_status |= MCG_STATUS_LMCE;
flags = 0;
}
cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
(MCM_ADDR_PHYS << 6) | 0xc, flags);
}
static void emit_hypervisor_memory_failure(MemoryFailureAction action, bool ar)
{
MemoryFailureFlags mff = {.action_required = ar, .recursive = false};
qapi_event_send_memory_failure(MEMORY_FAILURE_RECIPIENT_HYPERVISOR, action,
&mff);
}
static void hardware_memory_error(void *host_addr)
{
emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_FATAL, true);
error_report("QEMU got Hardware memory error at addr %p", host_addr);
exit(1);
}
void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
{
X86CPU *cpu = X86_CPU(c);
CPUX86State *env = &cpu->env;
ram_addr_t ram_addr;
hwaddr paddr;
/* If we get an action required MCE, it has been injected by KVM
* while the VM was running. An action optional MCE instead should
* be coming from the main thread, which qemu_init_sigbus identifies
* as the "early kill" thread.
*/
assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
if ((env->mcg_cap & MCG_SER_P) && addr) {
ram_addr = qemu_ram_addr_from_host(addr);
if (ram_addr != RAM_ADDR_INVALID &&
kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
kvm_hwpoison_page_add(ram_addr);
kvm_mce_inject(cpu, paddr, code);
/*
* Use different logging severity based on error type.
* If there is additional MCE reporting on the hypervisor, QEMU VA
* could be another source to identify the PA and MCE details.
*/
if (code == BUS_MCEERR_AR) {
error_report("Guest MCE Memory Error at QEMU addr %p and "
"GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
addr, paddr, "BUS_MCEERR_AR");
} else {
warn_report("Guest MCE Memory Error at QEMU addr %p and "
"GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
addr, paddr, "BUS_MCEERR_AO");
}
return;
}
if (code == BUS_MCEERR_AO) {
warn_report("Hardware memory error at addr %p of type %s "
"for memory used by QEMU itself instead of guest system!",
addr, "BUS_MCEERR_AO");
}
}
if (code == BUS_MCEERR_AR) {
hardware_memory_error(addr);
}
/* Hope we are lucky for AO MCE, just notify a event */
emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_IGNORE, false);
}
static void kvm_reset_exception(CPUX86State *env)
{
env->exception_nr = -1;
env->exception_pending = 0;
env->exception_injected = 0;
env->exception_has_payload = false;
env->exception_payload = 0;
}
static void kvm_queue_exception(CPUX86State *env,
int32_t exception_nr,
uint8_t exception_has_payload,
uint64_t exception_payload)
{
assert(env->exception_nr == -1);
assert(!env->exception_pending);
assert(!env->exception_injected);
assert(!env->exception_has_payload);
env->exception_nr = exception_nr;
if (has_exception_payload) {
env->exception_pending = 1;
env->exception_has_payload = exception_has_payload;
env->exception_payload = exception_payload;
} else {
env->exception_injected = 1;
if (exception_nr == EXCP01_DB) {
assert(exception_has_payload);
env->dr[6] = exception_payload;
} else if (exception_nr == EXCP0E_PAGE) {
assert(exception_has_payload);
env->cr[2] = exception_payload;
} else {
assert(!exception_has_payload);
}
}
}
static int kvm_inject_mce_oldstyle(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
unsigned int bank, bank_num = env->mcg_cap & 0xff;
struct kvm_x86_mce mce;
kvm_reset_exception(env);
/*
* 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];
return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
}
return 0;
}
static void cpu_update_state(void *opaque, bool running, RunState state)
{
CPUX86State *env = opaque;
if (running) {
env->tsc_valid = false;
}
}
unsigned long kvm_arch_vcpu_id(CPUState *cs)
{
X86CPU *cpu = X86_CPU(cs);
return cpu->apic_id;
}
#ifndef KVM_CPUID_SIGNATURE_NEXT
#define KVM_CPUID_SIGNATURE_NEXT 0x40000100
#endif
static bool hyperv_enabled(X86CPU *cpu)
{
return kvm_check_extension(kvm_state, KVM_CAP_HYPERV) > 0 &&
((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_NOTIFY) ||
cpu->hyperv_features || cpu->hyperv_passthrough);
}
/*
* Check whether target_freq is within conservative
* ntp correctable bounds (250ppm) of freq
*/
static inline bool freq_within_bounds(int freq, int target_freq)
{
int max_freq = freq + (freq * 250 / 1000000);
int min_freq = freq - (freq * 250 / 1000000);
if (target_freq >= min_freq && target_freq <= max_freq) {
return true;
}
return false;
}
static int kvm_arch_set_tsc_khz(CPUState *cs)
{
X86CPU *cpu = X86_CPU(cs);
CPUX86State *env = &cpu->env;
int r, cur_freq;
bool set_ioctl = false;
if (!env->tsc_khz) {
return 0;
}
cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) : -ENOTSUP;
/*
* If TSC scaling is supported, attempt to set TSC frequency.
*/
if (kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL)) {
set_ioctl = true;
}
/*
* If desired TSC frequency is within bounds of NTP correction,
* attempt to set TSC frequency.
*/
if (cur_freq != -ENOTSUP && freq_within_bounds(cur_freq, env->tsc_khz)) {
set_ioctl = true;
}
r = set_ioctl ?
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.
*/
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) {
warn_report("TSC frequency mismatch between "
"VM (%" PRId64 " kHz) and host (%d kHz), "
"and TSC scaling unavailable",
env->tsc_khz, cur_freq);
return r;
}
}
return 0;
}
static bool tsc_is_stable_and_known(CPUX86State *env)
{
if (!env->tsc_khz) {
return false;
}
return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
|| env->user_tsc_khz;
}
static struct {
const char *desc;
struct {
uint32_t func;
int reg;
uint32_t bits;
} flags[2];
uint64_t dependencies;
} kvm_hyperv_properties[] = {
[HYPERV_FEAT_RELAXED] = {
.desc = "relaxed timing (hv-relaxed)",
.flags = {
{.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
.bits = HV_RELAXED_TIMING_RECOMMENDED}
}
},
[HYPERV_FEAT_VAPIC] = {
.desc = "virtual APIC (hv-vapic)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_APIC_ACCESS_AVAILABLE}
}
},
[HYPERV_FEAT_TIME] = {
.desc = "clocksources (hv-time)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_TIME_REF_COUNT_AVAILABLE | HV_REFERENCE_TSC_AVAILABLE}
}
},
[HYPERV_FEAT_CRASH] = {
.desc = "crash MSRs (hv-crash)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EDX,
.bits = HV_GUEST_CRASH_MSR_AVAILABLE}
}
},
[HYPERV_FEAT_RESET] = {
.desc = "reset MSR (hv-reset)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_RESET_AVAILABLE}
}
},
[HYPERV_FEAT_VPINDEX] = {
.desc = "VP_INDEX MSR (hv-vpindex)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_VP_INDEX_AVAILABLE}
}
},
[HYPERV_FEAT_RUNTIME] = {
.desc = "VP_RUNTIME MSR (hv-runtime)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_VP_RUNTIME_AVAILABLE}
}
},
[HYPERV_FEAT_SYNIC] = {
.desc = "synthetic interrupt controller (hv-synic)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_SYNIC_AVAILABLE}
}
},
[HYPERV_FEAT_STIMER] = {
.desc = "synthetic timers (hv-stimer)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_SYNTIMERS_AVAILABLE}
},
.dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
},
[HYPERV_FEAT_FREQUENCIES] = {
.desc = "frequency MSRs (hv-frequencies)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_ACCESS_FREQUENCY_MSRS},
{.func = HV_CPUID_FEATURES, .reg = R_EDX,
.bits = HV_FREQUENCY_MSRS_AVAILABLE}
}
},
[HYPERV_FEAT_REENLIGHTENMENT] = {
.desc = "reenlightenment MSRs (hv-reenlightenment)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EAX,
.bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
}
},
[HYPERV_FEAT_TLBFLUSH] = {
.desc = "paravirtualized TLB flush (hv-tlbflush)",
.flags = {
{.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
.bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
HV_EX_PROCESSOR_MASKS_RECOMMENDED}
},
.dependencies = BIT(HYPERV_FEAT_VPINDEX)
},
[HYPERV_FEAT_EVMCS] = {
.desc = "enlightened VMCS (hv-evmcs)",
.flags = {
{.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
.bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
},
.dependencies = BIT(HYPERV_FEAT_VAPIC)
},
[HYPERV_FEAT_IPI] = {
.desc = "paravirtualized IPI (hv-ipi)",
.flags = {
{.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
.bits = HV_CLUSTER_IPI_RECOMMENDED |
HV_EX_PROCESSOR_MASKS_RECOMMENDED}
},
.dependencies = BIT(HYPERV_FEAT_VPINDEX)
},
[HYPERV_FEAT_STIMER_DIRECT] = {
.desc = "direct mode synthetic timers (hv-stimer-direct)",
.flags = {
{.func = HV_CPUID_FEATURES, .reg = R_EDX,
.bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
},
.dependencies = BIT(HYPERV_FEAT_STIMER)
},
[HYPERV_FEAT_AVIC] = {
.desc = "AVIC/APICv support (hv-avic/hv-apicv)",
.flags = {
{.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
.bits = HV_DEPRECATING_AEOI_RECOMMENDED}
}
},
};
static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max,
bool do_sys_ioctl)
{
struct kvm_cpuid2 *cpuid;
int r, size;
size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
cpuid = g_malloc0(size);
cpuid->nent = max;
if (do_sys_ioctl) {
r = kvm_ioctl(kvm_state, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
} else {
r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
}
if (r == 0 && cpuid->nent >= max) {
r = -E2BIG;
}
if (r < 0) {
if (r == -E2BIG) {
g_free(cpuid);
return NULL;
} else {
fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
strerror(-r));
exit(1);
}
}
return cpuid;
}
/*
* Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
* for all entries.
*/
static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
{
struct kvm_cpuid2 *cpuid;
/* 0x40000000..0x40000005, 0x4000000A, 0x40000080..0x40000080 leaves */
int max = 10;
int i;
bool do_sys_ioctl;
do_sys_ioctl =
kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID) > 0;
/*
* Non-empty KVM context is needed when KVM_CAP_SYS_HYPERV_CPUID is
* unsupported, kvm_hyperv_expand_features() checks for that.
*/
assert(do_sys_ioctl || cs->kvm_state);
/*
* When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
* -E2BIG, however, it doesn't report back the right size. Keep increasing
* it and re-trying until we succeed.
*/
while ((cpuid = try_get_hv_cpuid(cs, max, do_sys_ioctl)) == NULL) {
max++;
}
/*
* KVM_GET_SUPPORTED_HV_CPUID does not set EVMCS CPUID bit before
* KVM_CAP_HYPERV_ENLIGHTENED_VMCS is enabled but we want to get the
* information early, just check for the capability and set the bit
* manually.
*/
if (!do_sys_ioctl && kvm_check_extension(cs->kvm_state,
KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
for (i = 0; i < cpuid->nent; i++) {
if (cpuid->entries[i].function == HV_CPUID_ENLIGHTMENT_INFO) {
cpuid->entries[i].eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
}
}
}
return cpuid;
}
/*
* When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
* leaves from KVM_CAP_HYPERV* and present MSRs data.
*/
static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
{
X86CPU *cpu = X86_CPU(cs);
struct kvm_cpuid2 *cpuid;
struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
/* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
cpuid->nent = 2;
/* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
entry_feat = &cpuid->entries[0];
entry_feat->function = HV_CPUID_FEATURES;
entry_recomm = &cpuid->entries[1];
entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
}
if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
}
if (has_msr_hv_frequencies) {
entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
}
if (has_msr_hv_crash) {
entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
}
if (has_msr_hv_reenlightenment) {
entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
}
if (has_msr_hv_reset) {
entry_feat->eax |= HV_RESET_AVAILABLE;
}
if (has_msr_hv_vpindex) {
entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
}
if (has_msr_hv_runtime) {
entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
}
if (has_msr_hv_synic) {
unsigned int cap = cpu->hyperv_synic_kvm_only ?
KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
if (kvm_check_extension(cs->kvm_state, cap) > 0) {
entry_feat->eax |= HV_SYNIC_AVAILABLE;
}
}
if (has_msr_hv_stimer) {
entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
}
if (kvm_check_extension(cs->kvm_state,
KVM_CAP_HYPERV_TLBFLUSH) > 0) {
entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
}
if (kvm_check_extension(cs->kvm_state,
KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
}
if (kvm_check_extension(cs->kvm_state,
KVM_CAP_HYPERV_SEND_IPI) > 0) {
entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
}
return cpuid;
}
static uint32_t hv_cpuid_get_host(CPUState *cs, uint32_t func, int reg)
{
struct kvm_cpuid_entry2 *entry;
struct kvm_cpuid2 *cpuid;
if (hv_cpuid_cache) {
cpuid = hv_cpuid_cache;
} else {
if (kvm_check_extension(kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
cpuid = get_supported_hv_cpuid(cs);
} else {
/*
* 'cs->kvm_state' may be NULL when Hyper-V features are expanded
* before KVM context is created but this is only done when
* KVM_CAP_SYS_HYPERV_CPUID is supported and it implies
* KVM_CAP_HYPERV_CPUID.
*/
assert(cs->kvm_state);
cpuid = get_supported_hv_cpuid_legacy(cs);
}
hv_cpuid_cache = cpuid;
}
if (!cpuid) {
return 0;
}
entry = cpuid_find_entry(cpuid, func, 0);
if (!entry) {
return 0;
}
return cpuid_entry_get_reg(entry, reg);
}
static bool hyperv_feature_supported(CPUState *cs, int feature)
{
uint32_t func, bits;
int i, reg;
for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
func = kvm_hyperv_properties[feature].flags[i].func;
reg = kvm_hyperv_properties[feature].flags[i].reg;
bits = kvm_hyperv_properties[feature].flags[i].bits;
if (!func) {
continue;
}
if ((hv_cpuid_get_host(cs, func, reg) & bits) != bits) {
return false;
}
}
return true;
}
/* Checks that all feature dependencies are enabled */
static bool hv_feature_check_deps(X86CPU *cpu, int feature, Error **errp)
{
uint64_t deps;
int dep_feat;
deps = kvm_hyperv_properties[feature].dependencies;
while (deps) {
dep_feat = ctz64(deps);
if (!(hyperv_feat_enabled(cpu, dep_feat))) {
error_setg(errp, "Hyper-V %s requires Hyper-V %s",
kvm_hyperv_properties[feature].desc,
kvm_hyperv_properties[dep_feat].desc);
return false;
}
deps &= ~(1ull << dep_feat);
}
return true;
}
static uint32_t hv_build_cpuid_leaf(CPUState *cs, uint32_t func, int reg)
{
X86CPU *cpu = X86_CPU(cs);
uint32_t r = 0;
int i, j;
for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties); i++) {
if (!hyperv_feat_enabled(cpu, i)) {
continue;
}
for (j = 0; j < ARRAY_SIZE(kvm_hyperv_properties[i].flags); j++) {
if (kvm_hyperv_properties[i].flags[j].func != func) {
continue;
}
if (kvm_hyperv_properties[i].flags[j].reg != reg) {
continue;
}
r |= kvm_hyperv_properties[i].flags[j].bits;
}
}
return r;
}
/*
* Expand Hyper-V CPU features. In partucular, check that all the requested
* features are supported by the host and the sanity of the configuration
* (that all the required dependencies are included). Also, this takes care
* of 'hv_passthrough' mode and fills the environment with all supported
* Hyper-V features.
*/
bool kvm_hyperv_expand_features(X86CPU *cpu, Error **errp)
{
CPUState *cs = CPU(cpu);
Error *local_err = NULL;
int feat;
if (!hyperv_enabled(cpu))
return true;
/*
* When kvm_hyperv_expand_features is called at CPU feature expansion
* time per-CPU kvm_state is not available yet so we can only proceed
* when KVM_CAP_SYS_HYPERV_CPUID is supported.
*/
if (!cs->kvm_state &&
!kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID))
return true;
if (cpu->hyperv_passthrough) {
cpu->hyperv_vendor_id[0] =
hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EBX);
cpu->hyperv_vendor_id[1] =
hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_ECX);
cpu->hyperv_vendor_id[2] =
hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EDX);
cpu->hyperv_vendor = g_realloc(cpu->hyperv_vendor,
sizeof(cpu->hyperv_vendor_id) + 1);
memcpy(cpu->hyperv_vendor, cpu->hyperv_vendor_id,
sizeof(cpu->hyperv_vendor_id));
cpu->hyperv_vendor[sizeof(cpu->hyperv_vendor_id)] = 0;
cpu->hyperv_interface_id[0] =
hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EAX);
cpu->hyperv_interface_id[1] =
hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EBX);
cpu->hyperv_interface_id[2] =
hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_ECX);
cpu->hyperv_interface_id[3] =
hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EDX);
cpu->hyperv_ver_id_build =
hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EAX);
cpu->hyperv_ver_id_major =
hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX) >> 16;
cpu->hyperv_ver_id_minor =
hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX) & 0xffff;
cpu->hyperv_ver_id_sp =
hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_ECX);
cpu->hyperv_ver_id_sb =
hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX) >> 24;
cpu->hyperv_ver_id_sn =
hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX) & 0xffffff;
cpu->hv_max_vps = hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS,
R_EAX);
cpu->hyperv_limits[0] =
hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EBX);
cpu->hyperv_limits[1] =
hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_ECX);
cpu->hyperv_limits[2] =
hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EDX);
cpu->hyperv_spinlock_attempts =
hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EBX);
/*
* Mark feature as enabled in 'cpu->hyperv_features' as
* hv_build_cpuid_leaf() uses this info to build guest CPUIDs.
*/
for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
if (hyperv_feature_supported(cs, feat)) {
cpu->hyperv_features |= BIT(feat);
}
}
} else {
/* Check features availability and dependencies */
for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
/* If the feature was not requested skip it. */
if (!hyperv_feat_enabled(cpu, feat)) {
continue;
}
/* Check if the feature is supported by KVM */
if (!hyperv_feature_supported(cs, feat)) {
error_setg(errp, "Hyper-V %s is not supported by kernel",
kvm_hyperv_properties[feat].desc);
return false;
}
/* Check dependencies */
if (!hv_feature_check_deps(cpu, feat, &local_err)) {
error_propagate(errp, local_err);
return false;
}
}
}
/* Additional dependencies not covered by kvm_hyperv_properties[] */
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
!cpu->hyperv_synic_kvm_only &&
!hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
error_setg(errp, "Hyper-V %s requires Hyper-V %s",
kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
return false;
}
return true;
}
/*
* Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent.
*/
static int hyperv_fill_cpuids(CPUState *cs,
struct kvm_cpuid_entry2 *cpuid_ent)
{
X86CPU *cpu = X86_CPU(cs);
struct kvm_cpuid_entry2 *c;
uint32_t cpuid_i = 0;
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
c->ebx = cpu->hyperv_vendor_id[0];
c->ecx = cpu->hyperv_vendor_id[1];
c->edx = cpu->hyperv_vendor_id[2];
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_INTERFACE;
c->eax = cpu->hyperv_interface_id[0];
c->ebx = cpu->hyperv_interface_id[1];
c->ecx = cpu->hyperv_interface_id[2];
c->edx = cpu->hyperv_interface_id[3];
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_VERSION;
c->eax = cpu->hyperv_ver_id_build;
c->ebx = (uint32_t)cpu->hyperv_ver_id_major << 16 |
cpu->hyperv_ver_id_minor;
c->ecx = cpu->hyperv_ver_id_sp;
c->edx = (uint32_t)cpu->hyperv_ver_id_sb << 24 |
(cpu->hyperv_ver_id_sn & 0xffffff);
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_FEATURES;
c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EAX);
c->ebx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EBX);
c->edx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EDX);
/* Unconditionally required with any Hyper-V enlightenment */
c->eax |= HV_HYPERCALL_AVAILABLE;
/* SynIC and Vmbus devices require messages/signals hypercalls */
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
!cpu->hyperv_synic_kvm_only) {
c->ebx |= HV_POST_MESSAGES | HV_SIGNAL_EVENTS;
}
/* Not exposed by KVM but needed to make CPU hotplug in Windows work */
c->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_ENLIGHTMENT_INFO;
c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX);
c->ebx = cpu->hyperv_spinlock_attempts;
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC) &&
!hyperv_feat_enabled(cpu, HYPERV_FEAT_AVIC)) {
c->eax |= HV_APIC_ACCESS_RECOMMENDED;
}
if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
c->eax |= HV_NO_NONARCH_CORESHARING;
} else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
c->eax |= hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX) &
HV_NO_NONARCH_CORESHARING;
}
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_IMPLEMENT_LIMITS;
c->eax = cpu->hv_max_vps;
c->ebx = cpu->hyperv_limits[0];
c->ecx = cpu->hyperv_limits[1];
c->edx = cpu->hyperv_limits[2];
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
uint32_t function;
/* Create zeroed 0x40000006..0x40000009 leaves */
for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
function < HV_CPUID_NESTED_FEATURES; function++) {
c = &cpuid_ent[cpuid_i++];
c->function = function;
}
c = &cpuid_ent[cpuid_i++];
c->function = HV_CPUID_NESTED_FEATURES;
c->eax = cpu->hyperv_nested[0];
}
return cpuid_i;
}
static Error *hv_passthrough_mig_blocker;
static Error *hv_no_nonarch_cs_mig_blocker;
/* Checks that the exposed eVMCS version range is supported by KVM */
static bool evmcs_version_supported(uint16_t evmcs_version,
uint16_t supported_evmcs_version)
{
uint8_t min_version = evmcs_version & 0xff;
uint8_t max_version = evmcs_version >> 8;
uint8_t min_supported_version = supported_evmcs_version & 0xff;
uint8_t max_supported_version = supported_evmcs_version >> 8;
return (min_version >= min_supported_version) &&
(max_version <= max_supported_version);
}
#define DEFAULT_EVMCS_VERSION ((1 << 8) | 1)
static int hyperv_init_vcpu(X86CPU *cpu)
{
CPUState *cs = CPU(cpu);
Error *local_err = NULL;
int ret;
if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
error_setg(&hv_passthrough_mig_blocker,
"'hv-passthrough' CPU flag prevents migration, use explicit"
" set of hv-* flags instead");
ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
if (ret < 0) {
error_report_err(local_err);
return ret;
}
}
if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
hv_no_nonarch_cs_mig_blocker == NULL) {
error_setg(&hv_no_nonarch_cs_mig_blocker,
"'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
" use explicit 'hv-no-nonarch-coresharing=on' instead (but"
" make sure SMT is disabled and/or that vCPUs are properly"
" pinned)");
ret = migrate_add_blocker(hv_no_nonarch_cs_mig_blocker, &local_err);
if (ret < 0) {
error_report_err(local_err);
return ret;
}
}
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
/*
* the kernel doesn't support setting vp_index; assert that its value
* is in sync
*/
struct {
struct kvm_msrs info;
struct kvm_msr_entry entries[1];
} msr_data = {
.info.nmsrs = 1,
.entries[0].index = HV_X64_MSR_VP_INDEX,
};
ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
if (ret < 0) {
return ret;
}
assert(ret == 1);
if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
error_report("kernel's vp_index != QEMU's vp_index");
return -ENXIO;
}
}
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
if (ret < 0) {
error_report("failed to turn on HyperV SynIC in KVM: %s",
strerror(-ret));
return ret;
}
if (!cpu->hyperv_synic_kvm_only) {
ret = hyperv_x86_synic_add(cpu);
if (ret < 0) {
error_report("failed to create HyperV SynIC: %s",
strerror(-ret));
return ret;
}
}
}
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
uint16_t evmcs_version = DEFAULT_EVMCS_VERSION;
uint16_t supported_evmcs_version;
ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
(uintptr_t)&supported_evmcs_version);
/*
* KVM is required to support EVMCS ver.1. as that's what 'hv-evmcs'
* option sets. Note: we hardcode the maximum supported eVMCS version
* to '1' as well so 'hv-evmcs' feature is migratable even when (and if)
* ver.2 is implemented. A new option (e.g. 'hv-evmcs=2') will then have
* to be added.
*/
if (ret < 0) {
error_report("Hyper-V %s is not supported by kernel",
kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
return ret;
}
if (!evmcs_version_supported(evmcs_version, supported_evmcs_version)) {
error_report("eVMCS version range [%d..%d] is not supported by "
"kernel (supported: [%d..%d])", evmcs_version & 0xff,
evmcs_version >> 8, supported_evmcs_version & 0xff,
supported_evmcs_version >> 8);
return -ENOTSUP;
}
cpu->hyperv_nested[0] = evmcs_version;
}
if (cpu->hyperv_enforce_cpuid) {
ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENFORCE_CPUID, 0, 1);
if (ret < 0) {
error_report("failed to enable KVM_CAP_HYPERV_ENFORCE_CPUID: %s",
strerror(-ret));
return ret;
}
}
return 0;
}
static Error *invtsc_mig_blocker;
#define KVM_MAX_CPUID_ENTRIES 100
static void kvm_init_xsave(CPUX86State *env)
{
if (has_xsave2) {
env->xsave_buf_len = QEMU_ALIGN_UP(has_xsave2, 4096);
} else if (has_xsave) {
env->xsave_buf_len = sizeof(struct kvm_xsave);
} else {
return;
}
env->xsave_buf = qemu_memalign(4096, env->xsave_buf_len);
memset(env->xsave_buf, 0, env->xsave_buf_len);
/*
* The allocated storage must be large enough for all of the
* possible XSAVE state components.
*/
assert(kvm_arch_get_supported_cpuid(kvm_state, 0xd, 0, R_ECX) <=
env->xsave_buf_len);
}
int kvm_arch_init_vcpu(CPUState *cs)
{
struct {
struct kvm_cpuid2 cpuid;
struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
} cpuid_data;
/*
* The kernel defines these structs with padding fields so there
* should be no extra padding in our cpuid_data struct.
*/
QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
sizeof(struct kvm_cpuid2) +
sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
X86CPU *cpu = X86_CPU(cs);
CPUX86State *env = &cpu->env;
uint32_t limit, i, j, cpuid_i;
uint32_t unused;
struct kvm_cpuid_entry2 *c;
uint32_t signature[3];
int kvm_base = KVM_CPUID_SIGNATURE;
int max_nested_state_len;
int r;
Error *local_err = NULL;
memset(&cpuid_data, 0, sizeof(cpuid_data));
cpuid_i = 0;
has_xsave2 = kvm_check_extension(cs->kvm_state, KVM_CAP_XSAVE2);
r = kvm_arch_set_tsc_khz(cs);
if (r < 0) {
return r;
}
/* 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;
}
}
env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
/*
* kvm_hyperv_expand_features() is called here for the second time in case
* KVM_CAP_SYS_HYPERV_CPUID is not supported. While we can't possibly handle
* 'query-cpu-model-expansion' in this case as we don't have a KVM vCPU to
* check which Hyper-V enlightenments are supported and which are not, we
* can still proceed and check/expand Hyper-V enlightenments here so legacy
* behavior is preserved.
*/
if (!kvm_hyperv_expand_features(cpu, &local_err)) {
error_report_err(local_err);
return -ENOSYS;
}
if (hyperv_enabled(cpu)) {
r = hyperv_init_vcpu(cpu);
if (r) {
return r;
}
cpuid_i = hyperv_fill_cpuids(cs, cpuid_data.entries);
kvm_base = KVM_CPUID_SIGNATURE_NEXT;
has_msr_hv_hypercall = true;
}
if (cpu->expose_kvm) {
memcpy(signature, "KVMKVMKVM\0\0\0", 12);
c = &cpuid_data.entries[cpuid_i++];
c->function = KVM_CPUID_SIGNATURE | kvm_base;
c->eax = KVM_CPUID_FEATURES | kvm_base;
c->ebx = signature[0];
c->ecx = signature[1];
c->edx = signature[2];
c = &cpuid_data.entries[cpuid_i++];
c->function = KVM_CPUID_FEATURES | kvm_base;
c->eax = env->features[FEAT_KVM];
c->edx = env->features[FEAT_KVM_HINTS];
}
cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
if (cpu->kvm_pv_enforce_cpuid) {
r = kvm_vcpu_enable_cap(cs, KVM_CAP_ENFORCE_PV_FEATURE_CPUID, 0, 1);
if (r < 0) {
fprintf(stderr,
"failed to enable KVM_CAP_ENFORCE_PV_FEATURE_CPUID: %s",
strerror(-r));
abort();
}
}
for (i = 0; i <= limit; i++) {
if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
fprintf(stderr, "unsupported level value: 0x%x\n", limit);
abort();
}
c = &cpuid_data.entries[cpuid_i++];
switch (i) {
case 2: {
/* Keep reading function 2 till all the input is received */
int times;
c->function = i;
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;
for (j = 1; j < times; ++j) {
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();
}
c = &cpuid_data.entries[cpuid_i++];
c->function = i;
c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
}
break;
}
case 0x1f:
if (env->nr_dies < 2) {
break;
}
/* fallthrough */
case 4:
case 0xb:
case 0xd:
for (j = 0; ; j++) {
if (i == 0xd && j == 64) {
break;
}
if (i == 0x1f && j == 64) {
break;
}
c->function = i;
c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
c->index = j;
cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
if (i == 4 && c->eax == 0) {
break;
}
if (i == 0xb && !(c->ecx & 0xff00)) {
break;
}
if (i == 0x1f && !(c->ecx & 0xff00)) {
break;
}
if (i == 0xd && c->eax == 0) {
continue;
}
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();
}
c = &cpuid_data.entries[cpuid_i++];
}
break;
case 0x7:
case 0x12:
for (j = 0; ; j++) {
c->function = i;
c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
c->index = j;
cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
if (j > 1 && (c->eax & 0xf) != 1) {
break;
}
if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
fprintf(stderr, "cpuid_data is full, no space for "
"cpuid(eax:0x12,ecx:0x%x)\n", j);
abort();
}
c = &cpuid_data.entries[cpuid_i++];
}
break;
case 0x14:
case 0x1d:
case 0x1e: {
uint32_t times;
c->function = i;
c->index = 0;
c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
times = c->eax;
for (j = 1; j <= times; ++j) {
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();
}
c = &cpuid_data.entries[cpuid_i++];
c->function = i;
c->index = j;
c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
}
break;
}
default:
c->function = i;
c->flags = 0;
cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
/*
* KVM already returns all zeroes if a CPUID entry is missing,
* so we can omit it and avoid hitting KVM's 80-entry limit.
*/
cpuid_i--;
}
break;
}
}
if (limit >= 0x0a) {
uint32_t eax, edx;
cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
has_architectural_pmu_version = eax & 0xff;
if (has_architectural_pmu_version > 0) {
num_architectural_pmu_gp_counters = (eax & 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_gp_counters > MAX_GP_COUNTERS) {
num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
}
if (has_architectural_pmu_version > 1) {
num_architectural_pmu_fixed_counters = edx & 0x1f;
if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
}
}
}
}
cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
for (i = 0x80000000; i <= limit; i++) {
if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
abort();
}
c = &cpuid_data.entries[cpuid_i++];
switch (i) {
case 0x8000001d:
/* Query for all AMD cache information leaves */
for (j = 0; ; j++) {
c->function = i;
c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
c->index = j;
cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
if (c->eax == 0) {
break;
}
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();
}
c = &cpuid_data.entries[cpuid_i++];
}
break;
default:
c->function = i;
c->flags = 0;
cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
/*
* KVM already returns all zeroes if a CPUID entry is missing,
* so we can omit it and avoid hitting KVM's 80-entry limit.
*/
cpuid_i--;
}
break;
}
}
/* 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++) {
if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
abort();
}
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);
}
}
cpuid_data.cpuid.nent = cpuid_i;
if (((env->cpuid_version >> 8)&0xF) >= 6
&& (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
(CPUID_MCE | CPUID_MCA)
&& kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
uint64_t mcg_cap, unsupported_caps;
int banks;
int ret;
ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
if (ret < 0) {
fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
return ret;
}
if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
(int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
return -ENOTSUP;
}
unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
if (unsupported_caps) {
if (unsupported_caps & MCG_LMCE_P) {
error_report("kvm: LMCE not supported");
return -ENOTSUP;
}
warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
unsupported_caps);
}
env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
if (ret < 0) {
fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
return ret;
}
}
cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
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);
}
c = cpuid_find_entry(&cpuid_data.cpuid, 7, 0);
if (c && (c->ebx & CPUID_7_0_EBX_SGX)) {
has_msr_feature_control = true;
}
if (env->mcg_cap & MCG_LMCE_P) {
has_msr_mcg_ext_ctl = has_msr_feature_control = true;
}
if (!env->user_tsc_khz) {
if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
invtsc_mig_blocker == NULL) {
error_setg(&invtsc_mig_blocker,
"State blocked by non-migratable CPU device"
" (invtsc flag)");
r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
if (r < 0) {
error_report_err(local_err);
return r;
}
}
}
if (cpu->vmware_cpuid_freq
/* Guests depend on 0x40000000 to detect this feature, so only expose
* it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
&& cpu->expose_kvm
&& kvm_base == KVM_CPUID_SIGNATURE
/* TSC clock must be stable and known for this feature. */
&& tsc_is_stable_and_known(env)) {
c = &cpuid_data.entries[cpuid_i++];
c->function = KVM_CPUID_SIGNATURE | 0x10;
c->eax = env->tsc_khz;
c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
c->ecx = c->edx = 0;
c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
}
cpuid_data.cpuid.nent = cpuid_i;
cpuid_data.cpuid.padding = 0;
r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
if (r) {
goto fail;
}
kvm_init_xsave(env);
max_nested_state_len = kvm_max_nested_state_length();
if (max_nested_state_len > 0) {
assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
if (cpu_has_vmx(env) || cpu_has_svm(env)) {
struct kvm_vmx_nested_state_hdr *vmx_hdr;
env->nested_state = g_malloc0(max_nested_state_len);
env->nested_state->size = max_nested_state_len;
if (cpu_has_vmx(env)) {
env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
vmx_hdr = &env->nested_state->hdr.vmx;
vmx_hdr->vmxon_pa = -1ull;
vmx_hdr->vmcs12_pa = -1ull;
} else {
env->nested_state->format = KVM_STATE_NESTED_FORMAT_SVM;
}
}
}
cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
has_msr_tsc_aux = false;
}
kvm_init_msrs(cpu);
return 0;
fail:
migrate_del_blocker(invtsc_mig_blocker);
return r;
}
int kvm_arch_destroy_vcpu(CPUState *cs)
{
X86CPU *cpu = X86_CPU(cs);
CPUX86State *env = &cpu->env;
g_free(env->xsave_buf);
if (cpu->kvm_msr_buf) {
g_free(cpu->kvm_msr_buf);
cpu->kvm_msr_buf = NULL;
}
if (env->nested_state) {
g_free(env->nested_state);
env->nested_state = NULL;
}
qemu_del_vm_change_state_handler(cpu->vmsentry);
return 0;
}
void kvm_arch_reset_vcpu(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
env->xcr0 = 1;
if (kvm_irqchip_in_kernel()) {
env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
KVM_MP_STATE_UNINITIALIZED;
} else {
env->mp_state = KVM_MP_STATE_RUNNABLE;
}
if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
int i;
for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
}
hyperv_x86_synic_reset(cpu);
}
/* enabled by default */
env->poll_control_msr = 1;
sev_es_set_reset_vector(CPU(cpu));
}
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;
}
}
static int kvm_get_supported_feature_msrs(KVMState *s)
{
int ret = 0;
if (kvm_feature_msrs != NULL) {
return 0;
}
if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
return 0;
}
struct kvm_msr_list msr_list;
msr_list.nmsrs = 0;
ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
if (ret < 0 && ret != -E2BIG) {
error_report("Fetch KVM feature MSR list failed: %s",
strerror(-ret));
return ret;
}
assert(msr_list.nmsrs > 0);
kvm_feature_msrs = (struct kvm_msr_list *) \
g_malloc0(sizeof(msr_list) +
msr_list.nmsrs * sizeof(msr_list.indices[0]));
kvm_feature_msrs->nmsrs = msr_list.nmsrs;
ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
if (ret < 0) {
error_report("Fetch KVM feature MSR list failed: %s",
strerror(-ret));
g_free(kvm_feature_msrs);
kvm_feature_msrs = NULL;
return ret;
}
return 0;
}
static int kvm_get_supported_msrs(KVMState *s)
{
int ret = 0;
struct kvm_msr_list msr_list, *kvm_msr_list;
/*
* Obtain MSR list from KVM. These are the MSRs that we must
* save/restore.
*/
msr_list.nmsrs = 0;
ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
if (ret < 0 && ret != -E2BIG) {
return ret;
}
/*
* Old kernel modules had a bug and could write beyond the provided
* memory. Allocate at least a safe amount of 1K.
*/
kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
msr_list.nmsrs *
sizeof(msr_list.indices[0])));
kvm_msr_list->nmsrs = msr_list.nmsrs;
ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
if (ret >= 0) {
int i;
for (i = 0; i < kvm_msr_list->nmsrs; i++) {
switch (kvm_msr_list->indices[i]) {
case MSR_STAR:
has_msr_star = true;
break;
case MSR_VM_HSAVE_PA:
has_msr_hsave_pa = true;
break;
case MSR_TSC_AUX:
has_msr_tsc_aux = true;
break;
case MSR_TSC_ADJUST:
has_msr_tsc_adjust = true;
break;
case MSR_IA32_TSCDEADLINE:
has_msr_tsc_deadline = true;
break;
case MSR_IA32_SMBASE:
has_msr_smbase = true;
break;
case MSR_SMI_COUNT:
has_msr_smi_count = true;
break;
case MSR_IA32_MISC_ENABLE:
has_msr_misc_enable = true;
break;
case MSR_IA32_BNDCFGS:
has_msr_bndcfgs = true;
break;
case MSR_IA32_XSS:
has_msr_xss = true;
break;
case MSR_IA32_UMWAIT_CONTROL:
has_msr_umwait = true;
break;
case HV_X64_MSR_CRASH_CTL:
has_msr_hv_crash = true;
break;
case HV_X64_MSR_RESET:
has_msr_hv_reset = true;
break;
case HV_X64_MSR_VP_INDEX:
has_msr_hv_vpindex = true;
break;
case HV_X64_MSR_VP_RUNTIME:
has_msr_hv_runtime = true;
break;
case HV_X64_MSR_SCONTROL:
has_msr_hv_synic = true;
break;
case HV_X64_MSR_STIMER0_CONFIG:
has_msr_hv_stimer = true;
break;
case HV_X64_MSR_TSC_FREQUENCY:
has_msr_hv_frequencies = true;
break;
case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
has_msr_hv_reenlightenment = true;
break;
case MSR_IA32_SPEC_CTRL:
has_msr_spec_ctrl = true;
break;
case MSR_AMD64_TSC_RATIO:
has_tsc_scale_msr = true;
break;
case MSR_IA32_TSX_CTRL:
has_msr_tsx_ctrl = true;
break;
case MSR_VIRT_SSBD:
has_msr_virt_ssbd = true;
break;
case MSR_IA32_ARCH_CAPABILITIES:
has_msr_arch_capabs = true;
break;
case MSR_IA32_CORE_CAPABILITY:
has_msr_core_capabs = true;
break;
case MSR_IA32_PERF_CAPABILITIES:
has_msr_perf_capabs = true;
break;
case MSR_IA32_VMX_VMFUNC:
has_msr_vmx_vmfunc = true;
break;
case MSR_IA32_UCODE_REV:
has_msr_ucode_rev = true;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
has_msr_vmx_procbased_ctls2 = true;
break;
case MSR_IA32_PKRS:
has_msr_pkrs = true;
break;
}
}
}
g_free(kvm_msr_list);
return ret;
}
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, "kvm-smram");
}
int kvm_arch_init(MachineState *ms, KVMState *s)
{
uint64_t identity_base = 0xfffbc000;
uint64_t shadow_mem;
int ret;
struct utsname utsname;
Error *local_err = NULL;
/*
* Initialize SEV context, if required
*
* If no memory encryption is requested (ms->cgs == NULL) this is
* a no-op.
*
* It's also a no-op if a non-SEV confidential guest support
* mechanism is selected. SEV is the only mechanism available to
* select on x86 at present, so this doesn't arise, but if new
* mechanisms are supported in future (e.g. TDX), they'll need
* their own initialization either here or elsewhere.
*/
ret = sev_kvm_init(ms->cgs, &local_err);
if (ret < 0) {
error_report_err(local_err);
return ret;
}
if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {
error_report("kvm: KVM_CAP_IRQ_ROUTING not supported by KVM");
return -ENOTSUP;
}
has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
if (has_exception_payload) {
ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
if (ret < 0) {
error_report("kvm: Failed to enable exception payload cap: %s",
strerror(-ret));
return ret;
}
}
ret = kvm_get_supported_msrs(s);
if (ret < 0) {
return ret;
}
kvm_get_supported_feature_msrs(s);
uname(&utsname);
lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
/*
* 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.
*/
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;
}
}
/* Set TSS base one page after EPT identity map. */
ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
if (ret < 0) {
return ret;
}
/* Tell fw_cfg to notify the BIOS to reserve the range. */
ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
if (ret < 0) {
fprintf(stderr, "e820_add_entry() table is full\n");
return ret;
}
shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
if (shadow_mem != -1) {
shadow_mem /= 4096;
ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
if (ret < 0) {
return ret;
}
}
if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
smram_machine_done.notify = register_smram_listener;
qemu_add_machine_init_done_notifier(&smram_machine_done);
}
if (enable_cpu_pm) {
int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
int ret;
/* Work around for kernel header with a typo. TODO: fix header and drop. */
#if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
#define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
#endif
if (disable_exits) {
disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
KVM_X86_DISABLE_EXITS_HLT |
KVM_X86_DISABLE_EXITS_PAUSE |
KVM_X86_DISABLE_EXITS_CSTATE);
}
ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
disable_exits);
if (ret < 0) {
error_report("kvm: guest stopping CPU not supported: %s",
strerror(-ret));
}
}
if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
X86MachineState *x86ms = X86_MACHINE(ms);
if (x86ms->bus_lock_ratelimit > 0) {
ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
error_report("kvm: bus lock detection unsupported");
return -ENOTSUP;
}
ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
KVM_BUS_LOCK_DETECTION_EXIT);
if (ret < 0) {
error_report("kvm: Failed to enable bus lock detection cap: %s",
strerror(-ret));
return ret;
}
ratelimit_init(&bus_lock_ratelimit_ctrl);
ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
}
}
return 0;
}
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;
lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
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;
lhs->unusable = !lhs->present;
lhs->padding = 0;
}
static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
{
lhs->selector = rhs->selector;
lhs->base = rhs->base;
lhs->limit = rhs->limit;
lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
((rhs->present && !rhs->unusable) * 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);
}
static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
{
if (set) {
*kvm_reg = *qemu_reg;
} else {
*qemu_reg = *kvm_reg;
}
}
static int kvm_getput_regs(X86CPU *cpu, int set)
{
CPUX86State *env = &cpu->env;
struct kvm_regs regs;
int ret = 0;
if (!set) {
ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
if (ret < 0) {
return ret;
}
}
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);
if (set) {
ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
}
return ret;
}
static int kvm_put_fpu(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
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;
fpu.last_opcode = env->fpop;
fpu.last_ip = env->fpip;
fpu.last_dp = env->fpdp;
for (i = 0; i < 8; ++i) {
fpu.ftwx |= (!env->fptags[i]) << i;
}
memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
for (i = 0; i < CPU_NB_REGS; i++) {
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));
}
fpu.mxcsr = env->mxcsr;
return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
}
static int kvm_put_xsave(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
void *xsave = env->xsave_buf;
if (!has_xsave) {
return kvm_put_fpu(cpu);
}
x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
}
static int kvm_put_xcrs(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
struct kvm_xcrs xcrs = {};
if (!has_xcrs) {
return 0;
}
xcrs.nr_xcrs = 1;
xcrs.flags = 0;
xcrs.xcrs[0].xcr = 0;
xcrs.xcrs[0].value = env->xcr0;
return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
}
static int kvm_put_sregs(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
struct kvm_sregs sregs;
/*
* The interrupt_bitmap is ignored because KVM_SET_SREGS is
* always followed by KVM_SET_VCPU_EVENTS.
*/
memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
if ((env->eflags & VM_MASK)) {
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]);
} else {
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]);
}
set_seg(&sregs.tr, &env->tr);
set_seg(&sregs.ldt, &env->ldt);
sregs.idt.limit = env->idt.limit;
sregs.idt.base = env->idt.base;
memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
sregs.gdt.limit = env->gdt.limit;
sregs.gdt.base = env->gdt.base;
memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
sregs.cr0 = env->cr[0];
sregs.cr2 = env->cr[2];
sregs.cr3 = env->cr[3];
sregs.cr4 = env->cr[4];
sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
sregs.efer = env->efer;
return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
}
static int kvm_put_sregs2(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
struct kvm_sregs2 sregs;
int i;
sregs.flags = 0;
if ((env->eflags & VM_MASK)) {
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]);
} else {
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]);
}
set_seg(&sregs.tr, &env->tr);
set_seg(&sregs.ldt, &env->ldt);
sregs.idt.limit = env->idt.limit;
sregs.idt.base = env->idt.base;
memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
sregs.gdt.limit = env->gdt.limit;
sregs.gdt.base = env->gdt.base;
memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
sregs.cr0 = env->cr[0];
sregs.cr2 = env->cr[2];
sregs.cr3 = env->cr[3];
sregs.cr4 = env->cr[4];
sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
sregs.efer = env->efer;
if (env->pdptrs_valid) {
for (i = 0; i < 4; i++) {
sregs.pdptrs[i] = env->pdptrs[i];
}
sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
}
return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
}
static void kvm_msr_buf_reset(X86CPU *cpu)
{
memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
}
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);
entry->index = index;
entry->reserved = 0;
entry->data = value;
msrs->nmsrs++;
}
static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
{
kvm_msr_buf_reset(cpu);
kvm_msr_entry_add(cpu, index, value);
return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
}
void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
{
int ret;
ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
assert(ret == 1);
}
static int kvm_put_tscdeadline_msr(X86CPU *cpu)
{
CPUX86State *env = &cpu->env;
int ret;
if (!has_msr_tsc_deadline) {
return 0;
}
ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
if (ret < 0) {
return ret;
}
assert(ret == 1);
return 0;
}
/*
* 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)
{
int ret;
if (!has_msr_feature_control) {
return 0;
}
ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
cpu->env.msr_ia32_feature_control);
if (ret < 0) {
return ret;
}
assert(ret == 1);
return 0;
}
static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
{
uint32_t default1, can_be_one, can_be_zero;
uint32_t must_be_one;
switch (index) {
case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
default1 = 0x00000016;
break;
case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
default1 = 0x0401e172;
break;
case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
default1 = 0x000011ff;
break;
case MSR_IA32_VMX_TRUE_EXIT_CTLS:
default1 = 0x00036dff;
break;
case MSR_IA32_VMX_PROCBASED_CTLS2:
default1 = 0;
break;
default:
abort();
}
/* If a feature bit is set, the control can be either set or clear.
* Otherwise the value is limited to either 0 or 1 by default1.
*/
can_be_one = features | default1;
can_be_zero = features | ~default1;
must_be_one = ~can_be_zero;
/*
* Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
* Bit 32:63 -> 1 if the control bit can be one.
*/
return must_be_one | (((uint64_t)can_be_one) << 32);
}
static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
{
uint64_t kvm_vmx_basic =
kvm_arch_get_supported_msr_feature(kvm_state,
MSR_IA32_VMX_BASIC);
if (!kvm_vmx_basic) {
/* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
* then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
*/
return;
}
uint64_t kvm_vmx_misc =
kvm_arch_get_supported_msr_feature(kvm_state,
MSR_IA32_VMX_MISC);
uint64_t kvm_vmx_ept_vpid =
kvm_arch_get_supported_msr_feature(kvm_state,
MSR_IA32_VMX_EPT_VPID_CAP);
/*
* If the guest is 64-bit, a value of 1 is allowed for the host address
* space size vmexit control.
*/
uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
/*
* Bits 0-30, 32-44 and 50-53 come from the host. KVM should
* not change them for backwards compatibility.
*/
uint64_t fixed_vmx_basic = kvm_vmx_basic &
(MSR_VMX_BASIC_VMCS_REVISION_MASK |
MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
/*
* Same for bits 0-4 and 25-27. Bits 16-24 (CR3 target count) can
* change in the future but are always zero for now, clear them to be
* future proof. Bits 32-63 in theory could change, though KVM does
* not support dual-monitor treatment and probably never will; mask
* them out as well.
*/
uint64_t fixed_vmx_misc = kvm_vmx_misc &
(MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
/*
* EPT memory types should not change either, so we do not bother
* adding features for them.
*/
uint64_t fixed_vmx_ept_mask =
(f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
f[FEAT_VMX_PROCBASED_CTLS]));
kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
f[FEAT_VMX_PINBASED_CTLS]));
kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
f[FEAT_VMX_ENTRY_CTLS]));
kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,