target/i386: kvm: do not use kvm_check_extension to find paravirtual capabilities
[qemu.git] / target / i386 / kvm.c
1 /*
2 * QEMU KVM support
3 *
4 * Copyright (C) 2006-2008 Qumranet Technologies
5 * Copyright IBM, Corp. 2008
6 *
7 * Authors:
8 * Anthony Liguori <aliguori@us.ibm.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
12 *
13 */
14
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include <sys/ioctl.h>
18 #include <sys/utsname.h>
19
20 #include <linux/kvm.h>
21 #include "standard-headers/asm-x86/kvm_para.h"
22
23 #include "cpu.h"
24 #include "sysemu/sysemu.h"
25 #include "sysemu/hw_accel.h"
26 #include "sysemu/kvm_int.h"
27 #include "sysemu/runstate.h"
28 #include "kvm_i386.h"
29 #include "hyperv.h"
30 #include "hyperv-proto.h"
31
32 #include "exec/gdbstub.h"
33 #include "qemu/host-utils.h"
34 #include "qemu/main-loop.h"
35 #include "qemu/config-file.h"
36 #include "qemu/error-report.h"
37 #include "hw/i386/x86.h"
38 #include "hw/i386/apic.h"
39 #include "hw/i386/apic_internal.h"
40 #include "hw/i386/apic-msidef.h"
41 #include "hw/i386/intel_iommu.h"
42 #include "hw/i386/x86-iommu.h"
43 #include "hw/i386/e820_memory_layout.h"
44
45 #include "hw/pci/pci.h"
46 #include "hw/pci/msi.h"
47 #include "hw/pci/msix.h"
48 #include "migration/blocker.h"
49 #include "exec/memattrs.h"
50 #include "trace.h"
51
52 //#define DEBUG_KVM
53
54 #ifdef DEBUG_KVM
55 #define DPRINTF(fmt, ...) \
56 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
57 #else
58 #define DPRINTF(fmt, ...) \
59 do { } while (0)
60 #endif
61
62 /* From arch/x86/kvm/lapic.h */
63 #define KVM_APIC_BUS_CYCLE_NS 1
64 #define KVM_APIC_BUS_FREQUENCY (1000000000ULL / KVM_APIC_BUS_CYCLE_NS)
65
66 #define MSR_KVM_WALL_CLOCK 0x11
67 #define MSR_KVM_SYSTEM_TIME 0x12
68
69 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
70 * 255 kvm_msr_entry structs */
71 #define MSR_BUF_SIZE 4096
72
73 static void kvm_init_msrs(X86CPU *cpu);
74
75 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
76 KVM_CAP_INFO(SET_TSS_ADDR),
77 KVM_CAP_INFO(EXT_CPUID),
78 KVM_CAP_INFO(MP_STATE),
79 KVM_CAP_LAST_INFO
80 };
81
82 static bool has_msr_star;
83 static bool has_msr_hsave_pa;
84 static bool has_msr_tsc_aux;
85 static bool has_msr_tsc_adjust;
86 static bool has_msr_tsc_deadline;
87 static bool has_msr_feature_control;
88 static bool has_msr_misc_enable;
89 static bool has_msr_smbase;
90 static bool has_msr_bndcfgs;
91 static int lm_capable_kernel;
92 static bool has_msr_hv_hypercall;
93 static bool has_msr_hv_crash;
94 static bool has_msr_hv_reset;
95 static bool has_msr_hv_vpindex;
96 static bool hv_vpindex_settable;
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_hv_frequencies;
101 static bool has_msr_hv_reenlightenment;
102 static bool has_msr_xss;
103 static bool has_msr_umwait;
104 static bool has_msr_spec_ctrl;
105 static bool has_msr_tsx_ctrl;
106 static bool has_msr_virt_ssbd;
107 static bool has_msr_smi_count;
108 static bool has_msr_arch_capabs;
109 static bool has_msr_core_capabs;
110 static bool has_msr_vmx_vmfunc;
111 static bool has_msr_ucode_rev;
112 static bool has_msr_vmx_procbased_ctls2;
113 static bool has_msr_perf_capabs;
114
115 static uint32_t has_architectural_pmu_version;
116 static uint32_t num_architectural_pmu_gp_counters;
117 static uint32_t num_architectural_pmu_fixed_counters;
118
119 static int has_xsave;
120 static int has_xcrs;
121 static int has_pit_state2;
122 static int has_exception_payload;
123
124 static bool has_msr_mcg_ext_ctl;
125
126 static struct kvm_cpuid2 *cpuid_cache;
127 static struct kvm_msr_list *kvm_feature_msrs;
128
129 int kvm_has_pit_state2(void)
130 {
131 return has_pit_state2;
132 }
133
134 bool kvm_has_smm(void)
135 {
136 return kvm_check_extension(kvm_state, KVM_CAP_X86_SMM);
137 }
138
139 bool kvm_has_adjust_clock_stable(void)
140 {
141 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
142
143 return (ret == KVM_CLOCK_TSC_STABLE);
144 }
145
146 bool kvm_has_adjust_clock(void)
147 {
148 return kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
149 }
150
151 bool kvm_has_exception_payload(void)
152 {
153 return has_exception_payload;
154 }
155
156 bool kvm_allows_irq0_override(void)
157 {
158 return !kvm_irqchip_in_kernel() || kvm_has_gsi_routing();
159 }
160
161 static bool kvm_x2apic_api_set_flags(uint64_t flags)
162 {
163 KVMState *s = KVM_STATE(current_accel());
164
165 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
166 }
167
168 #define MEMORIZE(fn, _result) \
169 ({ \
170 static bool _memorized; \
171 \
172 if (_memorized) { \
173 return _result; \
174 } \
175 _memorized = true; \
176 _result = fn; \
177 })
178
179 static bool has_x2apic_api;
180
181 bool kvm_has_x2apic_api(void)
182 {
183 return has_x2apic_api;
184 }
185
186 bool kvm_enable_x2apic(void)
187 {
188 return MEMORIZE(
189 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
190 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
191 has_x2apic_api);
192 }
193
194 bool kvm_hv_vpindex_settable(void)
195 {
196 return hv_vpindex_settable;
197 }
198
199 static int kvm_get_tsc(CPUState *cs)
200 {
201 X86CPU *cpu = X86_CPU(cs);
202 CPUX86State *env = &cpu->env;
203 struct {
204 struct kvm_msrs info;
205 struct kvm_msr_entry entries[1];
206 } msr_data = {};
207 int ret;
208
209 if (env->tsc_valid) {
210 return 0;
211 }
212
213 memset(&msr_data, 0, sizeof(msr_data));
214 msr_data.info.nmsrs = 1;
215 msr_data.entries[0].index = MSR_IA32_TSC;
216 env->tsc_valid = !runstate_is_running();
217
218 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
219 if (ret < 0) {
220 return ret;
221 }
222
223 assert(ret == 1);
224 env->tsc = msr_data.entries[0].data;
225 return 0;
226 }
227
228 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
229 {
230 kvm_get_tsc(cpu);
231 }
232
233 void kvm_synchronize_all_tsc(void)
234 {
235 CPUState *cpu;
236
237 if (kvm_enabled()) {
238 CPU_FOREACH(cpu) {
239 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
240 }
241 }
242 }
243
244 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
245 {
246 struct kvm_cpuid2 *cpuid;
247 int r, size;
248
249 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
250 cpuid = g_malloc0(size);
251 cpuid->nent = max;
252 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
253 if (r == 0 && cpuid->nent >= max) {
254 r = -E2BIG;
255 }
256 if (r < 0) {
257 if (r == -E2BIG) {
258 g_free(cpuid);
259 return NULL;
260 } else {
261 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
262 strerror(-r));
263 exit(1);
264 }
265 }
266 return cpuid;
267 }
268
269 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
270 * for all entries.
271 */
272 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
273 {
274 struct kvm_cpuid2 *cpuid;
275 int max = 1;
276
277 if (cpuid_cache != NULL) {
278 return cpuid_cache;
279 }
280 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
281 max *= 2;
282 }
283 cpuid_cache = cpuid;
284 return cpuid;
285 }
286
287 static bool host_tsx_broken(void)
288 {
289 int family, model, stepping;\
290 char vendor[CPUID_VENDOR_SZ + 1];
291
292 host_vendor_fms(vendor, &family, &model, &stepping);
293
294 /* Check if we are running on a Haswell host known to have broken TSX */
295 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
296 (family == 6) &&
297 ((model == 63 && stepping < 4) ||
298 model == 60 || model == 69 || model == 70);
299 }
300
301 /* Returns the value for a specific register on the cpuid entry
302 */
303 static uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
304 {
305 uint32_t ret = 0;
306 switch (reg) {
307 case R_EAX:
308 ret = entry->eax;
309 break;
310 case R_EBX:
311 ret = entry->ebx;
312 break;
313 case R_ECX:
314 ret = entry->ecx;
315 break;
316 case R_EDX:
317 ret = entry->edx;
318 break;
319 }
320 return ret;
321 }
322
323 /* Find matching entry for function/index on kvm_cpuid2 struct
324 */
325 static struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
326 uint32_t function,
327 uint32_t index)
328 {
329 int i;
330 for (i = 0; i < cpuid->nent; ++i) {
331 if (cpuid->entries[i].function == function &&
332 cpuid->entries[i].index == index) {
333 return &cpuid->entries[i];
334 }
335 }
336 /* not found: */
337 return NULL;
338 }
339
340 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
341 uint32_t index, int reg)
342 {
343 struct kvm_cpuid2 *cpuid;
344 uint32_t ret = 0;
345 uint32_t cpuid_1_edx;
346
347 cpuid = get_supported_cpuid(s);
348
349 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
350 if (entry) {
351 ret = cpuid_entry_get_reg(entry, reg);
352 }
353
354 /* Fixups for the data returned by KVM, below */
355
356 if (function == 1 && reg == R_EDX) {
357 /* KVM before 2.6.30 misreports the following features */
358 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
359 } else if (function == 1 && reg == R_ECX) {
360 /* We can set the hypervisor flag, even if KVM does not return it on
361 * GET_SUPPORTED_CPUID
362 */
363 ret |= CPUID_EXT_HYPERVISOR;
364 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
365 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
366 * and the irqchip is in the kernel.
367 */
368 if (kvm_irqchip_in_kernel() &&
369 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
370 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
371 }
372
373 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
374 * without the in-kernel irqchip
375 */
376 if (!kvm_irqchip_in_kernel()) {
377 ret &= ~CPUID_EXT_X2APIC;
378 }
379
380 if (enable_cpu_pm) {
381 int disable_exits = kvm_check_extension(s,
382 KVM_CAP_X86_DISABLE_EXITS);
383
384 if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
385 ret |= CPUID_EXT_MONITOR;
386 }
387 }
388 } else if (function == 6 && reg == R_EAX) {
389 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
390 } else if (function == 7 && index == 0 && reg == R_EBX) {
391 if (host_tsx_broken()) {
392 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
393 }
394 } else if (function == 7 && index == 0 && reg == R_EDX) {
395 /*
396 * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
397 * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
398 * returned by KVM_GET_MSR_INDEX_LIST.
399 */
400 if (!has_msr_arch_capabs) {
401 ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
402 }
403 } else if (function == 0x80000001 && reg == R_ECX) {
404 /*
405 * It's safe to enable TOPOEXT even if it's not returned by
406 * GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
407 * us to keep CPU models including TOPOEXT runnable on older kernels.
408 */
409 ret |= CPUID_EXT3_TOPOEXT;
410 } else if (function == 0x80000001 && reg == R_EDX) {
411 /* On Intel, kvm returns cpuid according to the Intel spec,
412 * so add missing bits according to the AMD spec:
413 */
414 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
415 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
416 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
417 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
418 * be enabled without the in-kernel irqchip
419 */
420 if (!kvm_irqchip_in_kernel()) {
421 ret &= ~(1U << KVM_FEATURE_PV_UNHALT);
422 }
423 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
424 ret |= 1U << KVM_HINTS_REALTIME;
425 }
426
427 return ret;
428 }
429
430 uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
431 {
432 struct {
433 struct kvm_msrs info;
434 struct kvm_msr_entry entries[1];
435 } msr_data = {};
436 uint64_t value;
437 uint32_t ret, can_be_one, must_be_one;
438
439 if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
440 return 0;
441 }
442
443 /* Check if requested MSR is supported feature MSR */
444 int i;
445 for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
446 if (kvm_feature_msrs->indices[i] == index) {
447 break;
448 }
449 if (i == kvm_feature_msrs->nmsrs) {
450 return 0; /* if the feature MSR is not supported, simply return 0 */
451 }
452
453 msr_data.info.nmsrs = 1;
454 msr_data.entries[0].index = index;
455
456 ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
457 if (ret != 1) {
458 error_report("KVM get MSR (index=0x%x) feature failed, %s",
459 index, strerror(-ret));
460 exit(1);
461 }
462
463 value = msr_data.entries[0].data;
464 switch (index) {
465 case MSR_IA32_VMX_PROCBASED_CTLS2:
466 if (!has_msr_vmx_procbased_ctls2) {
467 /* KVM forgot to add these bits for some time, do this ourselves. */
468 if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) &
469 CPUID_XSAVE_XSAVES) {
470 value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
471 }
472 if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) &
473 CPUID_EXT_RDRAND) {
474 value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
475 }
476 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
477 CPUID_7_0_EBX_INVPCID) {
478 value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
479 }
480 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
481 CPUID_7_0_EBX_RDSEED) {
482 value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
483 }
484 if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) &
485 CPUID_EXT2_RDTSCP) {
486 value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
487 }
488 }
489 /* fall through */
490 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
491 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
492 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
493 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
494 /*
495 * Return true for bits that can be one, but do not have to be one.
496 * The SDM tells us which bits could have a "must be one" setting,
497 * so we can do the opposite transformation in make_vmx_msr_value.
498 */
499 must_be_one = (uint32_t)value;
500 can_be_one = (uint32_t)(value >> 32);
501 return can_be_one & ~must_be_one;
502
503 default:
504 return value;
505 }
506 }
507
508 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
509 int *max_banks)
510 {
511 int r;
512
513 r = kvm_check_extension(s, KVM_CAP_MCE);
514 if (r > 0) {
515 *max_banks = r;
516 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
517 }
518 return -ENOSYS;
519 }
520
521 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
522 {
523 CPUState *cs = CPU(cpu);
524 CPUX86State *env = &cpu->env;
525 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
526 MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S;
527 uint64_t mcg_status = MCG_STATUS_MCIP;
528 int flags = 0;
529
530 if (code == BUS_MCEERR_AR) {
531 status |= MCI_STATUS_AR | 0x134;
532 mcg_status |= MCG_STATUS_EIPV;
533 } else {
534 status |= 0xc0;
535 mcg_status |= MCG_STATUS_RIPV;
536 }
537
538 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
539 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
540 * guest kernel back into env->mcg_ext_ctl.
541 */
542 cpu_synchronize_state(cs);
543 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
544 mcg_status |= MCG_STATUS_LMCE;
545 flags = 0;
546 }
547
548 cpu_x86_inject_mce(NULL, cpu, 9, status, mcg_status, paddr,
549 (MCM_ADDR_PHYS << 6) | 0xc, flags);
550 }
551
552 static void hardware_memory_error(void *host_addr)
553 {
554 error_report("QEMU got Hardware memory error at addr %p", host_addr);
555 exit(1);
556 }
557
558 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
559 {
560 X86CPU *cpu = X86_CPU(c);
561 CPUX86State *env = &cpu->env;
562 ram_addr_t ram_addr;
563 hwaddr paddr;
564
565 /* If we get an action required MCE, it has been injected by KVM
566 * while the VM was running. An action optional MCE instead should
567 * be coming from the main thread, which qemu_init_sigbus identifies
568 * as the "early kill" thread.
569 */
570 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
571
572 if ((env->mcg_cap & MCG_SER_P) && addr) {
573 ram_addr = qemu_ram_addr_from_host(addr);
574 if (ram_addr != RAM_ADDR_INVALID &&
575 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
576 kvm_hwpoison_page_add(ram_addr);
577 kvm_mce_inject(cpu, paddr, code);
578
579 /*
580 * Use different logging severity based on error type.
581 * If there is additional MCE reporting on the hypervisor, QEMU VA
582 * could be another source to identify the PA and MCE details.
583 */
584 if (code == BUS_MCEERR_AR) {
585 error_report("Guest MCE Memory Error at QEMU addr %p and "
586 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
587 addr, paddr, "BUS_MCEERR_AR");
588 } else {
589 warn_report("Guest MCE Memory Error at QEMU addr %p and "
590 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
591 addr, paddr, "BUS_MCEERR_AO");
592 }
593
594 return;
595 }
596
597 if (code == BUS_MCEERR_AO) {
598 warn_report("Hardware memory error at addr %p of type %s "
599 "for memory used by QEMU itself instead of guest system!",
600 addr, "BUS_MCEERR_AO");
601 }
602 }
603
604 if (code == BUS_MCEERR_AR) {
605 hardware_memory_error(addr);
606 }
607
608 /* Hope we are lucky for AO MCE */
609 }
610
611 static void kvm_reset_exception(CPUX86State *env)
612 {
613 env->exception_nr = -1;
614 env->exception_pending = 0;
615 env->exception_injected = 0;
616 env->exception_has_payload = false;
617 env->exception_payload = 0;
618 }
619
620 static void kvm_queue_exception(CPUX86State *env,
621 int32_t exception_nr,
622 uint8_t exception_has_payload,
623 uint64_t exception_payload)
624 {
625 assert(env->exception_nr == -1);
626 assert(!env->exception_pending);
627 assert(!env->exception_injected);
628 assert(!env->exception_has_payload);
629
630 env->exception_nr = exception_nr;
631
632 if (has_exception_payload) {
633 env->exception_pending = 1;
634
635 env->exception_has_payload = exception_has_payload;
636 env->exception_payload = exception_payload;
637 } else {
638 env->exception_injected = 1;
639
640 if (exception_nr == EXCP01_DB) {
641 assert(exception_has_payload);
642 env->dr[6] = exception_payload;
643 } else if (exception_nr == EXCP0E_PAGE) {
644 assert(exception_has_payload);
645 env->cr[2] = exception_payload;
646 } else {
647 assert(!exception_has_payload);
648 }
649 }
650 }
651
652 static int kvm_inject_mce_oldstyle(X86CPU *cpu)
653 {
654 CPUX86State *env = &cpu->env;
655
656 if (!kvm_has_vcpu_events() && env->exception_nr == EXCP12_MCHK) {
657 unsigned int bank, bank_num = env->mcg_cap & 0xff;
658 struct kvm_x86_mce mce;
659
660 kvm_reset_exception(env);
661
662 /*
663 * There must be at least one bank in use if an MCE is pending.
664 * Find it and use its values for the event injection.
665 */
666 for (bank = 0; bank < bank_num; bank++) {
667 if (env->mce_banks[bank * 4 + 1] & MCI_STATUS_VAL) {
668 break;
669 }
670 }
671 assert(bank < bank_num);
672
673 mce.bank = bank;
674 mce.status = env->mce_banks[bank * 4 + 1];
675 mce.mcg_status = env->mcg_status;
676 mce.addr = env->mce_banks[bank * 4 + 2];
677 mce.misc = env->mce_banks[bank * 4 + 3];
678
679 return kvm_vcpu_ioctl(CPU(cpu), KVM_X86_SET_MCE, &mce);
680 }
681 return 0;
682 }
683
684 static void cpu_update_state(void *opaque, int running, RunState state)
685 {
686 CPUX86State *env = opaque;
687
688 if (running) {
689 env->tsc_valid = false;
690 }
691 }
692
693 unsigned long kvm_arch_vcpu_id(CPUState *cs)
694 {
695 X86CPU *cpu = X86_CPU(cs);
696 return cpu->apic_id;
697 }
698
699 #ifndef KVM_CPUID_SIGNATURE_NEXT
700 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
701 #endif
702
703 static bool hyperv_enabled(X86CPU *cpu)
704 {
705 CPUState *cs = CPU(cpu);
706 return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&
707 ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_NOTIFY) ||
708 cpu->hyperv_features || cpu->hyperv_passthrough);
709 }
710
711 /*
712 * Check whether target_freq is within conservative
713 * ntp correctable bounds (250ppm) of freq
714 */
715 static inline bool freq_within_bounds(int freq, int target_freq)
716 {
717 int max_freq = freq + (freq * 250 / 1000000);
718 int min_freq = freq - (freq * 250 / 1000000);
719
720 if (target_freq >= min_freq && target_freq <= max_freq) {
721 return true;
722 }
723
724 return false;
725 }
726
727 static int kvm_arch_set_tsc_khz(CPUState *cs)
728 {
729 X86CPU *cpu = X86_CPU(cs);
730 CPUX86State *env = &cpu->env;
731 int r, cur_freq;
732 bool set_ioctl = false;
733
734 if (!env->tsc_khz) {
735 return 0;
736 }
737
738 cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
739 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) : -ENOTSUP;
740
741 /*
742 * If TSC scaling is supported, attempt to set TSC frequency.
743 */
744 if (kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL)) {
745 set_ioctl = true;
746 }
747
748 /*
749 * If desired TSC frequency is within bounds of NTP correction,
750 * attempt to set TSC frequency.
751 */
752 if (cur_freq != -ENOTSUP && freq_within_bounds(cur_freq, env->tsc_khz)) {
753 set_ioctl = true;
754 }
755
756 r = set_ioctl ?
757 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
758 -ENOTSUP;
759
760 if (r < 0) {
761 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
762 * TSC frequency doesn't match the one we want.
763 */
764 cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
765 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
766 -ENOTSUP;
767 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
768 warn_report("TSC frequency mismatch between "
769 "VM (%" PRId64 " kHz) and host (%d kHz), "
770 "and TSC scaling unavailable",
771 env->tsc_khz, cur_freq);
772 return r;
773 }
774 }
775
776 return 0;
777 }
778
779 static bool tsc_is_stable_and_known(CPUX86State *env)
780 {
781 if (!env->tsc_khz) {
782 return false;
783 }
784 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
785 || env->user_tsc_khz;
786 }
787
788 static struct {
789 const char *desc;
790 struct {
791 uint32_t fw;
792 uint32_t bits;
793 } flags[2];
794 uint64_t dependencies;
795 } kvm_hyperv_properties[] = {
796 [HYPERV_FEAT_RELAXED] = {
797 .desc = "relaxed timing (hv-relaxed)",
798 .flags = {
799 {.fw = FEAT_HYPERV_EAX,
800 .bits = HV_HYPERCALL_AVAILABLE},
801 {.fw = FEAT_HV_RECOMM_EAX,
802 .bits = HV_RELAXED_TIMING_RECOMMENDED}
803 }
804 },
805 [HYPERV_FEAT_VAPIC] = {
806 .desc = "virtual APIC (hv-vapic)",
807 .flags = {
808 {.fw = FEAT_HYPERV_EAX,
809 .bits = HV_HYPERCALL_AVAILABLE | HV_APIC_ACCESS_AVAILABLE},
810 {.fw = FEAT_HV_RECOMM_EAX,
811 .bits = HV_APIC_ACCESS_RECOMMENDED}
812 }
813 },
814 [HYPERV_FEAT_TIME] = {
815 .desc = "clocksources (hv-time)",
816 .flags = {
817 {.fw = FEAT_HYPERV_EAX,
818 .bits = HV_HYPERCALL_AVAILABLE | HV_TIME_REF_COUNT_AVAILABLE |
819 HV_REFERENCE_TSC_AVAILABLE}
820 }
821 },
822 [HYPERV_FEAT_CRASH] = {
823 .desc = "crash MSRs (hv-crash)",
824 .flags = {
825 {.fw = FEAT_HYPERV_EDX,
826 .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
827 }
828 },
829 [HYPERV_FEAT_RESET] = {
830 .desc = "reset MSR (hv-reset)",
831 .flags = {
832 {.fw = FEAT_HYPERV_EAX,
833 .bits = HV_RESET_AVAILABLE}
834 }
835 },
836 [HYPERV_FEAT_VPINDEX] = {
837 .desc = "VP_INDEX MSR (hv-vpindex)",
838 .flags = {
839 {.fw = FEAT_HYPERV_EAX,
840 .bits = HV_VP_INDEX_AVAILABLE}
841 }
842 },
843 [HYPERV_FEAT_RUNTIME] = {
844 .desc = "VP_RUNTIME MSR (hv-runtime)",
845 .flags = {
846 {.fw = FEAT_HYPERV_EAX,
847 .bits = HV_VP_RUNTIME_AVAILABLE}
848 }
849 },
850 [HYPERV_FEAT_SYNIC] = {
851 .desc = "synthetic interrupt controller (hv-synic)",
852 .flags = {
853 {.fw = FEAT_HYPERV_EAX,
854 .bits = HV_SYNIC_AVAILABLE}
855 }
856 },
857 [HYPERV_FEAT_STIMER] = {
858 .desc = "synthetic timers (hv-stimer)",
859 .flags = {
860 {.fw = FEAT_HYPERV_EAX,
861 .bits = HV_SYNTIMERS_AVAILABLE}
862 },
863 .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
864 },
865 [HYPERV_FEAT_FREQUENCIES] = {
866 .desc = "frequency MSRs (hv-frequencies)",
867 .flags = {
868 {.fw = FEAT_HYPERV_EAX,
869 .bits = HV_ACCESS_FREQUENCY_MSRS},
870 {.fw = FEAT_HYPERV_EDX,
871 .bits = HV_FREQUENCY_MSRS_AVAILABLE}
872 }
873 },
874 [HYPERV_FEAT_REENLIGHTENMENT] = {
875 .desc = "reenlightenment MSRs (hv-reenlightenment)",
876 .flags = {
877 {.fw = FEAT_HYPERV_EAX,
878 .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
879 }
880 },
881 [HYPERV_FEAT_TLBFLUSH] = {
882 .desc = "paravirtualized TLB flush (hv-tlbflush)",
883 .flags = {
884 {.fw = FEAT_HV_RECOMM_EAX,
885 .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
886 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
887 },
888 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
889 },
890 [HYPERV_FEAT_EVMCS] = {
891 .desc = "enlightened VMCS (hv-evmcs)",
892 .flags = {
893 {.fw = FEAT_HV_RECOMM_EAX,
894 .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
895 },
896 .dependencies = BIT(HYPERV_FEAT_VAPIC)
897 },
898 [HYPERV_FEAT_IPI] = {
899 .desc = "paravirtualized IPI (hv-ipi)",
900 .flags = {
901 {.fw = FEAT_HV_RECOMM_EAX,
902 .bits = HV_CLUSTER_IPI_RECOMMENDED |
903 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
904 },
905 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
906 },
907 [HYPERV_FEAT_STIMER_DIRECT] = {
908 .desc = "direct mode synthetic timers (hv-stimer-direct)",
909 .flags = {
910 {.fw = FEAT_HYPERV_EDX,
911 .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
912 },
913 .dependencies = BIT(HYPERV_FEAT_STIMER)
914 },
915 };
916
917 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max)
918 {
919 struct kvm_cpuid2 *cpuid;
920 int r, size;
921
922 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
923 cpuid = g_malloc0(size);
924 cpuid->nent = max;
925
926 r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
927 if (r == 0 && cpuid->nent >= max) {
928 r = -E2BIG;
929 }
930 if (r < 0) {
931 if (r == -E2BIG) {
932 g_free(cpuid);
933 return NULL;
934 } else {
935 fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
936 strerror(-r));
937 exit(1);
938 }
939 }
940 return cpuid;
941 }
942
943 /*
944 * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
945 * for all entries.
946 */
947 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
948 {
949 struct kvm_cpuid2 *cpuid;
950 int max = 7; /* 0x40000000..0x40000005, 0x4000000A */
951
952 /*
953 * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
954 * -E2BIG, however, it doesn't report back the right size. Keep increasing
955 * it and re-trying until we succeed.
956 */
957 while ((cpuid = try_get_hv_cpuid(cs, max)) == NULL) {
958 max++;
959 }
960 return cpuid;
961 }
962
963 /*
964 * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
965 * leaves from KVM_CAP_HYPERV* and present MSRs data.
966 */
967 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
968 {
969 X86CPU *cpu = X86_CPU(cs);
970 struct kvm_cpuid2 *cpuid;
971 struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
972
973 /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
974 cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
975 cpuid->nent = 2;
976
977 /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
978 entry_feat = &cpuid->entries[0];
979 entry_feat->function = HV_CPUID_FEATURES;
980
981 entry_recomm = &cpuid->entries[1];
982 entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
983 entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
984
985 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
986 entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
987 entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
988 entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
989 entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
990 entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
991 }
992
993 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
994 entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
995 entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
996 }
997
998 if (has_msr_hv_frequencies) {
999 entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
1000 entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
1001 }
1002
1003 if (has_msr_hv_crash) {
1004 entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
1005 }
1006
1007 if (has_msr_hv_reenlightenment) {
1008 entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
1009 }
1010
1011 if (has_msr_hv_reset) {
1012 entry_feat->eax |= HV_RESET_AVAILABLE;
1013 }
1014
1015 if (has_msr_hv_vpindex) {
1016 entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
1017 }
1018
1019 if (has_msr_hv_runtime) {
1020 entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
1021 }
1022
1023 if (has_msr_hv_synic) {
1024 unsigned int cap = cpu->hyperv_synic_kvm_only ?
1025 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1026
1027 if (kvm_check_extension(cs->kvm_state, cap) > 0) {
1028 entry_feat->eax |= HV_SYNIC_AVAILABLE;
1029 }
1030 }
1031
1032 if (has_msr_hv_stimer) {
1033 entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
1034 }
1035
1036 if (kvm_check_extension(cs->kvm_state,
1037 KVM_CAP_HYPERV_TLBFLUSH) > 0) {
1038 entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
1039 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1040 }
1041
1042 if (kvm_check_extension(cs->kvm_state,
1043 KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1044 entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1045 }
1046
1047 if (kvm_check_extension(cs->kvm_state,
1048 KVM_CAP_HYPERV_SEND_IPI) > 0) {
1049 entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
1050 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1051 }
1052
1053 return cpuid;
1054 }
1055
1056 static int hv_cpuid_get_fw(struct kvm_cpuid2 *cpuid, int fw, uint32_t *r)
1057 {
1058 struct kvm_cpuid_entry2 *entry;
1059 uint32_t func;
1060 int reg;
1061
1062 switch (fw) {
1063 case FEAT_HYPERV_EAX:
1064 reg = R_EAX;
1065 func = HV_CPUID_FEATURES;
1066 break;
1067 case FEAT_HYPERV_EDX:
1068 reg = R_EDX;
1069 func = HV_CPUID_FEATURES;
1070 break;
1071 case FEAT_HV_RECOMM_EAX:
1072 reg = R_EAX;
1073 func = HV_CPUID_ENLIGHTMENT_INFO;
1074 break;
1075 default:
1076 return -EINVAL;
1077 }
1078
1079 entry = cpuid_find_entry(cpuid, func, 0);
1080 if (!entry) {
1081 return -ENOENT;
1082 }
1083
1084 switch (reg) {
1085 case R_EAX:
1086 *r = entry->eax;
1087 break;
1088 case R_EDX:
1089 *r = entry->edx;
1090 break;
1091 default:
1092 return -EINVAL;
1093 }
1094
1095 return 0;
1096 }
1097
1098 static int hv_cpuid_check_and_set(CPUState *cs, struct kvm_cpuid2 *cpuid,
1099 int feature)
1100 {
1101 X86CPU *cpu = X86_CPU(cs);
1102 CPUX86State *env = &cpu->env;
1103 uint32_t r, fw, bits;
1104 uint64_t deps;
1105 int i, dep_feat;
1106
1107 if (!hyperv_feat_enabled(cpu, feature) && !cpu->hyperv_passthrough) {
1108 return 0;
1109 }
1110
1111 deps = kvm_hyperv_properties[feature].dependencies;
1112 while (deps) {
1113 dep_feat = ctz64(deps);
1114 if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1115 fprintf(stderr,
1116 "Hyper-V %s requires Hyper-V %s\n",
1117 kvm_hyperv_properties[feature].desc,
1118 kvm_hyperv_properties[dep_feat].desc);
1119 return 1;
1120 }
1121 deps &= ~(1ull << dep_feat);
1122 }
1123
1124 for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1125 fw = kvm_hyperv_properties[feature].flags[i].fw;
1126 bits = kvm_hyperv_properties[feature].flags[i].bits;
1127
1128 if (!fw) {
1129 continue;
1130 }
1131
1132 if (hv_cpuid_get_fw(cpuid, fw, &r) || (r & bits) != bits) {
1133 if (hyperv_feat_enabled(cpu, feature)) {
1134 fprintf(stderr,
1135 "Hyper-V %s is not supported by kernel\n",
1136 kvm_hyperv_properties[feature].desc);
1137 return 1;
1138 } else {
1139 return 0;
1140 }
1141 }
1142
1143 env->features[fw] |= bits;
1144 }
1145
1146 if (cpu->hyperv_passthrough) {
1147 cpu->hyperv_features |= BIT(feature);
1148 }
1149
1150 return 0;
1151 }
1152
1153 /*
1154 * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent in
1155 * case of success, errno < 0 in case of failure and 0 when no Hyper-V
1156 * extentions are enabled.
1157 */
1158 static int hyperv_handle_properties(CPUState *cs,
1159 struct kvm_cpuid_entry2 *cpuid_ent)
1160 {
1161 X86CPU *cpu = X86_CPU(cs);
1162 CPUX86State *env = &cpu->env;
1163 struct kvm_cpuid2 *cpuid;
1164 struct kvm_cpuid_entry2 *c;
1165 uint32_t signature[3];
1166 uint32_t cpuid_i = 0;
1167 int r;
1168
1169 if (!hyperv_enabled(cpu))
1170 return 0;
1171
1172 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ||
1173 cpu->hyperv_passthrough) {
1174 uint16_t evmcs_version;
1175
1176 r = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1177 (uintptr_t)&evmcs_version);
1178
1179 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) && r) {
1180 fprintf(stderr, "Hyper-V %s is not supported by kernel\n",
1181 kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1182 return -ENOSYS;
1183 }
1184
1185 if (!r) {
1186 env->features[FEAT_HV_RECOMM_EAX] |=
1187 HV_ENLIGHTENED_VMCS_RECOMMENDED;
1188 env->features[FEAT_HV_NESTED_EAX] = evmcs_version;
1189 }
1190 }
1191
1192 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1193 cpuid = get_supported_hv_cpuid(cs);
1194 } else {
1195 cpuid = get_supported_hv_cpuid_legacy(cs);
1196 }
1197
1198 if (cpu->hyperv_passthrough) {
1199 memcpy(cpuid_ent, &cpuid->entries[0],
1200 cpuid->nent * sizeof(cpuid->entries[0]));
1201
1202 c = cpuid_find_entry(cpuid, HV_CPUID_FEATURES, 0);
1203 if (c) {
1204 env->features[FEAT_HYPERV_EAX] = c->eax;
1205 env->features[FEAT_HYPERV_EBX] = c->ebx;
1206 env->features[FEAT_HYPERV_EDX] = c->eax;
1207 }
1208 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1209 if (c) {
1210 env->features[FEAT_HV_RECOMM_EAX] = c->eax;
1211
1212 /* hv-spinlocks may have been overriden */
1213 if (cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_NOTIFY) {
1214 c->ebx = cpu->hyperv_spinlock_attempts;
1215 }
1216 }
1217 c = cpuid_find_entry(cpuid, HV_CPUID_NESTED_FEATURES, 0);
1218 if (c) {
1219 env->features[FEAT_HV_NESTED_EAX] = c->eax;
1220 }
1221 }
1222
1223 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
1224 env->features[FEAT_HV_RECOMM_EAX] |= HV_NO_NONARCH_CORESHARING;
1225 } else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
1226 c = cpuid_find_entry(cpuid, HV_CPUID_ENLIGHTMENT_INFO, 0);
1227 if (c) {
1228 env->features[FEAT_HV_RECOMM_EAX] |=
1229 c->eax & HV_NO_NONARCH_CORESHARING;
1230 }
1231 }
1232
1233 /* Features */
1234 r = hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RELAXED);
1235 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VAPIC);
1236 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TIME);
1237 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_CRASH);
1238 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RESET);
1239 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_VPINDEX);
1240 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_RUNTIME);
1241 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_SYNIC);
1242 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER);
1243 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_FREQUENCIES);
1244 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_REENLIGHTENMENT);
1245 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_TLBFLUSH);
1246 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_EVMCS);
1247 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_IPI);
1248 r |= hv_cpuid_check_and_set(cs, cpuid, HYPERV_FEAT_STIMER_DIRECT);
1249
1250 /* Additional dependencies not covered by kvm_hyperv_properties[] */
1251 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1252 !cpu->hyperv_synic_kvm_only &&
1253 !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1254 fprintf(stderr, "Hyper-V %s requires Hyper-V %s\n",
1255 kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1256 kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1257 r |= 1;
1258 }
1259
1260 /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1261 env->features[FEAT_HYPERV_EDX] |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1262
1263 if (r) {
1264 r = -ENOSYS;
1265 goto free;
1266 }
1267
1268 if (cpu->hyperv_passthrough) {
1269 /* We already copied all feature words from KVM as is */
1270 r = cpuid->nent;
1271 goto free;
1272 }
1273
1274 c = &cpuid_ent[cpuid_i++];
1275 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1276 if (!cpu->hyperv_vendor_id) {
1277 memcpy(signature, "Microsoft Hv", 12);
1278 } else {
1279 size_t len = strlen(cpu->hyperv_vendor_id);
1280
1281 if (len > 12) {
1282 error_report("hv-vendor-id truncated to 12 characters");
1283 len = 12;
1284 }
1285 memset(signature, 0, 12);
1286 memcpy(signature, cpu->hyperv_vendor_id, len);
1287 }
1288 c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1289 HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1290 c->ebx = signature[0];
1291 c->ecx = signature[1];
1292 c->edx = signature[2];
1293
1294 c = &cpuid_ent[cpuid_i++];
1295 c->function = HV_CPUID_INTERFACE;
1296 memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
1297 c->eax = signature[0];
1298 c->ebx = 0;
1299 c->ecx = 0;
1300 c->edx = 0;
1301
1302 c = &cpuid_ent[cpuid_i++];
1303 c->function = HV_CPUID_VERSION;
1304 c->eax = 0x00001bbc;
1305 c->ebx = 0x00060001;
1306
1307 c = &cpuid_ent[cpuid_i++];
1308 c->function = HV_CPUID_FEATURES;
1309 c->eax = env->features[FEAT_HYPERV_EAX];
1310 c->ebx = env->features[FEAT_HYPERV_EBX];
1311 c->edx = env->features[FEAT_HYPERV_EDX];
1312
1313 c = &cpuid_ent[cpuid_i++];
1314 c->function = HV_CPUID_ENLIGHTMENT_INFO;
1315 c->eax = env->features[FEAT_HV_RECOMM_EAX];
1316 c->ebx = cpu->hyperv_spinlock_attempts;
1317
1318 c = &cpuid_ent[cpuid_i++];
1319 c->function = HV_CPUID_IMPLEMENT_LIMITS;
1320 c->eax = cpu->hv_max_vps;
1321 c->ebx = 0x40;
1322
1323 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1324 __u32 function;
1325
1326 /* Create zeroed 0x40000006..0x40000009 leaves */
1327 for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1328 function < HV_CPUID_NESTED_FEATURES; function++) {
1329 c = &cpuid_ent[cpuid_i++];
1330 c->function = function;
1331 }
1332
1333 c = &cpuid_ent[cpuid_i++];
1334 c->function = HV_CPUID_NESTED_FEATURES;
1335 c->eax = env->features[FEAT_HV_NESTED_EAX];
1336 }
1337 r = cpuid_i;
1338
1339 free:
1340 g_free(cpuid);
1341
1342 return r;
1343 }
1344
1345 static Error *hv_passthrough_mig_blocker;
1346 static Error *hv_no_nonarch_cs_mig_blocker;
1347
1348 static int hyperv_init_vcpu(X86CPU *cpu)
1349 {
1350 CPUState *cs = CPU(cpu);
1351 Error *local_err = NULL;
1352 int ret;
1353
1354 if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1355 error_setg(&hv_passthrough_mig_blocker,
1356 "'hv-passthrough' CPU flag prevents migration, use explicit"
1357 " set of hv-* flags instead");
1358 ret = migrate_add_blocker(hv_passthrough_mig_blocker, &local_err);
1359 if (local_err) {
1360 error_report_err(local_err);
1361 error_free(hv_passthrough_mig_blocker);
1362 return ret;
1363 }
1364 }
1365
1366 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
1367 hv_no_nonarch_cs_mig_blocker == NULL) {
1368 error_setg(&hv_no_nonarch_cs_mig_blocker,
1369 "'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
1370 " use explicit 'hv-no-nonarch-coresharing=on' instead (but"
1371 " make sure SMT is disabled and/or that vCPUs are properly"
1372 " pinned)");
1373 ret = migrate_add_blocker(hv_no_nonarch_cs_mig_blocker, &local_err);
1374 if (local_err) {
1375 error_report_err(local_err);
1376 error_free(hv_no_nonarch_cs_mig_blocker);
1377 return ret;
1378 }
1379 }
1380
1381 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1382 /*
1383 * the kernel doesn't support setting vp_index; assert that its value
1384 * is in sync
1385 */
1386 struct {
1387 struct kvm_msrs info;
1388 struct kvm_msr_entry entries[1];
1389 } msr_data = {
1390 .info.nmsrs = 1,
1391 .entries[0].index = HV_X64_MSR_VP_INDEX,
1392 };
1393
1394 ret = kvm_vcpu_ioctl(cs, KVM_GET_MSRS, &msr_data);
1395 if (ret < 0) {
1396 return ret;
1397 }
1398 assert(ret == 1);
1399
1400 if (msr_data.entries[0].data != hyperv_vp_index(CPU(cpu))) {
1401 error_report("kernel's vp_index != QEMU's vp_index");
1402 return -ENXIO;
1403 }
1404 }
1405
1406 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1407 uint32_t synic_cap = cpu->hyperv_synic_kvm_only ?
1408 KVM_CAP_HYPERV_SYNIC : KVM_CAP_HYPERV_SYNIC2;
1409 ret = kvm_vcpu_enable_cap(cs, synic_cap, 0);
1410 if (ret < 0) {
1411 error_report("failed to turn on HyperV SynIC in KVM: %s",
1412 strerror(-ret));
1413 return ret;
1414 }
1415
1416 if (!cpu->hyperv_synic_kvm_only) {
1417 ret = hyperv_x86_synic_add(cpu);
1418 if (ret < 0) {
1419 error_report("failed to create HyperV SynIC: %s",
1420 strerror(-ret));
1421 return ret;
1422 }
1423 }
1424 }
1425
1426 return 0;
1427 }
1428
1429 static Error *invtsc_mig_blocker;
1430
1431 #define KVM_MAX_CPUID_ENTRIES 100
1432
1433 int kvm_arch_init_vcpu(CPUState *cs)
1434 {
1435 struct {
1436 struct kvm_cpuid2 cpuid;
1437 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
1438 } cpuid_data;
1439 /*
1440 * The kernel defines these structs with padding fields so there
1441 * should be no extra padding in our cpuid_data struct.
1442 */
1443 QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
1444 sizeof(struct kvm_cpuid2) +
1445 sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
1446
1447 X86CPU *cpu = X86_CPU(cs);
1448 CPUX86State *env = &cpu->env;
1449 uint32_t limit, i, j, cpuid_i;
1450 uint32_t unused;
1451 struct kvm_cpuid_entry2 *c;
1452 uint32_t signature[3];
1453 int kvm_base = KVM_CPUID_SIGNATURE;
1454 int max_nested_state_len;
1455 int r;
1456 Error *local_err = NULL;
1457
1458 memset(&cpuid_data, 0, sizeof(cpuid_data));
1459
1460 cpuid_i = 0;
1461
1462 r = kvm_arch_set_tsc_khz(cs);
1463 if (r < 0) {
1464 return r;
1465 }
1466
1467 /* vcpu's TSC frequency is either specified by user, or following
1468 * the value used by KVM if the former is not present. In the
1469 * latter case, we query it from KVM and record in env->tsc_khz,
1470 * so that vcpu's TSC frequency can be migrated later via this field.
1471 */
1472 if (!env->tsc_khz) {
1473 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
1474 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
1475 -ENOTSUP;
1476 if (r > 0) {
1477 env->tsc_khz = r;
1478 }
1479 }
1480
1481 env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
1482
1483 /* Paravirtualization CPUIDs */
1484 r = hyperv_handle_properties(cs, cpuid_data.entries);
1485 if (r < 0) {
1486 return r;
1487 } else if (r > 0) {
1488 cpuid_i = r;
1489 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
1490 has_msr_hv_hypercall = true;
1491 }
1492
1493 if (cpu->expose_kvm) {
1494 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
1495 c = &cpuid_data.entries[cpuid_i++];
1496 c->function = KVM_CPUID_SIGNATURE | kvm_base;
1497 c->eax = KVM_CPUID_FEATURES | kvm_base;
1498 c->ebx = signature[0];
1499 c->ecx = signature[1];
1500 c->edx = signature[2];
1501
1502 c = &cpuid_data.entries[cpuid_i++];
1503 c->function = KVM_CPUID_FEATURES | kvm_base;
1504 c->eax = env->features[FEAT_KVM];
1505 c->edx = env->features[FEAT_KVM_HINTS];
1506 }
1507
1508 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1509
1510 for (i = 0; i <= limit; i++) {
1511 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1512 fprintf(stderr, "unsupported level value: 0x%x\n", limit);
1513 abort();
1514 }
1515 c = &cpuid_data.entries[cpuid_i++];
1516
1517 switch (i) {
1518 case 2: {
1519 /* Keep reading function 2 till all the input is received */
1520 int times;
1521
1522 c->function = i;
1523 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1524 KVM_CPUID_FLAG_STATE_READ_NEXT;
1525 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1526 times = c->eax & 0xff;
1527
1528 for (j = 1; j < times; ++j) {
1529 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1530 fprintf(stderr, "cpuid_data is full, no space for "
1531 "cpuid(eax:2):eax & 0xf = 0x%x\n", times);
1532 abort();
1533 }
1534 c = &cpuid_data.entries[cpuid_i++];
1535 c->function = i;
1536 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1537 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1538 }
1539 break;
1540 }
1541 case 0x1f:
1542 if (env->nr_dies < 2) {
1543 break;
1544 }
1545 /* fallthrough */
1546 case 4:
1547 case 0xb:
1548 case 0xd:
1549 for (j = 0; ; j++) {
1550 if (i == 0xd && j == 64) {
1551 break;
1552 }
1553
1554 if (i == 0x1f && j == 64) {
1555 break;
1556 }
1557
1558 c->function = i;
1559 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1560 c->index = j;
1561 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1562
1563 if (i == 4 && c->eax == 0) {
1564 break;
1565 }
1566 if (i == 0xb && !(c->ecx & 0xff00)) {
1567 break;
1568 }
1569 if (i == 0x1f && !(c->ecx & 0xff00)) {
1570 break;
1571 }
1572 if (i == 0xd && c->eax == 0) {
1573 continue;
1574 }
1575 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1576 fprintf(stderr, "cpuid_data is full, no space for "
1577 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1578 abort();
1579 }
1580 c = &cpuid_data.entries[cpuid_i++];
1581 }
1582 break;
1583 case 0x7:
1584 case 0x14: {
1585 uint32_t times;
1586
1587 c->function = i;
1588 c->index = 0;
1589 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1590 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1591 times = c->eax;
1592
1593 for (j = 1; j <= times; ++j) {
1594 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1595 fprintf(stderr, "cpuid_data is full, no space for "
1596 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1597 abort();
1598 }
1599 c = &cpuid_data.entries[cpuid_i++];
1600 c->function = i;
1601 c->index = j;
1602 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1603 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1604 }
1605 break;
1606 }
1607 default:
1608 c->function = i;
1609 c->flags = 0;
1610 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1611 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1612 /*
1613 * KVM already returns all zeroes if a CPUID entry is missing,
1614 * so we can omit it and avoid hitting KVM's 80-entry limit.
1615 */
1616 cpuid_i--;
1617 }
1618 break;
1619 }
1620 }
1621
1622 if (limit >= 0x0a) {
1623 uint32_t eax, edx;
1624
1625 cpu_x86_cpuid(env, 0x0a, 0, &eax, &unused, &unused, &edx);
1626
1627 has_architectural_pmu_version = eax & 0xff;
1628 if (has_architectural_pmu_version > 0) {
1629 num_architectural_pmu_gp_counters = (eax & 0xff00) >> 8;
1630
1631 /* Shouldn't be more than 32, since that's the number of bits
1632 * available in EBX to tell us _which_ counters are available.
1633 * Play it safe.
1634 */
1635 if (num_architectural_pmu_gp_counters > MAX_GP_COUNTERS) {
1636 num_architectural_pmu_gp_counters = MAX_GP_COUNTERS;
1637 }
1638
1639 if (has_architectural_pmu_version > 1) {
1640 num_architectural_pmu_fixed_counters = edx & 0x1f;
1641
1642 if (num_architectural_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
1643 num_architectural_pmu_fixed_counters = MAX_FIXED_COUNTERS;
1644 }
1645 }
1646 }
1647 }
1648
1649 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1650
1651 for (i = 0x80000000; i <= limit; i++) {
1652 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1653 fprintf(stderr, "unsupported xlevel value: 0x%x\n", limit);
1654 abort();
1655 }
1656 c = &cpuid_data.entries[cpuid_i++];
1657
1658 switch (i) {
1659 case 0x8000001d:
1660 /* Query for all AMD cache information leaves */
1661 for (j = 0; ; j++) {
1662 c->function = i;
1663 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1664 c->index = j;
1665 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1666
1667 if (c->eax == 0) {
1668 break;
1669 }
1670 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1671 fprintf(stderr, "cpuid_data is full, no space for "
1672 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
1673 abort();
1674 }
1675 c = &cpuid_data.entries[cpuid_i++];
1676 }
1677 break;
1678 default:
1679 c->function = i;
1680 c->flags = 0;
1681 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1682 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1683 /*
1684 * KVM already returns all zeroes if a CPUID entry is missing,
1685 * so we can omit it and avoid hitting KVM's 80-entry limit.
1686 */
1687 cpuid_i--;
1688 }
1689 break;
1690 }
1691 }
1692
1693 /* Call Centaur's CPUID instructions they are supported. */
1694 if (env->cpuid_xlevel2 > 0) {
1695 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
1696
1697 for (i = 0xC0000000; i <= limit; i++) {
1698 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1699 fprintf(stderr, "unsupported xlevel2 value: 0x%x\n", limit);
1700 abort();
1701 }
1702 c = &cpuid_data.entries[cpuid_i++];
1703
1704 c->function = i;
1705 c->flags = 0;
1706 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1707 }
1708 }
1709
1710 cpuid_data.cpuid.nent = cpuid_i;
1711
1712 if (((env->cpuid_version >> 8)&0xF) >= 6
1713 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
1714 (CPUID_MCE | CPUID_MCA)
1715 && kvm_check_extension(cs->kvm_state, KVM_CAP_MCE) > 0) {
1716 uint64_t mcg_cap, unsupported_caps;
1717 int banks;
1718 int ret;
1719
1720 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
1721 if (ret < 0) {
1722 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
1723 return ret;
1724 }
1725
1726 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
1727 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
1728 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
1729 return -ENOTSUP;
1730 }
1731
1732 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
1733 if (unsupported_caps) {
1734 if (unsupported_caps & MCG_LMCE_P) {
1735 error_report("kvm: LMCE not supported");
1736 return -ENOTSUP;
1737 }
1738 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
1739 unsupported_caps);
1740 }
1741
1742 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
1743 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
1744 if (ret < 0) {
1745 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
1746 return ret;
1747 }
1748 }
1749
1750 cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
1751
1752 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
1753 if (c) {
1754 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
1755 !!(c->ecx & CPUID_EXT_SMX);
1756 }
1757
1758 if (env->mcg_cap & MCG_LMCE_P) {
1759 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
1760 }
1761
1762 if (!env->user_tsc_khz) {
1763 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
1764 invtsc_mig_blocker == NULL) {
1765 error_setg(&invtsc_mig_blocker,
1766 "State blocked by non-migratable CPU device"
1767 " (invtsc flag)");
1768 r = migrate_add_blocker(invtsc_mig_blocker, &local_err);
1769 if (local_err) {
1770 error_report_err(local_err);
1771 error_free(invtsc_mig_blocker);
1772 return r;
1773 }
1774 }
1775 }
1776
1777 if (cpu->vmware_cpuid_freq
1778 /* Guests depend on 0x40000000 to detect this feature, so only expose
1779 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
1780 && cpu->expose_kvm
1781 && kvm_base == KVM_CPUID_SIGNATURE
1782 /* TSC clock must be stable and known for this feature. */
1783 && tsc_is_stable_and_known(env)) {
1784
1785 c = &cpuid_data.entries[cpuid_i++];
1786 c->function = KVM_CPUID_SIGNATURE | 0x10;
1787 c->eax = env->tsc_khz;
1788 c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
1789 c->ecx = c->edx = 0;
1790
1791 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
1792 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
1793 }
1794
1795 cpuid_data.cpuid.nent = cpuid_i;
1796
1797 cpuid_data.cpuid.padding = 0;
1798 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
1799 if (r) {
1800 goto fail;
1801 }
1802
1803 if (has_xsave) {
1804 env->xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));
1805 memset(env->xsave_buf, 0, sizeof(struct kvm_xsave));
1806 }
1807
1808 max_nested_state_len = kvm_max_nested_state_length();
1809 if (max_nested_state_len > 0) {
1810 assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
1811
1812 if (cpu_has_vmx(env) || cpu_has_svm(env)) {
1813 struct kvm_vmx_nested_state_hdr *vmx_hdr;
1814
1815 env->nested_state = g_malloc0(max_nested_state_len);
1816 env->nested_state->size = max_nested_state_len;
1817 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1818
1819 if (cpu_has_vmx(env)) {
1820 vmx_hdr = &env->nested_state->hdr.vmx;
1821 vmx_hdr->vmxon_pa = -1ull;
1822 vmx_hdr->vmcs12_pa = -1ull;
1823 }
1824 }
1825 }
1826
1827 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
1828
1829 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
1830 has_msr_tsc_aux = false;
1831 }
1832
1833 kvm_init_msrs(cpu);
1834
1835 r = hyperv_init_vcpu(cpu);
1836 if (r) {
1837 goto fail;
1838 }
1839
1840 return 0;
1841
1842 fail:
1843 migrate_del_blocker(invtsc_mig_blocker);
1844
1845 return r;
1846 }
1847
1848 int kvm_arch_destroy_vcpu(CPUState *cs)
1849 {
1850 X86CPU *cpu = X86_CPU(cs);
1851 CPUX86State *env = &cpu->env;
1852
1853 if (cpu->kvm_msr_buf) {
1854 g_free(cpu->kvm_msr_buf);
1855 cpu->kvm_msr_buf = NULL;
1856 }
1857
1858 if (env->nested_state) {
1859 g_free(env->nested_state);
1860 env->nested_state = NULL;
1861 }
1862
1863 qemu_del_vm_change_state_handler(cpu->vmsentry);
1864
1865 return 0;
1866 }
1867
1868 void kvm_arch_reset_vcpu(X86CPU *cpu)
1869 {
1870 CPUX86State *env = &cpu->env;
1871
1872 env->xcr0 = 1;
1873 if (kvm_irqchip_in_kernel()) {
1874 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
1875 KVM_MP_STATE_UNINITIALIZED;
1876 } else {
1877 env->mp_state = KVM_MP_STATE_RUNNABLE;
1878 }
1879
1880 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1881 int i;
1882 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
1883 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
1884 }
1885
1886 hyperv_x86_synic_reset(cpu);
1887 }
1888 /* enabled by default */
1889 env->poll_control_msr = 1;
1890 }
1891
1892 void kvm_arch_do_init_vcpu(X86CPU *cpu)
1893 {
1894 CPUX86State *env = &cpu->env;
1895
1896 /* APs get directly into wait-for-SIPI state. */
1897 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
1898 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
1899 }
1900 }
1901
1902 static int kvm_get_supported_feature_msrs(KVMState *s)
1903 {
1904 int ret = 0;
1905
1906 if (kvm_feature_msrs != NULL) {
1907 return 0;
1908 }
1909
1910 if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
1911 return 0;
1912 }
1913
1914 struct kvm_msr_list msr_list;
1915
1916 msr_list.nmsrs = 0;
1917 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
1918 if (ret < 0 && ret != -E2BIG) {
1919 error_report("Fetch KVM feature MSR list failed: %s",
1920 strerror(-ret));
1921 return ret;
1922 }
1923
1924 assert(msr_list.nmsrs > 0);
1925 kvm_feature_msrs = (struct kvm_msr_list *) \
1926 g_malloc0(sizeof(msr_list) +
1927 msr_list.nmsrs * sizeof(msr_list.indices[0]));
1928
1929 kvm_feature_msrs->nmsrs = msr_list.nmsrs;
1930 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
1931
1932 if (ret < 0) {
1933 error_report("Fetch KVM feature MSR list failed: %s",
1934 strerror(-ret));
1935 g_free(kvm_feature_msrs);
1936 kvm_feature_msrs = NULL;
1937 return ret;
1938 }
1939
1940 return 0;
1941 }
1942
1943 static int kvm_get_supported_msrs(KVMState *s)
1944 {
1945 int ret = 0;
1946 struct kvm_msr_list msr_list, *kvm_msr_list;
1947
1948 /*
1949 * Obtain MSR list from KVM. These are the MSRs that we must
1950 * save/restore.
1951 */
1952 msr_list.nmsrs = 0;
1953 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
1954 if (ret < 0 && ret != -E2BIG) {
1955 return ret;
1956 }
1957 /*
1958 * Old kernel modules had a bug and could write beyond the provided
1959 * memory. Allocate at least a safe amount of 1K.
1960 */
1961 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
1962 msr_list.nmsrs *
1963 sizeof(msr_list.indices[0])));
1964
1965 kvm_msr_list->nmsrs = msr_list.nmsrs;
1966 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
1967 if (ret >= 0) {
1968 int i;
1969
1970 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
1971 switch (kvm_msr_list->indices[i]) {
1972 case MSR_STAR:
1973 has_msr_star = true;
1974 break;
1975 case MSR_VM_HSAVE_PA:
1976 has_msr_hsave_pa = true;
1977 break;
1978 case MSR_TSC_AUX:
1979 has_msr_tsc_aux = true;
1980 break;
1981 case MSR_TSC_ADJUST:
1982 has_msr_tsc_adjust = true;
1983 break;
1984 case MSR_IA32_TSCDEADLINE:
1985 has_msr_tsc_deadline = true;
1986 break;
1987 case MSR_IA32_SMBASE:
1988 has_msr_smbase = true;
1989 break;
1990 case MSR_SMI_COUNT:
1991 has_msr_smi_count = true;
1992 break;
1993 case MSR_IA32_MISC_ENABLE:
1994 has_msr_misc_enable = true;
1995 break;
1996 case MSR_IA32_BNDCFGS:
1997 has_msr_bndcfgs = true;
1998 break;
1999 case MSR_IA32_XSS:
2000 has_msr_xss = true;
2001 break;
2002 case MSR_IA32_UMWAIT_CONTROL:
2003 has_msr_umwait = true;
2004 break;
2005 case HV_X64_MSR_CRASH_CTL:
2006 has_msr_hv_crash = true;
2007 break;
2008 case HV_X64_MSR_RESET:
2009 has_msr_hv_reset = true;
2010 break;
2011 case HV_X64_MSR_VP_INDEX:
2012 has_msr_hv_vpindex = true;
2013 break;
2014 case HV_X64_MSR_VP_RUNTIME:
2015 has_msr_hv_runtime = true;
2016 break;
2017 case HV_X64_MSR_SCONTROL:
2018 has_msr_hv_synic = true;
2019 break;
2020 case HV_X64_MSR_STIMER0_CONFIG:
2021 has_msr_hv_stimer = true;
2022 break;
2023 case HV_X64_MSR_TSC_FREQUENCY:
2024 has_msr_hv_frequencies = true;
2025 break;
2026 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2027 has_msr_hv_reenlightenment = true;
2028 break;
2029 case MSR_IA32_SPEC_CTRL:
2030 has_msr_spec_ctrl = true;
2031 break;
2032 case MSR_IA32_TSX_CTRL:
2033 has_msr_tsx_ctrl = true;
2034 break;
2035 case MSR_VIRT_SSBD:
2036 has_msr_virt_ssbd = true;
2037 break;
2038 case MSR_IA32_ARCH_CAPABILITIES:
2039 has_msr_arch_capabs = true;
2040 break;
2041 case MSR_IA32_CORE_CAPABILITY:
2042 has_msr_core_capabs = true;
2043 break;
2044 case MSR_IA32_PERF_CAPABILITIES:
2045 has_msr_perf_capabs = true;
2046 break;
2047 case MSR_IA32_VMX_VMFUNC:
2048 has_msr_vmx_vmfunc = true;
2049 break;
2050 case MSR_IA32_UCODE_REV:
2051 has_msr_ucode_rev = true;
2052 break;
2053 case MSR_IA32_VMX_PROCBASED_CTLS2:
2054 has_msr_vmx_procbased_ctls2 = true;
2055 break;
2056 }
2057 }
2058 }
2059
2060 g_free(kvm_msr_list);
2061
2062 return ret;
2063 }
2064
2065 static Notifier smram_machine_done;
2066 static KVMMemoryListener smram_listener;
2067 static AddressSpace smram_address_space;
2068 static MemoryRegion smram_as_root;
2069 static MemoryRegion smram_as_mem;
2070
2071 static void register_smram_listener(Notifier *n, void *unused)
2072 {
2073 MemoryRegion *smram =
2074 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2075
2076 /* Outer container... */
2077 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2078 memory_region_set_enabled(&smram_as_root, true);
2079
2080 /* ... with two regions inside: normal system memory with low
2081 * priority, and...
2082 */
2083 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2084 get_system_memory(), 0, ~0ull);
2085 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2086 memory_region_set_enabled(&smram_as_mem, true);
2087
2088 if (smram) {
2089 /* ... SMRAM with higher priority */
2090 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2091 memory_region_set_enabled(smram, true);
2092 }
2093
2094 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2095 kvm_memory_listener_register(kvm_state, &smram_listener,
2096 &smram_address_space, 1);
2097 }
2098
2099 int kvm_arch_init(MachineState *ms, KVMState *s)
2100 {
2101 uint64_t identity_base = 0xfffbc000;
2102 uint64_t shadow_mem;
2103 int ret;
2104 struct utsname utsname;
2105
2106 has_xsave = kvm_check_extension(s, KVM_CAP_XSAVE);
2107 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
2108 has_pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);
2109
2110 hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
2111
2112 has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
2113 if (has_exception_payload) {
2114 ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
2115 if (ret < 0) {
2116 error_report("kvm: Failed to enable exception payload cap: %s",
2117 strerror(-ret));
2118 return ret;
2119 }
2120 }
2121
2122 ret = kvm_get_supported_msrs(s);
2123 if (ret < 0) {
2124 return ret;
2125 }
2126
2127 kvm_get_supported_feature_msrs(s);
2128
2129 uname(&utsname);
2130 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
2131
2132 /*
2133 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
2134 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
2135 * Since these must be part of guest physical memory, we need to allocate
2136 * them, both by setting their start addresses in the kernel and by
2137 * creating a corresponding e820 entry. We need 4 pages before the BIOS.
2138 *
2139 * Older KVM versions may not support setting the identity map base. In
2140 * that case we need to stick with the default, i.e. a 256K maximum BIOS
2141 * size.
2142 */
2143 if (kvm_check_extension(s, KVM_CAP_SET_IDENTITY_MAP_ADDR)) {
2144 /* Allows up to 16M BIOSes. */
2145 identity_base = 0xfeffc000;
2146
2147 ret = kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
2148 if (ret < 0) {
2149 return ret;
2150 }
2151 }
2152
2153 /* Set TSS base one page after EPT identity map. */
2154 ret = kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, identity_base + 0x1000);
2155 if (ret < 0) {
2156 return ret;
2157 }
2158
2159 /* Tell fw_cfg to notify the BIOS to reserve the range. */
2160 ret = e820_add_entry(identity_base, 0x4000, E820_RESERVED);
2161 if (ret < 0) {
2162 fprintf(stderr, "e820_add_entry() table is full\n");
2163 return ret;
2164 }
2165
2166 shadow_mem = object_property_get_int(OBJECT(s), "kvm-shadow-mem", &error_abort);
2167 if (shadow_mem != -1) {
2168 shadow_mem /= 4096;
2169 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
2170 if (ret < 0) {
2171 return ret;
2172 }
2173 }
2174
2175 if (kvm_check_extension(s, KVM_CAP_X86_SMM) &&
2176 object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
2177 x86_machine_is_smm_enabled(X86_MACHINE(ms))) {
2178 smram_machine_done.notify = register_smram_listener;
2179 qemu_add_machine_init_done_notifier(&smram_machine_done);
2180 }
2181
2182 if (enable_cpu_pm) {
2183 int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
2184 int ret;
2185
2186 /* Work around for kernel header with a typo. TODO: fix header and drop. */
2187 #if defined(KVM_X86_DISABLE_EXITS_HTL) && !defined(KVM_X86_DISABLE_EXITS_HLT)
2188 #define KVM_X86_DISABLE_EXITS_HLT KVM_X86_DISABLE_EXITS_HTL
2189 #endif
2190 if (disable_exits) {
2191 disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
2192 KVM_X86_DISABLE_EXITS_HLT |
2193 KVM_X86_DISABLE_EXITS_PAUSE |
2194 KVM_X86_DISABLE_EXITS_CSTATE);
2195 }
2196
2197 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
2198 disable_exits);
2199 if (ret < 0) {
2200 error_report("kvm: guest stopping CPU not supported: %s",
2201 strerror(-ret));
2202 }
2203 }
2204
2205 return 0;
2206 }
2207
2208 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2209 {
2210 lhs->selector = rhs->selector;
2211 lhs->base = rhs->base;
2212 lhs->limit = rhs->limit;
2213 lhs->type = 3;
2214 lhs->present = 1;
2215 lhs->dpl = 3;
2216 lhs->db = 0;
2217 lhs->s = 1;
2218 lhs->l = 0;
2219 lhs->g = 0;
2220 lhs->avl = 0;
2221 lhs->unusable = 0;
2222 }
2223
2224 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
2225 {
2226 unsigned flags = rhs->flags;
2227 lhs->selector = rhs->selector;
2228 lhs->base = rhs->base;
2229 lhs->limit = rhs->limit;
2230 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
2231 lhs->present = (flags & DESC_P_MASK) != 0;
2232 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
2233 lhs->db = (flags >> DESC_B_SHIFT) & 1;
2234 lhs->s = (flags & DESC_S_MASK) != 0;
2235 lhs->l = (flags >> DESC_L_SHIFT) & 1;
2236 lhs->g = (flags & DESC_G_MASK) != 0;
2237 lhs->avl = (flags & DESC_AVL_MASK) != 0;
2238 lhs->unusable = !lhs->present;
2239 lhs->padding = 0;
2240 }
2241
2242 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
2243 {
2244 lhs->selector = rhs->selector;
2245 lhs->base = rhs->base;
2246 lhs->limit = rhs->limit;
2247 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
2248 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
2249 (rhs->dpl << DESC_DPL_SHIFT) |
2250 (rhs->db << DESC_B_SHIFT) |
2251 (rhs->s * DESC_S_MASK) |
2252 (rhs->l << DESC_L_SHIFT) |
2253 (rhs->g * DESC_G_MASK) |
2254 (rhs->avl * DESC_AVL_MASK);
2255 }
2256
2257 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
2258 {
2259 if (set) {
2260 *kvm_reg = *qemu_reg;
2261 } else {
2262 *qemu_reg = *kvm_reg;
2263 }
2264 }
2265
2266 static int kvm_getput_regs(X86CPU *cpu, int set)
2267 {
2268 CPUX86State *env = &cpu->env;
2269 struct kvm_regs regs;
2270 int ret = 0;
2271
2272 if (!set) {
2273 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
2274 if (ret < 0) {
2275 return ret;
2276 }
2277 }
2278
2279 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
2280 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
2281 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
2282 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
2283 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
2284 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
2285 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
2286 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
2287 #ifdef TARGET_X86_64
2288 kvm_getput_reg(&regs.r8, &env->regs[8], set);
2289 kvm_getput_reg(&regs.r9, &env->regs[9], set);
2290 kvm_getput_reg(&regs.r10, &env->regs[10], set);
2291 kvm_getput_reg(&regs.r11, &env->regs[11], set);
2292 kvm_getput_reg(&regs.r12, &env->regs[12], set);
2293 kvm_getput_reg(&regs.r13, &env->regs[13], set);
2294 kvm_getput_reg(&regs.r14, &env->regs[14], set);
2295 kvm_getput_reg(&regs.r15, &env->regs[15], set);
2296 #endif
2297
2298 kvm_getput_reg(&regs.rflags, &env->eflags, set);
2299 kvm_getput_reg(&regs.rip, &env->eip, set);
2300
2301 if (set) {
2302 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
2303 }
2304
2305 return ret;
2306 }
2307
2308 static int kvm_put_fpu(X86CPU *cpu)
2309 {
2310 CPUX86State *env = &cpu->env;
2311 struct kvm_fpu fpu;
2312 int i;
2313
2314 memset(&fpu, 0, sizeof fpu);
2315 fpu.fsw = env->fpus & ~(7 << 11);
2316 fpu.fsw |= (env->fpstt & 7) << 11;
2317 fpu.fcw = env->fpuc;
2318 fpu.last_opcode = env->fpop;
2319 fpu.last_ip = env->fpip;
2320 fpu.last_dp = env->fpdp;
2321 for (i = 0; i < 8; ++i) {
2322 fpu.ftwx |= (!env->fptags[i]) << i;
2323 }
2324 memcpy(fpu.fpr, env->fpregs, sizeof env->fpregs);
2325 for (i = 0; i < CPU_NB_REGS; i++) {
2326 stq_p(&fpu.xmm[i][0], env->xmm_regs[i].ZMM_Q(0));
2327 stq_p(&fpu.xmm[i][8], env->xmm_regs[i].ZMM_Q(1));
2328 }
2329 fpu.mxcsr = env->mxcsr;
2330
2331 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_FPU, &fpu);
2332 }
2333
2334 #define XSAVE_FCW_FSW 0
2335 #define XSAVE_FTW_FOP 1
2336 #define XSAVE_CWD_RIP 2
2337 #define XSAVE_CWD_RDP 4
2338 #define XSAVE_MXCSR 6
2339 #define XSAVE_ST_SPACE 8
2340 #define XSAVE_XMM_SPACE 40
2341 #define XSAVE_XSTATE_BV 128
2342 #define XSAVE_YMMH_SPACE 144
2343 #define XSAVE_BNDREGS 240
2344 #define XSAVE_BNDCSR 256
2345 #define XSAVE_OPMASK 272
2346 #define XSAVE_ZMM_Hi256 288
2347 #define XSAVE_Hi16_ZMM 416
2348 #define XSAVE_PKRU 672
2349
2350 #define XSAVE_BYTE_OFFSET(word_offset) \
2351 ((word_offset) * sizeof_field(struct kvm_xsave, region[0]))
2352
2353 #define ASSERT_OFFSET(word_offset, field) \
2354 QEMU_BUILD_BUG_ON(XSAVE_BYTE_OFFSET(word_offset) != \
2355 offsetof(X86XSaveArea, field))
2356
2357 ASSERT_OFFSET(XSAVE_FCW_FSW, legacy.fcw);
2358 ASSERT_OFFSET(XSAVE_FTW_FOP, legacy.ftw);
2359 ASSERT_OFFSET(XSAVE_CWD_RIP, legacy.fpip);
2360 ASSERT_OFFSET(XSAVE_CWD_RDP, legacy.fpdp);
2361 ASSERT_OFFSET(XSAVE_MXCSR, legacy.mxcsr);
2362 ASSERT_OFFSET(XSAVE_ST_SPACE, legacy.fpregs);
2363 ASSERT_OFFSET(XSAVE_XMM_SPACE, legacy.xmm_regs);
2364 ASSERT_OFFSET(XSAVE_XSTATE_BV, header.xstate_bv);
2365 ASSERT_OFFSET(XSAVE_YMMH_SPACE, avx_state);
2366 ASSERT_OFFSET(XSAVE_BNDREGS, bndreg_state);
2367 ASSERT_OFFSET(XSAVE_BNDCSR, bndcsr_state);
2368 ASSERT_OFFSET(XSAVE_OPMASK, opmask_state);
2369 ASSERT_OFFSET(XSAVE_ZMM_Hi256, zmm_hi256_state);
2370 ASSERT_OFFSET(XSAVE_Hi16_ZMM, hi16_zmm_state);
2371 ASSERT_OFFSET(XSAVE_PKRU, pkru_state);
2372
2373 static int kvm_put_xsave(X86CPU *cpu)
2374 {
2375 CPUX86State *env = &cpu->env;
2376 X86XSaveArea *xsave = env->xsave_buf;
2377
2378 if (!has_xsave) {
2379 return kvm_put_fpu(cpu);
2380 }
2381 x86_cpu_xsave_all_areas(cpu, xsave);
2382
2383 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
2384 }
2385
2386 static int kvm_put_xcrs(X86CPU *cpu)
2387 {
2388 CPUX86State *env = &cpu->env;
2389 struct kvm_xcrs xcrs = {};
2390
2391 if (!has_xcrs) {
2392 return 0;
2393 }
2394
2395 xcrs.nr_xcrs = 1;
2396 xcrs.flags = 0;
2397 xcrs.xcrs[0].xcr = 0;
2398 xcrs.xcrs[0].value = env->xcr0;
2399 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
2400 }
2401
2402 static int kvm_put_sregs(X86CPU *cpu)
2403 {
2404 CPUX86State *env = &cpu->env;
2405 struct kvm_sregs sregs;
2406
2407 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
2408 if (env->interrupt_injected >= 0) {
2409 sregs.interrupt_bitmap[env->interrupt_injected / 64] |=
2410 (uint64_t)1 << (env->interrupt_injected % 64);
2411 }
2412
2413 if ((env->eflags & VM_MASK)) {
2414 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
2415 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
2416 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
2417 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
2418 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
2419 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
2420 } else {
2421 set_seg(&sregs.cs, &env->segs[R_CS]);
2422 set_seg(&sregs.ds, &env->segs[R_DS]);
2423 set_seg(&sregs.es, &env->segs[R_ES]);
2424 set_seg(&sregs.fs, &env->segs[R_FS]);
2425 set_seg(&sregs.gs, &env->segs[R_GS]);
2426 set_seg(&sregs.ss, &env->segs[R_SS]);
2427 }
2428
2429 set_seg(&sregs.tr, &env->tr);
2430 set_seg(&sregs.ldt, &env->ldt);
2431
2432 sregs.idt.limit = env->idt.limit;
2433 sregs.idt.base = env->idt.base;
2434 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
2435 sregs.gdt.limit = env->gdt.limit;
2436 sregs.gdt.base = env->gdt.base;
2437 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
2438
2439 sregs.cr0 = env->cr[0];
2440 sregs.cr2 = env->cr[2];
2441 sregs.cr3 = env->cr[3];
2442 sregs.cr4 = env->cr[4];
2443
2444 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
2445 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
2446
2447 sregs.efer = env->efer;
2448
2449 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
2450 }
2451
2452 static void kvm_msr_buf_reset(X86CPU *cpu)
2453 {
2454 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
2455 }
2456
2457 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
2458 {
2459 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
2460 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
2461 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
2462
2463 assert((void *)(entry + 1) <= limit);
2464
2465 entry->index = index;
2466 entry->reserved = 0;
2467 entry->data = value;
2468 msrs->nmsrs++;
2469 }
2470
2471 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
2472 {
2473 kvm_msr_buf_reset(cpu);
2474 kvm_msr_entry_add(cpu, index, value);
2475
2476 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2477 }
2478
2479 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
2480 {
2481 int ret;
2482
2483 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
2484 assert(ret == 1);
2485 }
2486
2487 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
2488 {
2489 CPUX86State *env = &cpu->env;
2490 int ret;
2491
2492 if (!has_msr_tsc_deadline) {
2493 return 0;
2494 }
2495
2496 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
2497 if (ret < 0) {
2498 return ret;
2499 }
2500
2501 assert(ret == 1);
2502 return 0;
2503 }
2504
2505 /*
2506 * Provide a separate write service for the feature control MSR in order to
2507 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
2508 * before writing any other state because forcibly leaving nested mode
2509 * invalidates the VCPU state.
2510 */
2511 static int kvm_put_msr_feature_control(X86CPU *cpu)
2512 {
2513 int ret;
2514
2515 if (!has_msr_feature_control) {
2516 return 0;
2517 }
2518
2519 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
2520 cpu->env.msr_ia32_feature_control);
2521 if (ret < 0) {
2522 return ret;
2523 }
2524
2525 assert(ret == 1);
2526 return 0;
2527 }
2528
2529 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
2530 {
2531 uint32_t default1, can_be_one, can_be_zero;
2532 uint32_t must_be_one;
2533
2534 switch (index) {
2535 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
2536 default1 = 0x00000016;
2537 break;
2538 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
2539 default1 = 0x0401e172;
2540 break;
2541 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
2542 default1 = 0x000011ff;
2543 break;
2544 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
2545 default1 = 0x00036dff;
2546 break;
2547 case MSR_IA32_VMX_PROCBASED_CTLS2:
2548 default1 = 0;
2549 break;
2550 default:
2551 abort();
2552 }
2553
2554 /* If a feature bit is set, the control can be either set or clear.
2555 * Otherwise the value is limited to either 0 or 1 by default1.
2556 */
2557 can_be_one = features | default1;
2558 can_be_zero = features | ~default1;
2559 must_be_one = ~can_be_zero;
2560
2561 /*
2562 * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
2563 * Bit 32:63 -> 1 if the control bit can be one.
2564 */
2565 return must_be_one | (((uint64_t)can_be_one) << 32);
2566 }
2567
2568 #define VMCS12_MAX_FIELD_INDEX (0x17)
2569
2570 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
2571 {
2572 uint64_t kvm_vmx_basic =
2573 kvm_arch_get_supported_msr_feature(kvm_state,
2574 MSR_IA32_VMX_BASIC);
2575
2576 if (!kvm_vmx_basic) {
2577 /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
2578 * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
2579 */
2580 return;
2581 }
2582
2583 uint64_t kvm_vmx_misc =
2584 kvm_arch_get_supported_msr_feature(kvm_state,
2585 MSR_IA32_VMX_MISC);
2586 uint64_t kvm_vmx_ept_vpid =
2587 kvm_arch_get_supported_msr_feature(kvm_state,
2588 MSR_IA32_VMX_EPT_VPID_CAP);
2589
2590 /*
2591 * If the guest is 64-bit, a value of 1 is allowed for the host address
2592 * space size vmexit control.
2593 */
2594 uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
2595 ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
2596
2597 /*
2598 * Bits 0-30, 32-44 and 50-53 come from the host. KVM should
2599 * not change them for backwards compatibility.
2600 */
2601 uint64_t fixed_vmx_basic = kvm_vmx_basic &
2602 (MSR_VMX_BASIC_VMCS_REVISION_MASK |
2603 MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
2604 MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
2605
2606 /*
2607 * Same for bits 0-4 and 25-27. Bits 16-24 (CR3 target count) can
2608 * change in the future but are always zero for now, clear them to be
2609 * future proof. Bits 32-63 in theory could change, though KVM does
2610 * not support dual-monitor treatment and probably never will; mask
2611 * them out as well.
2612 */
2613 uint64_t fixed_vmx_misc = kvm_vmx_misc &
2614 (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
2615 MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
2616
2617 /*
2618 * EPT memory types should not change either, so we do not bother
2619 * adding features for them.
2620 */
2621 uint64_t fixed_vmx_ept_mask =
2622 (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
2623 MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
2624 uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
2625
2626 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2627 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
2628 f[FEAT_VMX_PROCBASED_CTLS]));
2629 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2630 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
2631 f[FEAT_VMX_PINBASED_CTLS]));
2632 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
2633 make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
2634 f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
2635 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2636 make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
2637 f[FEAT_VMX_ENTRY_CTLS]));
2638 kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
2639 make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
2640 f[FEAT_VMX_SECONDARY_CTLS]));
2641 kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
2642 f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
2643 kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
2644 f[FEAT_VMX_BASIC] | fixed_vmx_basic);
2645 kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
2646 f[FEAT_VMX_MISC] | fixed_vmx_misc);
2647 if (has_msr_vmx_vmfunc) {
2648 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
2649 }
2650
2651 /*
2652 * Just to be safe, write these with constant values. The CRn_FIXED1
2653 * MSRs are generated by KVM based on the vCPU's CPUID.
2654 */
2655 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
2656 CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
2657 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
2658 CR4_VMXE_MASK);
2659 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM,
2660 VMCS12_MAX_FIELD_INDEX << 1);
2661 }
2662
2663 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
2664 {
2665 uint64_t kvm_perf_cap =
2666 kvm_arch_get_supported_msr_feature(kvm_state,
2667 MSR_IA32_PERF_CAPABILITIES);
2668
2669 if (kvm_perf_cap) {
2670 kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
2671 kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
2672 }
2673 }
2674
2675 static int kvm_buf_set_msrs(X86CPU *cpu)
2676 {
2677 int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
2678 if (ret < 0) {
2679 return ret;
2680 }
2681
2682 if (ret < cpu->kvm_msr_buf->nmsrs) {
2683 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
2684 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
2685 (uint32_t)e->index, (uint64_t)e->data);
2686 }
2687
2688 assert(ret == cpu->kvm_msr_buf->nmsrs);
2689 return 0;
2690 }
2691
2692 static void kvm_init_msrs(X86CPU *cpu)
2693 {
2694 CPUX86State *env = &cpu->env;
2695
2696 kvm_msr_buf_reset(cpu);
2697 if (has_msr_arch_capabs) {
2698 kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
2699 env->features[FEAT_ARCH_CAPABILITIES]);
2700 }
2701
2702 if (has_msr_core_capabs) {
2703 kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
2704 env->features[FEAT_CORE_CAPABILITY]);
2705 }
2706
2707 if (has_msr_perf_capabs && cpu->enable_pmu) {
2708 kvm_msr_entry_add_perf(cpu, env->features);
2709 }
2710
2711 if (has_msr_ucode_rev) {
2712 kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
2713 }
2714
2715 /*
2716 * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
2717 * all kernels with MSR features should have them.
2718 */
2719 if (kvm_feature_msrs && cpu_has_vmx(env)) {
2720 kvm_msr_entry_add_vmx(cpu, env->features);
2721 }
2722
2723 assert(kvm_buf_set_msrs(cpu) == 0);
2724 }
2725
2726 static int kvm_put_msrs(X86CPU *cpu, int level)
2727 {
2728 CPUX86State *env = &cpu->env;
2729 int i;
2730
2731 kvm_msr_buf_reset(cpu);
2732
2733 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
2734 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
2735 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
2736 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
2737 if (has_msr_star) {
2738 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
2739 }
2740 if (has_msr_hsave_pa) {
2741 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
2742 }
2743 if (has_msr_tsc_aux) {
2744 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
2745 }
2746 if (has_msr_tsc_adjust) {
2747 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
2748 }
2749 if (has_msr_misc_enable) {
2750 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
2751 env->msr_ia32_misc_enable);
2752 }
2753 if (has_msr_smbase) {
2754 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
2755 }
2756 if (has_msr_smi_count) {
2757 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
2758 }
2759 if (has_msr_bndcfgs) {
2760 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
2761 }
2762 if (has_msr_xss) {
2763 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
2764 }
2765 if (has_msr_umwait) {
2766 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
2767 }
2768 if (has_msr_spec_ctrl) {
2769 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
2770 }
2771 if (has_msr_tsx_ctrl) {
2772 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
2773 }
2774 if (has_msr_virt_ssbd) {
2775 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
2776 }
2777
2778 #ifdef TARGET_X86_64
2779 if (lm_capable_kernel) {
2780 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
2781 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
2782 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
2783 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
2784 }
2785 #endif
2786
2787 /*
2788 * The following MSRs have side effects on the guest or are too heavy
2789 * for normal writeback. Limit them to reset or full state updates.
2790 */
2791 if (level >= KVM_PUT_RESET_STATE) {
2792 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
2793 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
2794 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
2795 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
2796 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
2797 }
2798 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
2799 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
2800 }
2801 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
2802 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
2803 }
2804 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
2805 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
2806 }
2807
2808 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
2809 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
2810 }
2811
2812 if (has_architectural_pmu_version > 0) {
2813 if (has_architectural_pmu_version > 1) {
2814 /* Stop the counter. */
2815 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
2816 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
2817 }
2818
2819 /* Set the counter values. */
2820 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
2821 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
2822 env->msr_fixed_counters[i]);
2823 }
2824 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
2825 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
2826 env->msr_gp_counters[i]);
2827 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
2828 env->msr_gp_evtsel[i]);
2829 }
2830 if (has_architectural_pmu_version > 1) {
2831 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
2832 env->msr_global_status);
2833 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
2834 env->msr_global_ovf_ctrl);
2835
2836 /* Now start the PMU. */
2837 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
2838 env->msr_fixed_ctr_ctrl);
2839 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
2840 env->msr_global_ctrl);
2841 }
2842 }
2843 /*
2844 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
2845 * only sync them to KVM on the first cpu
2846 */
2847 if (current_cpu == first_cpu) {
2848 if (has_msr_hv_hypercall) {
2849 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
2850 env->msr_hv_guest_os_id);
2851 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
2852 env->msr_hv_hypercall);
2853 }
2854 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
2855 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
2856 env->msr_hv_tsc);
2857 }
2858 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
2859 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
2860 env->msr_hv_reenlightenment_control);
2861 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
2862 env->msr_hv_tsc_emulation_control);
2863 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
2864 env->msr_hv_tsc_emulation_status);
2865 }
2866 }
2867 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
2868 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
2869 env->msr_hv_vapic);
2870 }
2871 if (has_msr_hv_crash) {
2872 int j;
2873
2874 for (j = 0; j < HV_CRASH_PARAMS; j++)
2875 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
2876 env->msr_hv_crash_params[j]);
2877
2878 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
2879 }
2880 if (has_msr_hv_runtime) {
2881 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
2882 }
2883 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
2884 && hv_vpindex_settable) {
2885 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
2886 hyperv_vp_index(CPU(cpu)));
2887 }
2888 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2889 int j;
2890
2891 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
2892
2893 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
2894 env->msr_hv_synic_control);
2895 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
2896 env->msr_hv_synic_evt_page);
2897 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
2898 env->msr_hv_synic_msg_page);
2899
2900 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
2901 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
2902 env->msr_hv_synic_sint[j]);
2903 }
2904 }
2905 if (has_msr_hv_stimer) {
2906 int j;
2907
2908 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
2909 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
2910 env->msr_hv_stimer_config[j]);
2911 }
2912
2913 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
2914 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
2915 env->msr_hv_stimer_count[j]);
2916 }
2917 }
2918 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
2919 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
2920
2921 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
2922 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
2923 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
2924 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
2925 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
2926 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
2927 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
2928 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
2929 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
2930 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
2931 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
2932 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
2933 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
2934 /* The CPU GPs if we write to a bit above the physical limit of
2935 * the host CPU (and KVM emulates that)
2936 */
2937 uint64_t mask = env->mtrr_var[i].mask;
2938 mask &= phys_mask;
2939
2940 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
2941 env->mtrr_var[i].base);
2942 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
2943 }
2944 }
2945 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
2946 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
2947 0x14, 1, R_EAX) & 0x7;
2948
2949 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
2950 env->msr_rtit_ctrl);
2951 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
2952 env->msr_rtit_status);
2953 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
2954 env->msr_rtit_output_base);
2955 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
2956 env->msr_rtit_output_mask);
2957 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
2958 env->msr_rtit_cr3_match);
2959 for (i = 0; i < addr_num; i++) {
2960 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
2961 env->msr_rtit_addrs[i]);
2962 }
2963 }
2964
2965 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
2966 * kvm_put_msr_feature_control. */
2967 }
2968
2969 if (env->mcg_cap) {
2970 int i;
2971
2972 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
2973 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
2974 if (has_msr_mcg_ext_ctl) {
2975 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
2976 }
2977 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
2978 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
2979 }
2980 }
2981
2982 return kvm_buf_set_msrs(cpu);
2983 }
2984
2985
2986 static int kvm_get_fpu(X86CPU *cpu)
2987 {
2988 CPUX86State *env = &cpu->env;
2989 struct kvm_fpu fpu;
2990 int i, ret;
2991
2992 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_FPU, &fpu);
2993 if (ret < 0) {
2994 return ret;
2995 }
2996
2997 env->fpstt = (fpu.fsw >> 11) & 7;
2998 env->fpus = fpu.fsw;
2999 env->fpuc = fpu.fcw;
3000 env->fpop = fpu.last_opcode;
3001 env->fpip = fpu.last_ip;
3002 env->fpdp = fpu.last_dp;
3003 for (i = 0; i < 8; ++i) {
3004 env->fptags[i] = !((fpu.ftwx >> i) & 1);
3005 }
3006 memcpy(env->fpregs, fpu.fpr, sizeof env->fpregs);
3007 for (i = 0; i < CPU_NB_REGS; i++) {
3008 env->xmm_regs[i].ZMM_Q(0) = ldq_p(&fpu.xmm[i][0]);
3009 env->xmm_regs[i].ZMM_Q(1) = ldq_p(&fpu.xmm[i][8]);
3010 }
3011 env->mxcsr = fpu.mxcsr;
3012
3013 return 0;
3014 }
3015
3016 static int kvm_get_xsave(X86CPU *cpu)
3017 {
3018 CPUX86State *env = &cpu->env;
3019 X86XSaveArea *xsave = env->xsave_buf;
3020 int ret;
3021
3022 if (!has_xsave) {
3023 return kvm_get_fpu(cpu);
3024 }
3025
3026 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XSAVE, xsave);
3027 if (ret < 0) {
3028 return ret;
3029 }
3030 x86_cpu_xrstor_all_areas(cpu, xsave);
3031
3032 return 0;
3033 }
3034
3035 static int kvm_get_xcrs(X86CPU *cpu)
3036 {
3037 CPUX86State *env = &cpu->env;
3038 int i, ret;
3039 struct kvm_xcrs xcrs;
3040
3041 if (!has_xcrs) {
3042 return 0;
3043 }
3044
3045 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
3046 if (ret < 0) {
3047 return ret;
3048 }
3049
3050 for (i = 0; i < xcrs.nr_xcrs; i++) {
3051 /* Only support xcr0 now */
3052 if (xcrs.xcrs[i].xcr == 0) {
3053 env->xcr0 = xcrs.xcrs[i].value;
3054 break;
3055 }
3056 }
3057 return 0;
3058 }
3059
3060 static int kvm_get_sregs(X86CPU *cpu)
3061 {
3062 CPUX86State *env = &cpu->env;
3063 struct kvm_sregs sregs;
3064 int bit, i, ret;
3065
3066 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
3067 if (ret < 0) {
3068 return ret;
3069 }
3070
3071 /* There can only be one pending IRQ set in the bitmap at a time, so try
3072 to find it and save its number instead (-1 for none). */
3073 env->interrupt_injected = -1;
3074 for (i = 0; i < ARRAY_SIZE(sregs.interrupt_bitmap); i++) {
3075 if (sregs.interrupt_bitmap[i]) {
3076 bit = ctz64(sregs.interrupt_bitmap[i]);
3077 env->interrupt_injected = i * 64 + bit;
3078 break;
3079 }
3080 }
3081
3082 get_seg(&env->segs[R_CS], &sregs.cs);
3083 get_seg(&env->segs[R_DS], &sregs.ds);
3084 get_seg(&env->segs[R_ES], &sregs.es);
3085 get_seg(&env->segs[R_FS], &sregs.fs);
3086 get_seg(&env->segs[R_GS], &sregs.gs);
3087 get_seg(&env->segs[R_SS], &sregs.ss);
3088
3089 get_seg(&env->tr, &sregs.tr);
3090 get_seg(&env->ldt, &sregs.ldt);
3091
3092 env->idt.limit = sregs.idt.limit;
3093 env->idt.base = sregs.idt.base;
3094 env->gdt.limit = sregs.gdt.limit;
3095 env->gdt.base = sregs.gdt.base;
3096
3097 env->cr[0] = sregs.cr0;
3098 env->cr[2] = sregs.cr2;
3099 env->cr[3] = sregs.cr3;
3100 env->cr[4] = sregs.cr4;
3101
3102 env->efer = sregs.efer;
3103
3104 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
3105 x86_update_hflags(env);
3106
3107 return 0;
3108 }
3109
3110 static int kvm_get_msrs(X86CPU *cpu)
3111 {
3112 CPUX86State *env = &cpu->env;
3113 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
3114 int ret, i;
3115 uint64_t mtrr_top_bits;
3116
3117 kvm_msr_buf_reset(cpu);
3118
3119 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
3120 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
3121 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
3122 kvm_msr_entry_add(cpu, MSR_PAT, 0);
3123 if (has_msr_star) {
3124 kvm_msr_entry_add(cpu, MSR_STAR, 0);
3125 }
3126 if (has_msr_hsave_pa) {
3127 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
3128 }
3129 if (has_msr_tsc_aux) {
3130 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
3131 }
3132 if (has_msr_tsc_adjust) {
3133 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
3134 }
3135 if (has_msr_tsc_deadline) {
3136 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
3137 }
3138 if (has_msr_misc_enable) {
3139 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
3140 }
3141 if (has_msr_smbase) {
3142 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
3143 }
3144 if (has_msr_smi_count) {
3145 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
3146 }
3147 if (has_msr_feature_control) {
3148 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
3149 }
3150 if (has_msr_bndcfgs) {
3151 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
3152 }
3153 if (has_msr_xss) {
3154 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
3155 }
3156 if (has_msr_umwait) {
3157 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
3158 }
3159 if (has_msr_spec_ctrl) {
3160 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
3161 }
3162 if (has_msr_tsx_ctrl) {
3163 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
3164 }
3165 if (has_msr_virt_ssbd) {
3166 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
3167 }
3168 if (!env->tsc_valid) {
3169 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
3170 env->tsc_valid = !runstate_is_running();
3171 }
3172
3173 #ifdef TARGET_X86_64
3174 if (lm_capable_kernel) {
3175 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
3176 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
3177 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
3178 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
3179 }
3180 #endif
3181 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
3182 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
3183 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF_INT)) {
3184 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
3185 }
3186 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {
3187 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
3188 }
3189 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {
3190 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
3191 }
3192 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {
3193 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
3194 }
3195 if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_POLL_CONTROL)) {
3196 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
3197 }
3198 if (has_architectural_pmu_version > 0) {
3199 if (has_architectural_pmu_version > 1) {
3200 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
3201 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
3202 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
3203 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
3204 }
3205 for (i = 0; i < num_architectural_pmu_fixed_counters; i++) {
3206 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
3207 }
3208 for (i = 0; i < num_architectural_pmu_gp_counters; i++) {
3209 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
3210 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
3211 }
3212 }
3213
3214 if (env->mcg_cap) {
3215 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
3216 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
3217 if (has_msr_mcg_ext_ctl) {
3218 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
3219 }
3220 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
3221 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
3222 }
3223 }
3224
3225 if (has_msr_hv_hypercall) {
3226 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
3227 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
3228 }
3229 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
3230 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
3231 }
3232 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
3233 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
3234 }
3235 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
3236 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
3237 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
3238 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
3239 }
3240 if (has_msr_hv_crash) {
3241 int j;
3242
3243 for (j = 0; j < HV_CRASH_PARAMS; j++) {
3244 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
3245 }
3246 }
3247 if (has_msr_hv_runtime) {
3248 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
3249 }
3250 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
3251 uint32_t msr;
3252
3253 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
3254 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
3255 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
3256 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
3257 kvm_msr_entry_add(cpu, msr, 0);
3258 }
3259 }
3260 if (has_msr_hv_stimer) {
3261 uint32_t msr;
3262
3263 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
3264 msr++) {
3265 kvm_msr_entry_add(cpu, msr, 0);
3266 }
3267 }
3268 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
3269 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
3270 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
3271 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
3272 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
3273 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
3274 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
3275 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
3276 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
3277 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
3278 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
3279 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
3280 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
3281 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
3282 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
3283 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
3284 }
3285 }
3286
3287 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
3288 int addr_num =
3289 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
3290
3291 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
3292 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
3293 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
3294 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
3295 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
3296 for (i = 0; i < addr_num; i++) {
3297 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
3298 }
3299 }
3300
3301 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);
3302 if (ret < 0) {
3303 return ret;
3304 }
3305
3306 if (ret < cpu->kvm_msr_buf->nmsrs) {