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