master
c 7,142 lines 223 KB
Raw
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/qapi-events-run-state.h"
17 #include "qapi/error.h"
18 #include "qapi/visitor.h"
19 #include <math.h>
20 #include <sys/ioctl.h>
21 #include <sys/utsname.h>
22 #include <sys/syscall.h>
23 #include <sys/resource.h>
24
25 #include <linux/kvm.h>
26 #include <linux/kvm_para.h>
27 #include "standard-headers/asm-x86/kvm_para.h"
28 #include "hw/xen/interface/arch-x86/cpuid.h"
29
30 #include "cpu.h"
31 #include "host-cpu.h"
32 #include "vmsr_energy.h"
33 #include "system/system.h"
34 #include "system/hw_accel.h"
35 #include "system/accel-irq.h"
36 #include "system/kvm_int.h"
37 #include "system/runstate.h"
38 #include "system/ramblock.h"
39 #include "kvm_i386.h"
40 #include "../confidential-guest.h"
41 #include "sev.h"
42 #include "tdx.h"
43 #include "xen-emu.h"
44 #include "hyperv.h"
45 #include "hyperv-proto.h"
46
47 #include "gdbstub/enums.h"
48 #include "qemu/host-utils.h"
49 #include "qemu/main-loop.h"
50 #include "qemu/ratelimit.h"
51 #include "qemu/config-file.h"
52 #include "qemu/error-report.h"
53 #include "qemu/memalign.h"
54 #include "hw/i386/x86.h"
55 #include "hw/i386/kvm/xen_evtchn.h"
56 #include "hw/i386/pc.h"
57 #include "hw/i386/apic.h"
58 #include "hw/i386/apic_internal.h"
59 #include "hw/i386/apic-msidef.h"
60 #include "hw/i386/intel_iommu.h"
61 #include "hw/i386/topology.h"
62 #include "hw/i386/x86-iommu.h"
63 #include "hw/i386/e820_memory_layout.h"
64
65 #include "hw/xen/xen.h"
66
67 #include "hw/pci/pci.h"
68 #include "hw/pci/msi.h"
69 #include "hw/pci/msix.h"
70 #include "migration/blocker.h"
71 #include "exec/memattrs.h"
72 #include "exec/target_page.h"
73 #include "trace.h"
74
75 #include CONFIG_DEVICES
76
77 //#define DEBUG_KVM
78
79 #ifdef DEBUG_KVM
80 #define DPRINTF(fmt, ...) \
81 do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
82 #else
83 #define DPRINTF(fmt, ...) \
84 do { } while (0)
85 #endif
86
87 /*
88 * On older Intel CPUs, KVM uses vm86 mode to emulate 16-bit code directly.
89 * In order to use vm86 mode, an EPT identity map and a TSS are needed.
90 * Since these must be part of guest physical memory, we need to allocate
91 * them, both by setting their start addresses in the kernel and by
92 * creating a corresponding e820 entry. We need 4 pages before the BIOS,
93 * so this value allows up to 16M BIOSes.
94 */
95 #define KVM_IDENTITY_BASE 0xfeffc000
96
97 /* From arch/x86/kvm/lapic.h */
98 #define KVM_APIC_BUS_CYCLE_NS 1
99 #define KVM_APIC_BUS_FREQUENCY (1000000000ULL / KVM_APIC_BUS_CYCLE_NS)
100
101 /* A 4096-byte buffer can hold the 8-byte kvm_msrs header, plus
102 * 255 kvm_msr_entry structs */
103 #define MSR_BUF_SIZE 4096
104
105 typedef bool QEMURDMSRHandler(X86CPU *cpu, uint32_t msr, uint64_t *val);
106 typedef bool QEMUWRMSRHandler(X86CPU *cpu, uint32_t msr, uint64_t val);
107 typedef struct {
108 uint32_t msr;
109 QEMURDMSRHandler *rdmsr;
110 QEMUWRMSRHandler *wrmsr;
111 } KVMMSRHandlers;
112
113 static void kvm_init_msrs(X86CPU *cpu);
114 static int kvm_filter_msr(KVMState *s, uint32_t msr, QEMURDMSRHandler *rdmsr,
115 QEMUWRMSRHandler *wrmsr);
116 static int unregister_smram_listener(NotifierWithReturn *notifier,
117 void *data, Error** errp);
118 NotifierWithReturn kvm_vmfd_change_notifier = {
119 .notify = unregister_smram_listener,
120 };
121
122 const KVMCapabilityInfo kvm_arch_required_capabilities[] = {
123 KVM_CAP_INFO(SET_TSS_ADDR),
124 KVM_CAP_INFO(EXT_CPUID),
125 KVM_CAP_INFO(MP_STATE),
126 KVM_CAP_INFO(SIGNAL_MSI),
127 KVM_CAP_INFO(IRQ_ROUTING),
128 KVM_CAP_INFO(DEBUGREGS),
129 KVM_CAP_INFO(XSAVE),
130 KVM_CAP_INFO(VCPU_EVENTS),
131 KVM_CAP_INFO(X86_ROBUST_SINGLESTEP),
132 KVM_CAP_INFO(MCE),
133 KVM_CAP_INFO(ADJUST_CLOCK),
134 KVM_CAP_INFO(SET_IDENTITY_MAP_ADDR),
135 KVM_CAP_LAST_INFO
136 };
137
138 static bool has_msr_star;
139 static bool has_msr_hsave_pa;
140 static bool has_msr_tsc_aux;
141 static bool has_msr_tsc_adjust;
142 static bool has_msr_tsc_deadline;
143 static bool has_msr_feature_control;
144 static bool has_msr_misc_enable;
145 static bool has_msr_smbase;
146 static bool has_msr_bndcfgs;
147 static int lm_capable_kernel;
148 static bool has_msr_hv_hypercall;
149 static bool has_msr_hv_crash;
150 static bool has_msr_hv_reset;
151 static bool has_msr_hv_vpindex;
152 static bool hv_vpindex_settable;
153 static bool has_msr_hv_runtime;
154 static bool has_msr_hv_synic;
155 static bool has_msr_hv_stimer;
156 static bool has_msr_hv_frequencies;
157 static bool has_msr_hv_reenlightenment;
158 static bool has_msr_hv_syndbg_options;
159 static bool has_msr_xss;
160 static bool has_msr_umwait;
161 static bool has_msr_spec_ctrl;
162 static bool has_tsc_scale_msr;
163 static bool has_msr_tsx_ctrl;
164 static bool has_msr_virt_ssbd;
165 static bool has_msr_smi_count;
166 static bool has_msr_arch_capabs;
167 static bool has_msr_core_capabs;
168 static bool has_msr_vmx_vmfunc;
169 static bool has_msr_ucode_rev;
170 static bool has_msr_vmx_procbased_ctls2;
171 static bool has_msr_perf_capabs;
172 static bool has_msr_pkrs;
173 static bool has_msr_hwcr;
174
175 /*
176 * For Intel processors, the meaning is the architectural PMU version
177 * number.
178 *
179 * For AMD processors: 1 corresponds to the prior versions, and 2
180 * corresponds to AMD PerfMonV2.
181 */
182 static uint32_t pmu_version;
183 static uint32_t num_pmu_gp_counters;
184 static uint32_t num_pmu_fixed_counters;
185
186 static int has_xsave2;
187 static int has_xcrs;
188 static int has_sregs2;
189 static int has_exception_payload;
190 static int has_triple_fault_event;
191
192 static bool has_msr_mcg_ext_ctl;
193
194 static int pmu_cap;
195
196 static struct kvm_cpuid2 *cpuid_cache;
197 static struct kvm_cpuid2 *hv_cpuid_cache;
198 static struct kvm_msr_list *kvm_feature_msrs;
199
200 static KVMMSRHandlers msr_handlers[KVM_MSR_FILTER_MAX_RANGES];
201
202 #define BUS_LOCK_SLICE_TIME 1000000000ULL /* ns */
203 static RateLimit bus_lock_ratelimit_ctrl;
204 static int kvm_get_one_msr(X86CPU *cpu, int index, uint64_t *value);
205
206 static const char *vm_type_name[] = {
207 [KVM_X86_DEFAULT_VM] = "default",
208 [KVM_X86_SEV_VM] = "SEV",
209 [KVM_X86_SEV_ES_VM] = "SEV-ES",
210 [KVM_X86_SNP_VM] = "SEV-SNP",
211 [KVM_X86_TDX_VM] = "TDX",
212 };
213
214 bool kvm_is_vm_type_supported(int type)
215 {
216 uint32_t machine_types;
217
218 /*
219 * old KVM doesn't support KVM_CAP_VM_TYPES but KVM_X86_DEFAULT_VM
220 * is always supported
221 */
222 if (type == KVM_X86_DEFAULT_VM) {
223 return true;
224 }
225
226 machine_types = kvm_check_extension(KVM_STATE(current_machine->accelerator),
227 KVM_CAP_VM_TYPES);
228 return !!(machine_types & BIT(type));
229 }
230
231 int kvm_get_vm_type(MachineState *ms)
232 {
233 int kvm_type = KVM_X86_DEFAULT_VM;
234
235 if (ms->cgs) {
236 if (!object_dynamic_cast(OBJECT(ms->cgs), TYPE_X86_CONFIDENTIAL_GUEST)) {
237 error_report("configuration type %s not supported for x86 guests",
238 object_get_typename(OBJECT(ms->cgs)));
239 exit(1);
240 }
241 kvm_type = x86_confidential_guest_kvm_type(
242 X86_CONFIDENTIAL_GUEST(ms->cgs));
243 }
244
245 if (!kvm_is_vm_type_supported(kvm_type)) {
246 error_report("vm-type %s not supported by KVM", vm_type_name[kvm_type]);
247 exit(1);
248 }
249
250 return kvm_type;
251 }
252
253 bool kvm_enable_hypercall(uint64_t enable_mask)
254 {
255 KVMState *s = KVM_STATE(current_accel());
256
257 return !kvm_vm_enable_cap(s, KVM_CAP_EXIT_HYPERCALL, 0, enable_mask);
258 }
259
260 bool kvm_has_smm(void)
261 {
262 return kvm_vm_check_extension(kvm_state, KVM_CAP_X86_SMM);
263 }
264
265 bool kvm_has_adjust_clock_stable(void)
266 {
267 int ret = kvm_check_extension(kvm_state, KVM_CAP_ADJUST_CLOCK);
268
269 return (ret & KVM_CLOCK_TSC_STABLE);
270 }
271
272 bool kvm_has_exception_payload(void)
273 {
274 return has_exception_payload;
275 }
276
277 static bool kvm_x2apic_api_set_flags(uint64_t flags)
278 {
279 KVMState *s = KVM_STATE(current_accel());
280
281 return !kvm_vm_enable_cap(s, KVM_CAP_X2APIC_API, 0, flags);
282 }
283
284 #define MEMORIZE(fn, _result) \
285 ({ \
286 static bool _memorized; \
287 \
288 if (_memorized) { \
289 return _result; \
290 } \
291 _memorized = true; \
292 _result = fn; \
293 })
294
295 static bool has_x2apic_api;
296
297 bool kvm_has_x2apic_api(void)
298 {
299 return has_x2apic_api;
300 }
301
302 bool kvm_enable_x2apic(void)
303 {
304 return MEMORIZE(
305 kvm_x2apic_api_set_flags(KVM_X2APIC_API_USE_32BIT_IDS |
306 KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK),
307 has_x2apic_api);
308 }
309
310 bool kvm_hv_vpindex_settable(void)
311 {
312 return hv_vpindex_settable;
313 }
314
315 static int kvm_get_tsc(CPUState *cs)
316 {
317 X86CPU *cpu = X86_CPU(cs);
318 CPUX86State *env = &cpu->env;
319 uint64_t value;
320 int ret;
321
322 if (env->tsc_valid) {
323 return 0;
324 }
325
326 env->tsc_valid = !runstate_is_running();
327
328 ret = kvm_get_one_msr(cpu, MSR_IA32_TSC, &value);
329 if (ret < 0) {
330 return ret;
331 }
332
333 env->tsc = value;
334 return 0;
335 }
336
337 static inline void do_kvm_synchronize_tsc(CPUState *cpu, run_on_cpu_data arg)
338 {
339 kvm_get_tsc(cpu);
340 }
341
342 void kvm_synchronize_all_tsc(void)
343 {
344 CPUState *cpu;
345
346 if (kvm_enabled() && !is_tdx_vm()) {
347 CPU_FOREACH(cpu) {
348 run_on_cpu(cpu, do_kvm_synchronize_tsc, RUN_ON_CPU_NULL);
349 }
350 }
351 }
352
353 static struct kvm_cpuid2 *try_get_cpuid(KVMState *s, int max)
354 {
355 struct kvm_cpuid2 *cpuid;
356 int r, size;
357
358 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
359 cpuid = g_malloc0(size);
360 cpuid->nent = max;
361 r = kvm_ioctl(s, KVM_GET_SUPPORTED_CPUID, cpuid);
362 if (r == 0 && cpuid->nent >= max) {
363 r = -E2BIG;
364 }
365 if (r < 0) {
366 if (r == -E2BIG) {
367 g_free(cpuid);
368 return NULL;
369 } else {
370 fprintf(stderr, "KVM_GET_SUPPORTED_CPUID failed: %s\n",
371 strerror(-r));
372 exit(1);
373 }
374 }
375 return cpuid;
376 }
377
378 /* Run KVM_GET_SUPPORTED_CPUID ioctl(), allocating a buffer large enough
379 * for all entries.
380 */
381 static struct kvm_cpuid2 *get_supported_cpuid(KVMState *s)
382 {
383 struct kvm_cpuid2 *cpuid;
384 int max = 1;
385
386 if (cpuid_cache != NULL) {
387 return cpuid_cache;
388 }
389 while ((cpuid = try_get_cpuid(s, max)) == NULL) {
390 max *= 2;
391 }
392 cpuid_cache = cpuid;
393 return cpuid;
394 }
395
396 static bool host_tsx_broken(void)
397 {
398 int family, model, stepping;\
399 char vendor[CPUID_VENDOR_SZ + 1];
400
401 host_cpu_vendor_fms(vendor, &family, &model, &stepping);
402
403 /* Check if we are running on a Haswell host known to have broken TSX */
404 return !strcmp(vendor, CPUID_VENDOR_INTEL) &&
405 (family == 6) &&
406 ((model == 63 && stepping < 4) ||
407 model == 60 || model == 69 || model == 70);
408 }
409
410 /* Returns the value for a specific register on the cpuid entry
411 */
412 uint32_t cpuid_entry_get_reg(struct kvm_cpuid_entry2 *entry, int reg)
413 {
414 uint32_t ret = 0;
415 switch (reg) {
416 case R_EAX:
417 ret = entry->eax;
418 break;
419 case R_EBX:
420 ret = entry->ebx;
421 break;
422 case R_ECX:
423 ret = entry->ecx;
424 break;
425 case R_EDX:
426 ret = entry->edx;
427 break;
428 }
429 return ret;
430 }
431
432 /* Find matching entry for function/index on kvm_cpuid2 struct
433 */
434 struct kvm_cpuid_entry2 *cpuid_find_entry(struct kvm_cpuid2 *cpuid,
435 uint32_t function,
436 uint32_t index)
437 {
438 int i;
439 for (i = 0; i < cpuid->nent; ++i) {
440 if (cpuid->entries[i].function == function &&
441 cpuid->entries[i].index == index) {
442 return &cpuid->entries[i];
443 }
444 }
445 /* not found: */
446 return NULL;
447 }
448
449 uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
450 uint32_t index, int reg)
451 {
452 struct kvm_cpuid2 *cpuid;
453 uint32_t ret = 0;
454 uint32_t cpuid_1_edx, unused;
455 uint64_t bitmask;
456
457 cpuid = get_supported_cpuid(s);
458
459 struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
460 if (entry) {
461 ret = cpuid_entry_get_reg(entry, reg);
462 }
463
464 /* Fixups for the data returned by KVM, below */
465
466 if (function == 1 && reg == R_EDX) {
467 /* KVM before 2.6.30 misreports the following features */
468 ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
469 /* KVM never reports CPUID_HT but QEMU can support when vcpus > 1 */
470 ret |= CPUID_HT;
471 } else if (function == 1 && reg == R_ECX) {
472 /* We can set the hypervisor flag, even if KVM does not return it on
473 * GET_SUPPORTED_CPUID
474 */
475 ret |= CPUID_EXT_HYPERVISOR;
476 /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
477 * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
478 * and the irqchip is in the kernel.
479 */
480 if (kvm_irqchip_in_kernel() &&
481 kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
482 ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
483 }
484
485 /* x2apic is reported by GET_SUPPORTED_CPUID, but it can't be enabled
486 * without the in-kernel irqchip
487 */
488 if (!kvm_irqchip_in_kernel()) {
489 ret &= ~CPUID_EXT_X2APIC;
490 }
491
492 if (enable_cpu_pm) {
493 int disable_exits = kvm_check_extension(s,
494 KVM_CAP_X86_DISABLE_EXITS);
495
496 if (disable_exits & KVM_X86_DISABLE_EXITS_MWAIT) {
497 ret |= CPUID_EXT_MONITOR;
498 }
499 }
500 } else if (function == 6 && reg == R_EAX) {
501 ret |= CPUID_6_EAX_ARAT; /* safe to allow because of emulated APIC */
502 } else if (function == 7 && index == 0 && reg == R_EBX) {
503 /* Not new instructions, just an optimization. */
504 uint32_t ebx;
505 host_cpuid(7, 0, &unused, &ebx, &unused, &unused);
506 ret |= ebx & CPUID_7_0_EBX_ERMS;
507
508 if (host_tsx_broken()) {
509 ret &= ~(CPUID_7_0_EBX_RTM | CPUID_7_0_EBX_HLE);
510 }
511 } else if (function == 7 && index == 0 && reg == R_EDX) {
512 /* Not new instructions, just an optimization. */
513 uint32_t edx;
514 host_cpuid(7, 0, &unused, &unused, &unused, &edx);
515 ret |= edx & CPUID_7_0_EDX_FSRM;
516
517 /*
518 * Linux v4.17-v4.20 incorrectly return ARCH_CAPABILITIES on SVM hosts.
519 * We can detect the bug by checking if MSR_IA32_ARCH_CAPABILITIES is
520 * returned by KVM_GET_MSR_INDEX_LIST.
521 */
522 if (!has_msr_arch_capabs) {
523 ret &= ~CPUID_7_0_EDX_ARCH_CAPABILITIES;
524 }
525 } else if (function == 7 && index == 1 && reg == R_EAX) {
526 /* Not new instructions, just an optimization. */
527 uint32_t eax;
528 host_cpuid(7, 1, &eax, &unused, &unused, &unused);
529 ret |= eax & (CPUID_7_1_EAX_FZRM | CPUID_7_1_EAX_FSRS | CPUID_7_1_EAX_FSRC);
530 } else if (function == 7 && index == 2 && reg == R_EDX) {
531 uint32_t edx;
532 host_cpuid(7, 2, &unused, &unused, &unused, &edx);
533 ret |= edx & CPUID_7_2_EDX_MCDT_NO;
534 } else if (function == 0xd && index == 0 &&
535 (reg == R_EAX || reg == R_EDX)) {
536 /*
537 * The value returned by KVM_GET_SUPPORTED_CPUID does not include
538 * features that still have to be enabled with the arch_prctl
539 * system call. QEMU needs the full value, which is retrieved
540 * with KVM_GET_DEVICE_ATTR.
541 */
542 struct kvm_device_attr attr = {
543 .group = 0,
544 .attr = KVM_X86_XCOMP_GUEST_SUPP,
545 .addr = (unsigned long) &bitmask
546 };
547
548 bool sys_attr = kvm_check_extension(s, KVM_CAP_SYS_ATTRIBUTES);
549 if (!sys_attr) {
550 return ret;
551 }
552
553 int rc = kvm_ioctl(s, KVM_GET_DEVICE_ATTR, &attr);
554 if (rc < 0) {
555 if (rc != -ENXIO) {
556 warn_report("KVM_GET_DEVICE_ATTR(0, KVM_X86_XCOMP_GUEST_SUPP) "
557 "error: %d", rc);
558 }
559 return ret;
560 }
561 ret = (reg == R_EAX) ? bitmask : bitmask >> 32;
562 } else if (function == 0x80000001 && reg == R_ECX) {
563 /*
564 * It's safe to enable TOPOEXT even if it's not returned by
565 * GET_SUPPORTED_CPUID. Unconditionally enabling TOPOEXT here allows
566 * us to keep CPU models including TOPOEXT runnable on older kernels.
567 */
568 ret |= CPUID_EXT3_TOPOEXT;
569 } else if (function == 0x80000001 && reg == R_EDX) {
570 /* On Intel, kvm returns cpuid according to the Intel spec,
571 * so add missing bits according to the AMD spec:
572 */
573 cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
574 ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
575 } else if (function == 0x80000007 && reg == R_EBX) {
576 ret |= CPUID_8000_0007_EBX_OVERFLOW_RECOV | CPUID_8000_0007_EBX_SUCCOR;
577 } else if (function == KVM_CPUID_FEATURES && reg == R_EAX) {
578 /* kvm_pv_unhalt is reported by GET_SUPPORTED_CPUID, but it can't
579 * be enabled without the in-kernel irqchip
580 */
581 if (!kvm_irqchip_in_kernel()) {
582 ret &= ~CPUID_KVM_PV_UNHALT;
583 }
584 if (kvm_irqchip_is_split()) {
585 ret |= CPUID_KVM_MSI_EXT_DEST_ID;
586 }
587 } else if (function == KVM_CPUID_FEATURES && reg == R_EDX) {
588 ret |= CPUID_KVM_HINTS_REALTIME;
589 }
590
591 if (current_machine->cgs) {
592 ret = x86_confidential_guest_adjust_cpuid_features(
593 X86_CONFIDENTIAL_GUEST(current_machine->cgs),
594 function, index, reg, ret);
595 }
596 return ret;
597 }
598
599 uint64_t kvm_arch_get_supported_msr_feature(KVMState *s, uint32_t index)
600 {
601 struct {
602 struct kvm_msrs info;
603 struct kvm_msr_entry entries[1];
604 } msr_data = {};
605 uint64_t value;
606 uint32_t ret, can_be_one, must_be_one;
607
608 if (kvm_feature_msrs == NULL) { /* Host doesn't support feature MSRs */
609 return 0;
610 }
611
612 /* Check if requested MSR is supported feature MSR */
613 int i;
614 for (i = 0; i < kvm_feature_msrs->nmsrs; i++)
615 if (kvm_feature_msrs->indices[i] == index) {
616 break;
617 }
618 if (i == kvm_feature_msrs->nmsrs) {
619 return 0; /* if the feature MSR is not supported, simply return 0 */
620 }
621
622 msr_data.info.nmsrs = 1;
623 msr_data.entries[0].index = index;
624
625 ret = kvm_ioctl(s, KVM_GET_MSRS, &msr_data);
626 if (ret != 1) {
627 error_report("KVM get MSR (index=0x%x) feature failed, %s",
628 index, strerror(-ret));
629 exit(1);
630 }
631
632 value = msr_data.entries[0].data;
633 switch (index) {
634 case MSR_IA32_VMX_PROCBASED_CTLS2:
635 if (!has_msr_vmx_procbased_ctls2) {
636 /* KVM forgot to add these bits for some time, do this ourselves. */
637 if (kvm_arch_get_supported_cpuid(s, 0xD, 1, R_ECX) &
638 CPUID_XSAVE_XSAVES) {
639 value |= (uint64_t)VMX_SECONDARY_EXEC_XSAVES << 32;
640 }
641 if (kvm_arch_get_supported_cpuid(s, 1, 0, R_ECX) &
642 CPUID_EXT_RDRAND) {
643 value |= (uint64_t)VMX_SECONDARY_EXEC_RDRAND_EXITING << 32;
644 }
645 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
646 CPUID_7_0_EBX_INVPCID) {
647 value |= (uint64_t)VMX_SECONDARY_EXEC_ENABLE_INVPCID << 32;
648 }
649 if (kvm_arch_get_supported_cpuid(s, 7, 0, R_EBX) &
650 CPUID_7_0_EBX_RDSEED) {
651 value |= (uint64_t)VMX_SECONDARY_EXEC_RDSEED_EXITING << 32;
652 }
653 if (kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX) &
654 CPUID_EXT2_RDTSCP) {
655 value |= (uint64_t)VMX_SECONDARY_EXEC_RDTSCP << 32;
656 }
657 }
658 /* fall through */
659 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
660 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
661 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
662 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
663 /*
664 * Return true for bits that can be one, but do not have to be one.
665 * The SDM tells us which bits could have a "must be one" setting,
666 * so we can do the opposite transformation in make_vmx_msr_value.
667 */
668 must_be_one = (uint32_t)value;
669 can_be_one = (uint32_t)(value >> 32);
670 return can_be_one & ~must_be_one;
671 case MSR_IA32_ARCH_CAPABILITIES:
672 /*
673 * Special handling for fb-clear bit in ARCH_CAPABILITIES MSR.
674 * KVM will only report the bit if it is enabled in the host,
675 * but, for live migration capability purposes, we want to
676 * expose the bit to the guest even if it is disabled in the
677 * host, as long as the host itself is not vulnerable to
678 * the issue that the fb-clear bit is meant to mitigate.
679 */
680 if ((value & MSR_ARCH_CAP_MDS_NO) &&
681 (value & MSR_ARCH_CAP_TAA_NO) &&
682 (value & MSR_ARCH_CAP_SBDR_SSDP_NO) &&
683 (value & MSR_ARCH_CAP_FBSDP_NO) &&
684 (value & MSR_ARCH_CAP_PSDP_NO)) {
685 value |= MSR_ARCH_CAP_FB_CLEAR;
686 }
687 return value;
688
689 default:
690 return value;
691 }
692 }
693
694 static int kvm_get_mce_cap_supported(KVMState *s, uint64_t *mce_cap,
695 int *max_banks)
696 {
697 *max_banks = kvm_check_extension(s, KVM_CAP_MCE);
698 return kvm_ioctl(s, KVM_X86_GET_MCE_CAP_SUPPORTED, mce_cap);
699 }
700
701 static void kvm_mce_inject(X86CPU *cpu, hwaddr paddr, int code)
702 {
703 CPUState *cs = CPU(cpu);
704 CPUX86State *env = &cpu->env;
705 uint64_t status = MCI_STATUS_VAL | MCI_STATUS_EN | MCI_STATUS_MISCV |
706 MCI_STATUS_ADDRV;
707 uint64_t mcg_status = MCG_STATUS_MCIP | MCG_STATUS_RIPV;
708 int flags = 0;
709
710 if (!IS_AMD_CPU(env)) {
711 status |= MCI_STATUS_S | MCI_STATUS_UC;
712 if (code == BUS_MCEERR_AR) {
713 status |= MCI_STATUS_AR | 0x134;
714 mcg_status |= MCG_STATUS_EIPV;
715 } else {
716 status |= 0xc0;
717 }
718 } else {
719 if (code == BUS_MCEERR_AR) {
720 status |= MCI_STATUS_UC | MCI_STATUS_POISON;
721 mcg_status |= MCG_STATUS_EIPV;
722 } else {
723 /* Setting the POISON bit for deferred errors indicates to the
724 * guest kernel that the address provided by the MCE is valid
725 * and usable which will ensure that the guest kernel will send
726 * a SIGBUS_AO signal to the guest process. This allows for
727 * more desirable behavior in the case that the guest process
728 * with poisoned memory has set the MCE_KILL_EARLY prctl flag
729 * which indicates that the process would prefer to handle or
730 * shutdown due to the poisoned memory condition before the
731 * memory has been accessed.
732 *
733 * While the POISON bit would not be set in a deferred error
734 * sent from hardware, the bit is not meaningful for deferred
735 * errors and can be reused in this scenario.
736 */
737 status |= MCI_STATUS_DEFERRED | MCI_STATUS_POISON;
738 }
739 }
740
741 flags = cpu_x86_support_mca_broadcast(env) ? MCE_INJECT_BROADCAST : 0;
742 /* We need to read back the value of MSR_EXT_MCG_CTL that was set by the
743 * guest kernel back into env->mcg_ext_ctl.
744 */
745 cpu_synchronize_state(cs);
746 if (env->mcg_ext_ctl & MCG_EXT_CTL_LMCE_EN) {
747 mcg_status |= MCG_STATUS_LMCE;
748 flags = 0;
749 }
750
751 cpu_x86_inject_mce(cpu, 9, status, mcg_status, paddr,
752 (MCM_ADDR_PHYS << 6) | 0xc, flags, NULL);
753 }
754
755 static void emit_hypervisor_memory_failure(MemoryFailureAction action, bool ar)
756 {
757 MemoryFailureFlags mff = {.action_required = ar, .recursive = false};
758
759 qapi_event_send_memory_failure(MEMORY_FAILURE_RECIPIENT_HYPERVISOR, action,
760 &mff);
761 }
762
763 static void hardware_memory_error(void *host_addr)
764 {
765 emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_FATAL, true);
766 error_report("QEMU got Hardware memory error at addr %p", host_addr);
767 exit(1);
768 }
769
770 void kvm_arch_on_sigbus_vcpu(CPUState *c, int code, void *addr)
771 {
772 X86CPU *cpu = X86_CPU(c);
773 CPUX86State *env = &cpu->env;
774 ram_addr_t ram_addr;
775 hwaddr paddr;
776
777 /* If we get an action required MCE, it has been injected by KVM
778 * while the VM was running. An action optional MCE instead should
779 * be coming from the main thread, which qemu_init_sigbus identifies
780 * as the "early kill" thread.
781 */
782 assert(code == BUS_MCEERR_AR || code == BUS_MCEERR_AO);
783
784 if ((env->mcg_cap & MCG_SER_P) && addr) {
785 ram_addr = qemu_ram_addr_from_host(addr);
786 if (ram_addr != RAM_ADDR_INVALID &&
787 kvm_physical_memory_addr_from_host(c->kvm_state, addr, &paddr)) {
788 kvm_hwpoison_page_add(ram_addr);
789 kvm_mce_inject(cpu, paddr, code);
790
791 /*
792 * Use different logging severity based on error type.
793 * If there is additional MCE reporting on the hypervisor, QEMU VA
794 * could be another source to identify the PA and MCE details.
795 */
796 if (code == BUS_MCEERR_AR) {
797 error_report("Guest MCE Memory Error at QEMU addr %p and "
798 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
799 addr, paddr, "BUS_MCEERR_AR");
800 } else {
801 warn_report("Guest MCE Memory Error at QEMU addr %p and "
802 "GUEST addr 0x%" HWADDR_PRIx " of type %s injected",
803 addr, paddr, "BUS_MCEERR_AO");
804 }
805
806 return;
807 }
808
809 if (code == BUS_MCEERR_AO) {
810 warn_report("Hardware memory error at addr %p of type %s "
811 "for memory used by QEMU itself instead of guest system!",
812 addr, "BUS_MCEERR_AO");
813 }
814 }
815
816 if (code == BUS_MCEERR_AR) {
817 hardware_memory_error(addr);
818 }
819
820 /* Hope we are lucky for AO MCE, just notify a event */
821 emit_hypervisor_memory_failure(MEMORY_FAILURE_ACTION_IGNORE, false);
822 }
823
824 static void kvm_queue_exception(CPUX86State *env,
825 int32_t exception_nr,
826 uint8_t exception_has_payload,
827 uint64_t exception_payload)
828 {
829 assert(env->exception_nr == -1);
830 assert(!env->exception_pending);
831 assert(!env->exception_injected);
832 assert(!env->exception_has_payload);
833
834 env->exception_nr = exception_nr;
835
836 if (has_exception_payload) {
837 env->exception_pending = 1;
838
839 env->exception_has_payload = exception_has_payload;
840 env->exception_payload = exception_payload;
841 } else {
842 env->exception_injected = 1;
843
844 if (exception_nr == EXCP01_DB) {
845 assert(exception_has_payload);
846 env->dr[6] = exception_payload;
847 } else if (exception_nr == EXCP0E_PAGE) {
848 assert(exception_has_payload);
849 env->cr[2] = exception_payload;
850 } else {
851 assert(!exception_has_payload);
852 }
853 }
854 }
855
856 static void cpu_update_state(void *opaque, bool running, RunState state)
857 {
858 CPUX86State *env = opaque;
859
860 if (running) {
861 env->tsc_valid = false;
862 }
863 }
864
865 unsigned long kvm_arch_vcpu_id(CPUState *cs)
866 {
867 X86CPU *cpu = X86_CPU(cs);
868 return cpu->apic_id;
869 }
870
871 #ifndef KVM_CPUID_SIGNATURE_NEXT
872 #define KVM_CPUID_SIGNATURE_NEXT 0x40000100
873 #endif
874
875 static bool hyperv_enabled(X86CPU *cpu)
876 {
877 return kvm_check_extension(kvm_state, KVM_CAP_HYPERV) > 0 &&
878 ((cpu->hyperv_spinlock_attempts != HYPERV_SPINLOCK_NEVER_NOTIFY) ||
879 cpu->hyperv_features || cpu->hyperv_passthrough);
880 }
881
882 /*
883 * Check whether target_freq is within conservative
884 * ntp correctable bounds (250ppm) of freq
885 */
886 static inline bool freq_within_bounds(int freq, int target_freq)
887 {
888 int max_freq = freq + (freq * 250 / 1000000);
889 int min_freq = freq - (freq * 250 / 1000000);
890
891 if (target_freq >= min_freq && target_freq <= max_freq) {
892 return true;
893 }
894
895 return false;
896 }
897
898 static int kvm_arch_set_tsc_khz(CPUState *cs)
899 {
900 X86CPU *cpu = X86_CPU(cs);
901 CPUX86State *env = &cpu->env;
902 int r, cur_freq;
903 bool set_ioctl = false;
904
905 /*
906 * TSC of TD vcpu is immutable, it cannot be set/changed via vcpu scope
907 * VM_SET_TSC_KHZ, but only be initialized via VM scope VM_SET_TSC_KHZ
908 * before ioctl KVM_TDX_INIT_VM in tdx_pre_create_vcpu()
909 */
910 if (is_tdx_vm()) {
911 return 0;
912 }
913
914 if (!env->tsc_khz) {
915 return 0;
916 }
917
918 cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
919 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) : -ENOTSUP;
920
921 /*
922 * If TSC scaling is supported, attempt to set TSC frequency.
923 */
924 if (kvm_check_extension(cs->kvm_state, KVM_CAP_TSC_CONTROL)) {
925 set_ioctl = true;
926 }
927
928 /*
929 * If desired TSC frequency is within bounds of NTP correction,
930 * attempt to set TSC frequency.
931 */
932 if (cur_freq != -ENOTSUP && freq_within_bounds(cur_freq, env->tsc_khz)) {
933 set_ioctl = true;
934 }
935
936 r = set_ioctl ?
937 kvm_vcpu_ioctl(cs, KVM_SET_TSC_KHZ, env->tsc_khz) :
938 -ENOTSUP;
939
940 if (r < 0) {
941 /* When KVM_SET_TSC_KHZ fails, it's an error only if the current
942 * TSC frequency doesn't match the one we want.
943 */
944 cur_freq = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
945 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
946 -ENOTSUP;
947 if (cur_freq <= 0 || cur_freq != env->tsc_khz) {
948 warn_report("TSC frequency mismatch between "
949 "VM (%" PRId64 " kHz) and host (%d kHz), "
950 "and TSC scaling unavailable",
951 env->tsc_khz, cur_freq);
952 return r;
953 }
954 }
955
956 return 0;
957 }
958
959 static bool tsc_is_stable_and_known(CPUX86State *env)
960 {
961 if (!env->tsc_khz) {
962 return false;
963 }
964 return (env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC)
965 || env->user_tsc_khz;
966 }
967
968 #define DEFAULT_EVMCS_VERSION ((1 << 8) | 1)
969
970 static struct {
971 const char *desc;
972 struct {
973 uint32_t func;
974 int reg;
975 uint32_t bits;
976 } flags[2];
977 uint64_t dependencies;
978 bool skip_passthrough;
979 } kvm_hyperv_properties[] = {
980 [HYPERV_FEAT_RELAXED] = {
981 .desc = "relaxed timing (hv-relaxed)",
982 .flags = {
983 {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
984 .bits = HV_RELAXED_TIMING_RECOMMENDED}
985 }
986 },
987 [HYPERV_FEAT_VAPIC] = {
988 .desc = "virtual APIC (hv-vapic)",
989 .flags = {
990 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
991 .bits = HV_APIC_ACCESS_AVAILABLE}
992 }
993 },
994 [HYPERV_FEAT_TIME] = {
995 .desc = "clocksources (hv-time)",
996 .flags = {
997 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
998 .bits = HV_TIME_REF_COUNT_AVAILABLE | HV_REFERENCE_TSC_AVAILABLE}
999 }
1000 },
1001 [HYPERV_FEAT_CRASH] = {
1002 .desc = "crash MSRs (hv-crash)",
1003 .flags = {
1004 {.func = HV_CPUID_FEATURES, .reg = R_EDX,
1005 .bits = HV_GUEST_CRASH_MSR_AVAILABLE}
1006 }
1007 },
1008 [HYPERV_FEAT_RESET] = {
1009 .desc = "reset MSR (hv-reset)",
1010 .flags = {
1011 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1012 .bits = HV_RESET_AVAILABLE}
1013 }
1014 },
1015 [HYPERV_FEAT_VPINDEX] = {
1016 .desc = "VP_INDEX MSR (hv-vpindex)",
1017 .flags = {
1018 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1019 .bits = HV_VP_INDEX_AVAILABLE}
1020 }
1021 },
1022 [HYPERV_FEAT_RUNTIME] = {
1023 .desc = "VP_RUNTIME MSR (hv-runtime)",
1024 .flags = {
1025 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1026 .bits = HV_VP_RUNTIME_AVAILABLE}
1027 }
1028 },
1029 [HYPERV_FEAT_SYNIC] = {
1030 .desc = "synthetic interrupt controller (hv-synic)",
1031 .flags = {
1032 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1033 .bits = HV_SYNIC_AVAILABLE}
1034 }
1035 },
1036 [HYPERV_FEAT_STIMER] = {
1037 .desc = "synthetic timers (hv-stimer)",
1038 .flags = {
1039 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1040 .bits = HV_SYNTIMERS_AVAILABLE}
1041 },
1042 .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_TIME)
1043 },
1044 [HYPERV_FEAT_FREQUENCIES] = {
1045 .desc = "frequency MSRs (hv-frequencies)",
1046 .flags = {
1047 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1048 .bits = HV_ACCESS_FREQUENCY_MSRS},
1049 {.func = HV_CPUID_FEATURES, .reg = R_EDX,
1050 .bits = HV_FREQUENCY_MSRS_AVAILABLE}
1051 }
1052 },
1053 [HYPERV_FEAT_REENLIGHTENMENT] = {
1054 .desc = "reenlightenment MSRs (hv-reenlightenment)",
1055 .flags = {
1056 {.func = HV_CPUID_FEATURES, .reg = R_EAX,
1057 .bits = HV_ACCESS_REENLIGHTENMENTS_CONTROL}
1058 }
1059 },
1060 [HYPERV_FEAT_TLBFLUSH] = {
1061 .desc = "paravirtualized TLB flush (hv-tlbflush)",
1062 .flags = {
1063 {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
1064 .bits = HV_REMOTE_TLB_FLUSH_RECOMMENDED |
1065 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
1066 },
1067 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
1068 },
1069 [HYPERV_FEAT_EVMCS] = {
1070 .desc = "enlightened VMCS (hv-evmcs)",
1071 .flags = {
1072 {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
1073 .bits = HV_ENLIGHTENED_VMCS_RECOMMENDED}
1074 },
1075 .dependencies = BIT(HYPERV_FEAT_VAPIC)
1076 },
1077 [HYPERV_FEAT_IPI] = {
1078 .desc = "paravirtualized IPI (hv-ipi)",
1079 .flags = {
1080 {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
1081 .bits = HV_CLUSTER_IPI_RECOMMENDED |
1082 HV_EX_PROCESSOR_MASKS_RECOMMENDED}
1083 },
1084 .dependencies = BIT(HYPERV_FEAT_VPINDEX)
1085 },
1086 [HYPERV_FEAT_STIMER_DIRECT] = {
1087 .desc = "direct mode synthetic timers (hv-stimer-direct)",
1088 .flags = {
1089 {.func = HV_CPUID_FEATURES, .reg = R_EDX,
1090 .bits = HV_STIMER_DIRECT_MODE_AVAILABLE}
1091 },
1092 .dependencies = BIT(HYPERV_FEAT_STIMER)
1093 },
1094 [HYPERV_FEAT_AVIC] = {
1095 .desc = "AVIC/APICv support (hv-avic/hv-apicv)",
1096 .flags = {
1097 {.func = HV_CPUID_ENLIGHTMENT_INFO, .reg = R_EAX,
1098 .bits = HV_DEPRECATING_AEOI_RECOMMENDED}
1099 }
1100 },
1101 [HYPERV_FEAT_SYNDBG] = {
1102 .desc = "Enable synthetic kernel debugger channel (hv-syndbg)",
1103 .flags = {
1104 {.func = HV_CPUID_FEATURES, .reg = R_EDX,
1105 .bits = HV_FEATURE_DEBUG_MSRS_AVAILABLE}
1106 },
1107 .dependencies = BIT(HYPERV_FEAT_SYNIC) | BIT(HYPERV_FEAT_RELAXED),
1108 .skip_passthrough = true,
1109 },
1110 [HYPERV_FEAT_MSR_BITMAP] = {
1111 .desc = "enlightened MSR-Bitmap (hv-emsr-bitmap)",
1112 .flags = {
1113 {.func = HV_CPUID_NESTED_FEATURES, .reg = R_EAX,
1114 .bits = HV_NESTED_MSR_BITMAP}
1115 }
1116 },
1117 [HYPERV_FEAT_XMM_INPUT] = {
1118 .desc = "XMM fast hypercall input (hv-xmm-input)",
1119 .flags = {
1120 {.func = HV_CPUID_FEATURES, .reg = R_EDX,
1121 .bits = HV_HYPERCALL_XMM_INPUT_AVAILABLE}
1122 }
1123 },
1124 [HYPERV_FEAT_TLBFLUSH_EXT] = {
1125 .desc = "Extended gva ranges for TLB flush hypercalls (hv-tlbflush-ext)",
1126 .flags = {
1127 {.func = HV_CPUID_FEATURES, .reg = R_EDX,
1128 .bits = HV_EXT_GVA_RANGES_FLUSH_AVAILABLE}
1129 },
1130 .dependencies = BIT(HYPERV_FEAT_TLBFLUSH)
1131 },
1132 [HYPERV_FEAT_TLBFLUSH_DIRECT] = {
1133 .desc = "direct TLB flush (hv-tlbflush-direct)",
1134 .flags = {
1135 {.func = HV_CPUID_NESTED_FEATURES, .reg = R_EAX,
1136 .bits = HV_NESTED_DIRECT_FLUSH}
1137 },
1138 .dependencies = BIT(HYPERV_FEAT_VAPIC)
1139 },
1140 };
1141
1142 static struct kvm_cpuid2 *try_get_hv_cpuid(CPUState *cs, int max,
1143 bool do_sys_ioctl)
1144 {
1145 struct kvm_cpuid2 *cpuid;
1146 int r, size;
1147
1148 size = sizeof(*cpuid) + max * sizeof(*cpuid->entries);
1149 cpuid = g_malloc0(size);
1150 cpuid->nent = max;
1151
1152 if (do_sys_ioctl) {
1153 r = kvm_ioctl(kvm_state, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1154 } else {
1155 r = kvm_vcpu_ioctl(cs, KVM_GET_SUPPORTED_HV_CPUID, cpuid);
1156 }
1157 if (r == 0 && cpuid->nent >= max) {
1158 r = -E2BIG;
1159 }
1160 if (r < 0) {
1161 if (r == -E2BIG) {
1162 g_free(cpuid);
1163 return NULL;
1164 } else {
1165 fprintf(stderr, "KVM_GET_SUPPORTED_HV_CPUID failed: %s\n",
1166 strerror(-r));
1167 exit(1);
1168 }
1169 }
1170 return cpuid;
1171 }
1172
1173 /*
1174 * Run KVM_GET_SUPPORTED_HV_CPUID ioctl(), allocating a buffer large enough
1175 * for all entries.
1176 */
1177 static struct kvm_cpuid2 *get_supported_hv_cpuid(CPUState *cs)
1178 {
1179 struct kvm_cpuid2 *cpuid;
1180 /* 0x40000000..0x40000005, 0x4000000A, 0x40000080..0x40000082 leaves */
1181 int max = 11;
1182 int i;
1183 bool do_sys_ioctl;
1184
1185 do_sys_ioctl =
1186 kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID) > 0;
1187
1188 /*
1189 * Non-empty KVM context is needed when KVM_CAP_SYS_HYPERV_CPUID is
1190 * unsupported, kvm_hyperv_expand_features() checks for that.
1191 */
1192 assert(do_sys_ioctl || cs->kvm_state);
1193
1194 /*
1195 * When the buffer is too small, KVM_GET_SUPPORTED_HV_CPUID fails with
1196 * -E2BIG, however, it doesn't report back the right size. Keep increasing
1197 * it and re-trying until we succeed.
1198 */
1199 while ((cpuid = try_get_hv_cpuid(cs, max, do_sys_ioctl)) == NULL) {
1200 max++;
1201 }
1202
1203 /*
1204 * KVM_GET_SUPPORTED_HV_CPUID does not set EVMCS CPUID bit before
1205 * KVM_CAP_HYPERV_ENLIGHTENED_VMCS is enabled but we want to get the
1206 * information early, just check for the capability and set the bit
1207 * manually.
1208 */
1209 if (!do_sys_ioctl && kvm_check_extension(cs->kvm_state,
1210 KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1211 for (i = 0; i < cpuid->nent; i++) {
1212 if (cpuid->entries[i].function == HV_CPUID_ENLIGHTMENT_INFO) {
1213 cpuid->entries[i].eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1214 }
1215 }
1216 }
1217
1218 return cpuid;
1219 }
1220
1221 /*
1222 * When KVM_GET_SUPPORTED_HV_CPUID is not supported we fill CPUID feature
1223 * leaves from KVM_CAP_HYPERV* and present MSRs data.
1224 */
1225 static struct kvm_cpuid2 *get_supported_hv_cpuid_legacy(CPUState *cs)
1226 {
1227 X86CPU *cpu = X86_CPU(cs);
1228 struct kvm_cpuid2 *cpuid;
1229 struct kvm_cpuid_entry2 *entry_feat, *entry_recomm;
1230
1231 /* HV_CPUID_FEATURES, HV_CPUID_ENLIGHTMENT_INFO */
1232 cpuid = g_malloc0(sizeof(*cpuid) + 2 * sizeof(*cpuid->entries));
1233 cpuid->nent = 2;
1234
1235 /* HV_CPUID_VENDOR_AND_MAX_FUNCTIONS */
1236 entry_feat = &cpuid->entries[0];
1237 entry_feat->function = HV_CPUID_FEATURES;
1238
1239 entry_recomm = &cpuid->entries[1];
1240 entry_recomm->function = HV_CPUID_ENLIGHTMENT_INFO;
1241 entry_recomm->ebx = cpu->hyperv_spinlock_attempts;
1242
1243 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0) {
1244 entry_feat->eax |= HV_HYPERCALL_AVAILABLE;
1245 entry_feat->eax |= HV_APIC_ACCESS_AVAILABLE;
1246 entry_feat->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1247 entry_recomm->eax |= HV_RELAXED_TIMING_RECOMMENDED;
1248 entry_recomm->eax |= HV_APIC_ACCESS_RECOMMENDED;
1249 }
1250
1251 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_TIME) > 0) {
1252 entry_feat->eax |= HV_TIME_REF_COUNT_AVAILABLE;
1253 entry_feat->eax |= HV_REFERENCE_TSC_AVAILABLE;
1254 }
1255
1256 if (has_msr_hv_frequencies) {
1257 entry_feat->eax |= HV_ACCESS_FREQUENCY_MSRS;
1258 entry_feat->edx |= HV_FREQUENCY_MSRS_AVAILABLE;
1259 }
1260
1261 if (has_msr_hv_crash) {
1262 entry_feat->edx |= HV_GUEST_CRASH_MSR_AVAILABLE;
1263 }
1264
1265 if (has_msr_hv_reenlightenment) {
1266 entry_feat->eax |= HV_ACCESS_REENLIGHTENMENTS_CONTROL;
1267 }
1268
1269 if (has_msr_hv_reset) {
1270 entry_feat->eax |= HV_RESET_AVAILABLE;
1271 }
1272
1273 if (has_msr_hv_vpindex) {
1274 entry_feat->eax |= HV_VP_INDEX_AVAILABLE;
1275 }
1276
1277 if (has_msr_hv_runtime) {
1278 entry_feat->eax |= HV_VP_RUNTIME_AVAILABLE;
1279 }
1280
1281 if (has_msr_hv_synic) {
1282 if (kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV_SYNIC2) > 0) {
1283 entry_feat->eax |= HV_SYNIC_AVAILABLE;
1284 }
1285 }
1286
1287 if (has_msr_hv_stimer) {
1288 entry_feat->eax |= HV_SYNTIMERS_AVAILABLE;
1289 }
1290
1291 if (has_msr_hv_syndbg_options) {
1292 entry_feat->edx |= HV_GUEST_DEBUGGING_AVAILABLE;
1293 entry_feat->edx |= HV_FEATURE_DEBUG_MSRS_AVAILABLE;
1294 entry_feat->ebx |= HV_PARTITION_DEBUGGING_ALLOWED;
1295 }
1296
1297 if (kvm_check_extension(cs->kvm_state,
1298 KVM_CAP_HYPERV_TLBFLUSH) > 0) {
1299 entry_recomm->eax |= HV_REMOTE_TLB_FLUSH_RECOMMENDED;
1300 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1301 }
1302
1303 if (kvm_check_extension(cs->kvm_state,
1304 KVM_CAP_HYPERV_ENLIGHTENED_VMCS) > 0) {
1305 entry_recomm->eax |= HV_ENLIGHTENED_VMCS_RECOMMENDED;
1306 }
1307
1308 if (kvm_check_extension(cs->kvm_state,
1309 KVM_CAP_HYPERV_SEND_IPI) > 0) {
1310 entry_recomm->eax |= HV_CLUSTER_IPI_RECOMMENDED;
1311 entry_recomm->eax |= HV_EX_PROCESSOR_MASKS_RECOMMENDED;
1312 }
1313
1314 return cpuid;
1315 }
1316
1317 static uint32_t hv_cpuid_get_host(CPUState *cs, uint32_t func, int reg)
1318 {
1319 struct kvm_cpuid_entry2 *entry;
1320 struct kvm_cpuid2 *cpuid;
1321
1322 if (hv_cpuid_cache) {
1323 cpuid = hv_cpuid_cache;
1324 } else {
1325 if (kvm_check_extension(kvm_state, KVM_CAP_HYPERV_CPUID) > 0) {
1326 cpuid = get_supported_hv_cpuid(cs);
1327 } else {
1328 /*
1329 * 'cs->kvm_state' may be NULL when Hyper-V features are expanded
1330 * before KVM context is created but this is only done when
1331 * KVM_CAP_SYS_HYPERV_CPUID is supported and it implies
1332 * KVM_CAP_HYPERV_CPUID.
1333 */
1334 assert(cs->kvm_state);
1335
1336 cpuid = get_supported_hv_cpuid_legacy(cs);
1337 }
1338 hv_cpuid_cache = cpuid;
1339 }
1340
1341 if (!cpuid) {
1342 return 0;
1343 }
1344
1345 entry = cpuid_find_entry(cpuid, func, 0);
1346 if (!entry) {
1347 return 0;
1348 }
1349
1350 return cpuid_entry_get_reg(entry, reg);
1351 }
1352
1353 static bool hyperv_feature_supported(CPUState *cs, int feature)
1354 {
1355 uint32_t func, bits;
1356 int i, reg;
1357
1358 /*
1359 * kvm_hyperv_properties needs to define at least one CPUID flag which
1360 * must be used to detect the feature, it's hard to say whether it is
1361 * supported or not otherwise.
1362 */
1363 assert(kvm_hyperv_properties[feature].flags[0].func);
1364
1365 for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties[feature].flags); i++) {
1366
1367 func = kvm_hyperv_properties[feature].flags[i].func;
1368 reg = kvm_hyperv_properties[feature].flags[i].reg;
1369 bits = kvm_hyperv_properties[feature].flags[i].bits;
1370
1371 if (!func) {
1372 continue;
1373 }
1374
1375 if ((hv_cpuid_get_host(cs, func, reg) & bits) != bits) {
1376 return false;
1377 }
1378 }
1379
1380 return true;
1381 }
1382
1383 /* Checks that all feature dependencies are enabled */
1384 static bool hv_feature_check_deps(X86CPU *cpu, int feature, Error **errp)
1385 {
1386 uint64_t deps;
1387 int dep_feat;
1388
1389 deps = kvm_hyperv_properties[feature].dependencies;
1390 while (deps) {
1391 dep_feat = ctz64(deps);
1392 if (!(hyperv_feat_enabled(cpu, dep_feat))) {
1393 error_setg(errp, "Hyper-V %s requires Hyper-V %s",
1394 kvm_hyperv_properties[feature].desc,
1395 kvm_hyperv_properties[dep_feat].desc);
1396 return false;
1397 }
1398 deps &= ~(1ull << dep_feat);
1399 }
1400
1401 return true;
1402 }
1403
1404 static uint32_t hv_build_cpuid_leaf(CPUState *cs, uint32_t func, int reg)
1405 {
1406 X86CPU *cpu = X86_CPU(cs);
1407 uint32_t r = 0;
1408 int i, j;
1409
1410 for (i = 0; i < ARRAY_SIZE(kvm_hyperv_properties); i++) {
1411 if (!hyperv_feat_enabled(cpu, i)) {
1412 continue;
1413 }
1414
1415 for (j = 0; j < ARRAY_SIZE(kvm_hyperv_properties[i].flags); j++) {
1416 if (kvm_hyperv_properties[i].flags[j].func != func) {
1417 continue;
1418 }
1419 if (kvm_hyperv_properties[i].flags[j].reg != reg) {
1420 continue;
1421 }
1422
1423 r |= kvm_hyperv_properties[i].flags[j].bits;
1424 }
1425 }
1426
1427 /* HV_CPUID_NESTED_FEATURES.EAX also encodes the supported eVMCS range */
1428 if (func == HV_CPUID_NESTED_FEATURES && reg == R_EAX) {
1429 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1430 r |= DEFAULT_EVMCS_VERSION;
1431 }
1432 }
1433
1434 return r;
1435 }
1436
1437 /*
1438 * Expand Hyper-V CPU features. In partucular, check that all the requested
1439 * features are supported by the host and the sanity of the configuration
1440 * (that all the required dependencies are included). Also, this takes care
1441 * of 'hv_passthrough' mode and fills the environment with all supported
1442 * Hyper-V features.
1443 */
1444 bool kvm_hyperv_expand_features(X86CPU *cpu, Error **errp)
1445 {
1446 CPUState *cs = CPU(cpu);
1447 Error *local_err = NULL;
1448 int feat;
1449
1450 if (!hyperv_enabled(cpu))
1451 return true;
1452
1453 /*
1454 * When kvm_hyperv_expand_features is called at CPU feature expansion
1455 * time per-CPU kvm_state is not available yet so we can only proceed
1456 * when KVM_CAP_SYS_HYPERV_CPUID is supported.
1457 */
1458 if (!cs->kvm_state &&
1459 !kvm_check_extension(kvm_state, KVM_CAP_SYS_HYPERV_CPUID))
1460 return true;
1461
1462 if (cpu->hyperv_passthrough) {
1463 cpu->hyperv_vendor_id[0] =
1464 hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EBX);
1465 cpu->hyperv_vendor_id[1] =
1466 hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_ECX);
1467 cpu->hyperv_vendor_id[2] =
1468 hv_cpuid_get_host(cs, HV_CPUID_VENDOR_AND_MAX_FUNCTIONS, R_EDX);
1469 cpu->hyperv_vendor = g_realloc(cpu->hyperv_vendor,
1470 sizeof(cpu->hyperv_vendor_id) + 1);
1471 memcpy(cpu->hyperv_vendor, cpu->hyperv_vendor_id,
1472 sizeof(cpu->hyperv_vendor_id));
1473 cpu->hyperv_vendor[sizeof(cpu->hyperv_vendor_id)] = 0;
1474
1475 cpu->hyperv_interface_id[0] =
1476 hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EAX);
1477 cpu->hyperv_interface_id[1] =
1478 hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EBX);
1479 cpu->hyperv_interface_id[2] =
1480 hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_ECX);
1481 cpu->hyperv_interface_id[3] =
1482 hv_cpuid_get_host(cs, HV_CPUID_INTERFACE, R_EDX);
1483
1484 cpu->hyperv_ver_id_build =
1485 hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EAX);
1486 cpu->hyperv_ver_id_major =
1487 hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX) >> 16;
1488 cpu->hyperv_ver_id_minor =
1489 hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EBX) & 0xffff;
1490 cpu->hyperv_ver_id_sp =
1491 hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_ECX);
1492 cpu->hyperv_ver_id_sb =
1493 hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX) >> 24;
1494 cpu->hyperv_ver_id_sn =
1495 hv_cpuid_get_host(cs, HV_CPUID_VERSION, R_EDX) & 0xffffff;
1496
1497 cpu->hv_max_vps = hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS,
1498 R_EAX);
1499 cpu->hyperv_limits[0] =
1500 hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EBX);
1501 cpu->hyperv_limits[1] =
1502 hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_ECX);
1503 cpu->hyperv_limits[2] =
1504 hv_cpuid_get_host(cs, HV_CPUID_IMPLEMENT_LIMITS, R_EDX);
1505
1506 cpu->hyperv_spinlock_attempts =
1507 hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EBX);
1508
1509 /*
1510 * Mark feature as enabled in 'cpu->hyperv_features' as
1511 * hv_build_cpuid_leaf() uses this info to build guest CPUIDs.
1512 */
1513 for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
1514 if (hyperv_feature_supported(cs, feat) &&
1515 !kvm_hyperv_properties[feat].skip_passthrough) {
1516 cpu->hyperv_features |= BIT(feat);
1517 }
1518 }
1519 } else {
1520 /* Check features availability and dependencies */
1521 for (feat = 0; feat < ARRAY_SIZE(kvm_hyperv_properties); feat++) {
1522 /* If the feature was not requested skip it. */
1523 if (!hyperv_feat_enabled(cpu, feat)) {
1524 continue;
1525 }
1526
1527 /* Check if the feature is supported by KVM */
1528 if (!hyperv_feature_supported(cs, feat)) {
1529 error_setg(errp, "Hyper-V %s is not supported by kernel",
1530 kvm_hyperv_properties[feat].desc);
1531 return false;
1532 }
1533
1534 /* Check dependencies */
1535 if (!hv_feature_check_deps(cpu, feat, &local_err)) {
1536 error_propagate(errp, local_err);
1537 return false;
1538 }
1539 }
1540 }
1541
1542 /* Additional dependencies not covered by kvm_hyperv_properties[] */
1543 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC) &&
1544 !hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)) {
1545 error_setg(errp, "Hyper-V %s requires Hyper-V %s",
1546 kvm_hyperv_properties[HYPERV_FEAT_SYNIC].desc,
1547 kvm_hyperv_properties[HYPERV_FEAT_VPINDEX].desc);
1548 return false;
1549 }
1550
1551 return true;
1552 }
1553
1554 /*
1555 * Fill in Hyper-V CPUIDs. Returns the number of entries filled in cpuid_ent.
1556 */
1557 static int hyperv_fill_cpuids(CPUState *cs,
1558 struct kvm_cpuid_entry2 *cpuid_ent)
1559 {
1560 X86CPU *cpu = X86_CPU(cs);
1561 struct kvm_cpuid_entry2 *c;
1562 uint32_t signature[3];
1563 uint32_t cpuid_i = 0, max_cpuid_leaf = 0;
1564 uint32_t nested_eax =
1565 hv_build_cpuid_leaf(cs, HV_CPUID_NESTED_FEATURES, R_EAX);
1566
1567 max_cpuid_leaf = nested_eax ? HV_CPUID_NESTED_FEATURES :
1568 HV_CPUID_IMPLEMENT_LIMITS;
1569
1570 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG)) {
1571 max_cpuid_leaf =
1572 MAX(max_cpuid_leaf, HV_CPUID_SYNDBG_PLATFORM_CAPABILITIES);
1573 }
1574
1575 c = &cpuid_ent[cpuid_i++];
1576 c->function = HV_CPUID_VENDOR_AND_MAX_FUNCTIONS;
1577 c->eax = max_cpuid_leaf;
1578 c->ebx = cpu->hyperv_vendor_id[0];
1579 c->ecx = cpu->hyperv_vendor_id[1];
1580 c->edx = cpu->hyperv_vendor_id[2];
1581
1582 c = &cpuid_ent[cpuid_i++];
1583 c->function = HV_CPUID_INTERFACE;
1584 c->eax = cpu->hyperv_interface_id[0];
1585 c->ebx = cpu->hyperv_interface_id[1];
1586 c->ecx = cpu->hyperv_interface_id[2];
1587 c->edx = cpu->hyperv_interface_id[3];
1588
1589 c = &cpuid_ent[cpuid_i++];
1590 c->function = HV_CPUID_VERSION;
1591 c->eax = cpu->hyperv_ver_id_build;
1592 c->ebx = (uint32_t)cpu->hyperv_ver_id_major << 16 |
1593 cpu->hyperv_ver_id_minor;
1594 c->ecx = cpu->hyperv_ver_id_sp;
1595 c->edx = (uint32_t)cpu->hyperv_ver_id_sb << 24 |
1596 (cpu->hyperv_ver_id_sn & 0xffffff);
1597
1598 c = &cpuid_ent[cpuid_i++];
1599 c->function = HV_CPUID_FEATURES;
1600 c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EAX);
1601 c->ebx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EBX);
1602 c->edx = hv_build_cpuid_leaf(cs, HV_CPUID_FEATURES, R_EDX);
1603
1604 /* Unconditionally required with any Hyper-V enlightenment */
1605 c->eax |= HV_HYPERCALL_AVAILABLE;
1606
1607 /* SynIC and Vmbus devices require messages/signals hypercalls */
1608 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1609 c->ebx |= HV_POST_MESSAGES | HV_SIGNAL_EVENTS;
1610 }
1611
1612
1613 /* Not exposed by KVM but needed to make CPU hotplug in Windows work */
1614 c->edx |= HV_CPU_DYNAMIC_PARTITIONING_AVAILABLE;
1615
1616 c = &cpuid_ent[cpuid_i++];
1617 c->function = HV_CPUID_ENLIGHTMENT_INFO;
1618 c->eax = hv_build_cpuid_leaf(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX);
1619 c->ebx = cpu->hyperv_spinlock_attempts;
1620
1621 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC) &&
1622 !hyperv_feat_enabled(cpu, HYPERV_FEAT_AVIC)) {
1623 c->eax |= HV_APIC_ACCESS_RECOMMENDED;
1624 }
1625
1626 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_ON) {
1627 c->eax |= HV_NO_NONARCH_CORESHARING;
1628 } else if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO) {
1629 c->eax |= hv_cpuid_get_host(cs, HV_CPUID_ENLIGHTMENT_INFO, R_EAX) &
1630 HV_NO_NONARCH_CORESHARING;
1631 }
1632
1633 c = &cpuid_ent[cpuid_i++];
1634 c->function = HV_CPUID_IMPLEMENT_LIMITS;
1635 c->eax = cpu->hv_max_vps;
1636 c->ebx = cpu->hyperv_limits[0];
1637 c->ecx = cpu->hyperv_limits[1];
1638 c->edx = cpu->hyperv_limits[2];
1639
1640 if (nested_eax) {
1641 uint32_t function;
1642
1643 /* Create zeroed 0x40000006..0x40000009 leaves */
1644 for (function = HV_CPUID_IMPLEMENT_LIMITS + 1;
1645 function < HV_CPUID_NESTED_FEATURES; function++) {
1646 c = &cpuid_ent[cpuid_i++];
1647 c->function = function;
1648 }
1649
1650 c = &cpuid_ent[cpuid_i++];
1651 c->function = HV_CPUID_NESTED_FEATURES;
1652 c->eax = nested_eax;
1653 }
1654
1655 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG)) {
1656 c = &cpuid_ent[cpuid_i++];
1657 c->function = HV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS;
1658 c->eax = hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS) ?
1659 HV_CPUID_NESTED_FEATURES : HV_CPUID_IMPLEMENT_LIMITS;
1660 memcpy(signature, "Microsoft VS", 12);
1661 c->eax = 0;
1662 c->ebx = signature[0];
1663 c->ecx = signature[1];
1664 c->edx = signature[2];
1665
1666 c = &cpuid_ent[cpuid_i++];
1667 c->function = HV_CPUID_SYNDBG_INTERFACE;
1668 memcpy(signature, "VS#1\0\0\0\0\0\0\0\0", 12);
1669 c->eax = signature[0];
1670 c->ebx = 0;
1671 c->ecx = 0;
1672 c->edx = 0;
1673
1674 c = &cpuid_ent[cpuid_i++];
1675 c->function = HV_CPUID_SYNDBG_PLATFORM_CAPABILITIES;
1676 c->eax = HV_SYNDBG_CAP_ALLOW_KERNEL_DEBUGGING;
1677 c->ebx = 0;
1678 c->ecx = 0;
1679 c->edx = 0;
1680 }
1681
1682 return cpuid_i;
1683 }
1684
1685 static Error *hv_passthrough_mig_blocker;
1686 static Error *hv_no_nonarch_cs_mig_blocker;
1687
1688 /* Checks that the exposed eVMCS version range is supported by KVM */
1689 static bool evmcs_version_supported(uint16_t evmcs_version,
1690 uint16_t supported_evmcs_version)
1691 {
1692 uint8_t min_version = evmcs_version & 0xff;
1693 uint8_t max_version = evmcs_version >> 8;
1694 uint8_t min_supported_version = supported_evmcs_version & 0xff;
1695 uint8_t max_supported_version = supported_evmcs_version >> 8;
1696
1697 return (min_version >= min_supported_version) &&
1698 (max_version <= max_supported_version);
1699 }
1700
1701 static int hyperv_init_vcpu(X86CPU *cpu)
1702 {
1703 CPUState *cs = CPU(cpu);
1704 Error *local_err = NULL;
1705 int ret;
1706
1707 if (cpu->hyperv_passthrough && hv_passthrough_mig_blocker == NULL) {
1708 error_setg(&hv_passthrough_mig_blocker,
1709 "'hv-passthrough' CPU flag prevents migration, use explicit"
1710 " set of hv-* flags instead");
1711 ret = migrate_add_blocker(&hv_passthrough_mig_blocker, &local_err);
1712 if (ret < 0) {
1713 error_report_err(local_err);
1714 return ret;
1715 }
1716 }
1717
1718 if (cpu->hyperv_no_nonarch_cs == ON_OFF_AUTO_AUTO &&
1719 hv_no_nonarch_cs_mig_blocker == NULL) {
1720 error_setg(&hv_no_nonarch_cs_mig_blocker,
1721 "'hv-no-nonarch-coresharing=auto' CPU flag prevents migration"
1722 " use explicit 'hv-no-nonarch-coresharing=on' instead (but"
1723 " make sure SMT is disabled and/or that vCPUs are properly"
1724 " pinned)");
1725 ret = migrate_add_blocker(&hv_no_nonarch_cs_mig_blocker, &local_err);
1726 if (ret < 0) {
1727 error_report_err(local_err);
1728 return ret;
1729 }
1730 }
1731
1732 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX) && !hv_vpindex_settable) {
1733 /*
1734 * the kernel doesn't support setting vp_index; assert that its value
1735 * is in sync
1736 */
1737 uint64_t value;
1738
1739 ret = kvm_get_one_msr(cpu, HV_X64_MSR_VP_INDEX, &value);
1740 if (ret < 0) {
1741 return ret;
1742 }
1743
1744 if (value != hyperv_vp_index(CPU(cpu))) {
1745 error_report("kernel's vp_index != QEMU's vp_index");
1746 return -ENXIO;
1747 }
1748 }
1749
1750 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
1751 ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_SYNIC2, 0);
1752 if (ret < 0) {
1753 error_report("failed to turn on HyperV SynIC in KVM: %s",
1754 strerror(-ret));
1755 return ret;
1756 }
1757
1758 ret = hyperv_enable_synic(cpu);
1759 if (ret < 0) {
1760 error_report("failed to create HyperV SynIC: %s",
1761 strerror(-ret));
1762 return ret;
1763 }
1764 }
1765
1766 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_EVMCS)) {
1767 uint16_t evmcs_version = DEFAULT_EVMCS_VERSION;
1768 uint16_t supported_evmcs_version;
1769
1770 ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENLIGHTENED_VMCS, 0,
1771 (uintptr_t)&supported_evmcs_version);
1772
1773 /*
1774 * KVM is required to support EVMCS ver.1. as that's what 'hv-evmcs'
1775 * option sets. Note: we hardcode the maximum supported eVMCS version
1776 * to '1' as well so 'hv-evmcs' feature is migratable even when (and if)
1777 * ver.2 is implemented. A new option (e.g. 'hv-evmcs=2') will then have
1778 * to be added.
1779 */
1780 if (ret < 0) {
1781 error_report("Hyper-V %s is not supported by kernel",
1782 kvm_hyperv_properties[HYPERV_FEAT_EVMCS].desc);
1783 return ret;
1784 }
1785
1786 if (!evmcs_version_supported(evmcs_version, supported_evmcs_version)) {
1787 error_report("eVMCS version range [%d..%d] is not supported by "
1788 "kernel (supported: [%d..%d])", evmcs_version & 0xff,
1789 evmcs_version >> 8, supported_evmcs_version & 0xff,
1790 supported_evmcs_version >> 8);
1791 return -ENOTSUP;
1792 }
1793 }
1794
1795 if (cpu->hyperv_enforce_cpuid) {
1796 ret = kvm_vcpu_enable_cap(cs, KVM_CAP_HYPERV_ENFORCE_CPUID, 0, 1);
1797 if (ret < 0) {
1798 error_report("failed to enable KVM_CAP_HYPERV_ENFORCE_CPUID: %s",
1799 strerror(-ret));
1800 return ret;
1801 }
1802 }
1803
1804 /* Skip SynIC and VP_INDEX since they are hard deps already */
1805 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_STIMER) &&
1806 hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC) &&
1807 hyperv_feat_enabled(cpu, HYPERV_FEAT_RUNTIME)) {
1808 hyperv_x86_set_vmbus_recommended_features_enabled();
1809 }
1810
1811 return 0;
1812 }
1813
1814 static Error *invtsc_mig_blocker;
1815
1816 static void kvm_init_xsave(CPUX86State *env)
1817 {
1818 if (has_xsave2) {
1819 env->xsave_buf_len = QEMU_ALIGN_UP(has_xsave2, 4096);
1820 } else {
1821 env->xsave_buf_len = sizeof(struct kvm_xsave);
1822 }
1823
1824 env->xsave_buf = qemu_memalign(4096, env->xsave_buf_len);
1825 memset(env->xsave_buf, 0, env->xsave_buf_len);
1826 /*
1827 * The allocated storage must be large enough for all of the
1828 * possible XSAVE state components.
1829 */
1830 assert(kvm_arch_get_supported_cpuid(kvm_state, 0xd, 0, R_ECX) <=
1831 env->xsave_buf_len);
1832 }
1833
1834 static void kvm_init_nested_state(CPUX86State *env)
1835 {
1836 struct kvm_vmx_nested_state_hdr *vmx_hdr;
1837 uint32_t size;
1838
1839 if (!env->nested_state) {
1840 return;
1841 }
1842
1843 size = env->nested_state->size;
1844
1845 memset(env->nested_state, 0, size);
1846 env->nested_state->size = size;
1847
1848 if (cpu_has_vmx(env)) {
1849 env->nested_state->format = KVM_STATE_NESTED_FORMAT_VMX;
1850 vmx_hdr = &env->nested_state->hdr.vmx;
1851 vmx_hdr->vmxon_pa = -1ull;
1852 vmx_hdr->vmcs12_pa = -1ull;
1853 } else if (cpu_has_svm(env)) {
1854 env->nested_state->format = KVM_STATE_NESTED_FORMAT_SVM;
1855 }
1856 }
1857
1858 uint32_t kvm_x86_build_cpuid(CPUX86State *env, struct kvm_cpuid_entry2 *entries,
1859 uint32_t cpuid_i)
1860 {
1861 uint32_t limit, i, j;
1862 uint32_t unused;
1863 struct kvm_cpuid_entry2 *c;
1864
1865 cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);
1866
1867 for (i = 0; i <= limit; i++) {
1868 j = 0;
1869 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1870 goto full;
1871 }
1872 c = &entries[cpuid_i++];
1873 switch (i) {
1874 case 2: {
1875 /* Keep reading function 2 till all the input is received */
1876 int times;
1877
1878 c->function = i;
1879 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1880 times = c->eax & 0xff;
1881 if (times > 1) {
1882 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |
1883 KVM_CPUID_FLAG_STATE_READ_NEXT;
1884 }
1885
1886 for (j = 1; j < times; ++j) {
1887 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1888 goto full;
1889 }
1890 c = &entries[cpuid_i++];
1891 c->function = i;
1892 c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;
1893 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1894 }
1895 break;
1896 }
1897 case 0x1f:
1898 if (!x86_has_cpuid_0x1f(env_archcpu(env))) {
1899 cpuid_i--;
1900 break;
1901 }
1902 /* fallthrough */
1903 case 4:
1904 case 0xb:
1905 case 0xd:
1906 for (j = 0; ; j++) {
1907 c->function = i;
1908 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1909 c->index = j;
1910 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1911
1912 if (i == 4 && c->eax == 0) {
1913 break;
1914 }
1915 if (i == 0xb && !(c->ecx & 0xff00)) {
1916 break;
1917 }
1918 if (i == 0x1f && !(c->ecx & 0xff00)) {
1919 break;
1920 }
1921 if (i == 0xd && c->eax == 0) {
1922 if (j < 63) {
1923 continue;
1924 } else {
1925 cpuid_i--;
1926 break;
1927 }
1928 }
1929 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1930 goto full;
1931 }
1932 c = &entries[cpuid_i++];
1933 }
1934 break;
1935 case 0x12:
1936 for (j = 0; ; j++) {
1937 c->function = i;
1938 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1939 c->index = j;
1940 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1941
1942 if (j > 1 && (c->eax & 0xf) != 1) {
1943 break;
1944 }
1945
1946 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1947 goto full;
1948 }
1949 c = &entries[cpuid_i++];
1950 }
1951 break;
1952 case 0x7:
1953 case 0x14:
1954 case 0x1d:
1955 case 0x1e:
1956 case 0x24: {
1957 uint32_t times;
1958
1959 c->function = i;
1960 c->index = 0;
1961 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1962 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1963 times = c->eax;
1964
1965 for (j = 1; j <= times; ++j) {
1966 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1967 goto full;
1968 }
1969 c = &entries[cpuid_i++];
1970 c->function = i;
1971 c->index = j;
1972 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1973 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
1974 }
1975 break;
1976 }
1977 default:
1978 c->function = i;
1979 c->flags = 0;
1980 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
1981 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
1982 /*
1983 * KVM already returns all zeroes if a CPUID entry is missing,
1984 * so we can omit it and avoid hitting KVM's 80-entry limit.
1985 */
1986 cpuid_i--;
1987 }
1988 break;
1989 }
1990 }
1991
1992 cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);
1993
1994 for (i = 0x80000000; i <= limit; i++) {
1995 j = 0;
1996 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
1997 goto full;
1998 }
1999 c = &entries[cpuid_i++];
2000
2001 switch (i) {
2002 case 0x8000001d:
2003 /* Query for all AMD cache information leaves */
2004 for (j = 0; ; j++) {
2005 c->function = i;
2006 c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
2007 c->index = j;
2008 cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);
2009
2010 if (c->eax == 0) {
2011 break;
2012 }
2013 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2014 goto full;
2015 }
2016 c = &entries[cpuid_i++];
2017 }
2018 break;
2019 default:
2020 c->function = i;
2021 c->flags = 0;
2022 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2023 if (!c->eax && !c->ebx && !c->ecx && !c->edx) {
2024 /*
2025 * KVM already returns all zeroes if a CPUID entry is missing,
2026 * so we can omit it and avoid hitting KVM's 80-entry limit.
2027 */
2028 cpuid_i--;
2029 }
2030 break;
2031 }
2032 }
2033
2034 /* Call Centaur's CPUID instructions they are supported. */
2035 if (env->cpuid_xlevel2 > 0) {
2036 cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);
2037
2038 for (i = 0xC0000000; i <= limit; i++) {
2039 j = 0;
2040 if (cpuid_i == KVM_MAX_CPUID_ENTRIES) {
2041 goto full;
2042 }
2043 c = &entries[cpuid_i++];
2044
2045 c->function = i;
2046 c->flags = 0;
2047 cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);
2048 }
2049 }
2050
2051 return cpuid_i;
2052
2053 full:
2054 fprintf(stderr, "cpuid_data is full, no space for "
2055 "cpuid(eax:0x%x,ecx:0x%x)\n", i, j);
2056 abort();
2057 }
2058
2059 int kvm_arch_pre_create_vcpu(CPUState *cpu, Error **errp)
2060 {
2061 static bool first = true;
2062 int ret;
2063
2064 if (first) {
2065 first = false;
2066
2067 /*
2068 * Since Linux v5.18, KVM provides a VM-level capability to easily
2069 * disable PMUs; however, QEMU has been providing PMU property per
2070 * CPU since v1.6. In order to accommodate both, have to configure
2071 * the VM-level capability here.
2072 *
2073 * KVM_PMU_CAP_DISABLE doesn't change the PMU
2074 * behavior on Intel platform because current "pmu" property works
2075 * as expected.
2076 */
2077 if ((pmu_cap & KVM_PMU_CAP_DISABLE) && !X86_CPU(cpu)->enable_pmu) {
2078 ret = kvm_vm_enable_cap(kvm_state, KVM_CAP_PMU_CAPABILITY, 0,
2079 KVM_PMU_CAP_DISABLE);
2080 if (ret < 0) {
2081 error_setg_errno(errp, -ret,
2082 "Failed to set KVM_PMU_CAP_DISABLE");
2083 return ret;
2084 }
2085 }
2086 }
2087
2088 if (is_tdx_vm()) {
2089 return tdx_pre_create_vcpu(cpu, errp);
2090 }
2091
2092 return 0;
2093 }
2094
2095 static void kvm_init_pmu_info_intel(struct kvm_cpuid2 *cpuid)
2096 {
2097 struct kvm_cpuid_entry2 *c;
2098
2099 c = cpuid_find_entry(cpuid, 0xa, 0);
2100
2101 if (!c) {
2102 return;
2103 }
2104
2105 pmu_version = c->eax & 0xff;
2106 if (pmu_version > 0) {
2107 num_pmu_gp_counters = (c->eax & 0xff00) >> 8;
2108
2109 /*
2110 * Shouldn't be more than 32, since that's the number of bits
2111 * available in EBX to tell us _which_ counters are available.
2112 * Play it safe.
2113 */
2114 if (num_pmu_gp_counters > MAX_GP_COUNTERS) {
2115 num_pmu_gp_counters = MAX_GP_COUNTERS;
2116 }
2117
2118 if (pmu_version > 1) {
2119 num_pmu_fixed_counters = c->edx & 0x1f;
2120
2121 if (num_pmu_fixed_counters > MAX_FIXED_COUNTERS) {
2122 num_pmu_fixed_counters = MAX_FIXED_COUNTERS;
2123 }
2124 }
2125 }
2126 }
2127
2128 static void kvm_init_pmu_info_amd(struct kvm_cpuid2 *cpuid, X86CPU *cpu)
2129 {
2130 struct kvm_cpuid_entry2 *c;
2131 int64_t family;
2132
2133 family = object_property_get_int(OBJECT(cpu), "family", NULL);
2134 if (family < 0) {
2135 return;
2136 }
2137
2138 if (family < 6) {
2139 error_report("AMD performance-monitoring is supported from "
2140 "K7 and later");
2141 return;
2142 }
2143
2144 pmu_version = 1;
2145 num_pmu_gp_counters = AMD64_NUM_COUNTERS;
2146
2147 c = cpuid_find_entry(cpuid, 0x80000001, 0);
2148 if (!c) {
2149 return;
2150 }
2151
2152 if (!(c->ecx & CPUID_EXT3_PERFCORE)) {
2153 return;
2154 }
2155
2156 num_pmu_gp_counters = AMD64_NUM_COUNTERS_CORE;
2157
2158 c = cpuid_find_entry(cpuid, 0x80000022, 0);
2159 if (c && (c->eax & CPUID_8000_0022_EAX_PERFMON_V2)) {
2160 pmu_version = 2;
2161 num_pmu_gp_counters = c->ebx & 0xf;
2162
2163 if (num_pmu_gp_counters > MAX_GP_COUNTERS) {
2164 num_pmu_gp_counters = MAX_GP_COUNTERS;
2165 }
2166 }
2167 }
2168
2169 static bool is_host_compat_vendor(CPUX86State *env)
2170 {
2171 char host_vendor[CPUID_VENDOR_SZ + 1];
2172
2173 host_cpu_vendor_fms(host_vendor, NULL, NULL, NULL);
2174
2175 /*
2176 * Intel and Zhaoxin are compatible.
2177 */
2178 if ((g_str_equal(host_vendor, CPUID_VENDOR_INTEL) ||
2179 g_str_equal(host_vendor, CPUID_VENDOR_ZHAOXIN1) ||
2180 g_str_equal(host_vendor, CPUID_VENDOR_ZHAOXIN2)) &&
2181 (IS_INTEL_CPU(env) || IS_ZHAOXIN_CPU(env))) {
2182 return true;
2183 }
2184
2185 return g_str_equal(host_vendor, CPUID_VENDOR_AMD) &&
2186 IS_AMD_CPU(env);
2187 }
2188
2189 static void kvm_init_pmu_info(struct kvm_cpuid2 *cpuid, X86CPU *cpu)
2190 {
2191 CPUX86State *env = &cpu->env;
2192
2193 /*
2194 * If KVM_CAP_PMU_CAPABILITY is not supported, there is no way to
2195 * disable the AMD PMU virtualization.
2196 *
2197 * Assume the user is aware of this when !cpu->enable_pmu. AMD PMU
2198 * registers are not going to reset, even they are still available to
2199 * guest VM.
2200 */
2201 if (!cpu->enable_pmu) {
2202 return;
2203 }
2204
2205 /*
2206 * It is not supported to virtualize AMD PMU registers on Intel
2207 * processors, nor to virtualize Intel PMU registers on AMD processors.
2208 */
2209 if (!is_host_compat_vendor(env)) {
2210 error_report("host doesn't support requested feature: vPMU");
2211 return;
2212 }
2213
2214 if (IS_INTEL_CPU(env) || IS_ZHAOXIN_CPU(env)) {
2215 kvm_init_pmu_info_intel(cpuid);
2216 } else if (IS_AMD_CPU(env)) {
2217 kvm_init_pmu_info_amd(cpuid, cpu);
2218 }
2219 }
2220
2221 int kvm_arch_init_vcpu(CPUState *cs)
2222 {
2223 struct {
2224 struct kvm_cpuid2 cpuid;
2225 struct kvm_cpuid_entry2 entries[KVM_MAX_CPUID_ENTRIES];
2226 } cpuid_data;
2227 /*
2228 * The kernel defines these structs with padding fields so there
2229 * should be no extra padding in our cpuid_data struct.
2230 */
2231 QEMU_BUILD_BUG_ON(sizeof(cpuid_data) !=
2232 sizeof(struct kvm_cpuid2) +
2233 sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES);
2234
2235 X86CPU *cpu = X86_CPU(cs);
2236 CPUX86State *env = &cpu->env;
2237 uint32_t cpuid_i;
2238 struct kvm_cpuid_entry2 *c;
2239 uint32_t signature[3];
2240 int kvm_base = KVM_CPUID_SIGNATURE;
2241 int max_nested_state_len;
2242 int r;
2243 Error *local_err = NULL;
2244
2245 if (current_machine->cgs) {
2246 r = x86_confidential_guest_check_features(
2247 X86_CONFIDENTIAL_GUEST(current_machine->cgs), cs);
2248 if (r < 0) {
2249 return r;
2250 }
2251 }
2252
2253 memset(&cpuid_data, 0, sizeof(cpuid_data));
2254
2255 cpuid_i = 0;
2256
2257 has_xsave2 = kvm_check_extension(cs->kvm_state, KVM_CAP_XSAVE2);
2258
2259 r = kvm_arch_set_tsc_khz(cs);
2260 if (r < 0) {
2261 return r;
2262 }
2263
2264 /* vcpu's TSC frequency is either specified by user, or following
2265 * the value used by KVM if the former is not present. In the
2266 * latter case, we query it from KVM and record in env->tsc_khz,
2267 * so that vcpu's TSC frequency can be migrated later via this field.
2268 */
2269 if (!env->tsc_khz) {
2270 r = kvm_check_extension(cs->kvm_state, KVM_CAP_GET_TSC_KHZ) ?
2271 kvm_vcpu_ioctl(cs, KVM_GET_TSC_KHZ) :
2272 -ENOTSUP;
2273 if (r > 0) {
2274 env->tsc_khz = r;
2275 }
2276 }
2277
2278 env->apic_bus_freq = KVM_APIC_BUS_FREQUENCY;
2279
2280 /*
2281 * kvm_hyperv_expand_features() is called here for the second time in case
2282 * KVM_CAP_SYS_HYPERV_CPUID is not supported. While we can't possibly handle
2283 * 'query-cpu-model-expansion' in this case as we don't have a KVM vCPU to
2284 * check which Hyper-V enlightenments are supported and which are not, we
2285 * can still proceed and check/expand Hyper-V enlightenments here so legacy
2286 * behavior is preserved.
2287 */
2288 if (!kvm_hyperv_expand_features(cpu, &local_err)) {
2289 error_report_err(local_err);
2290 return -ENOSYS;
2291 }
2292
2293 if (hyperv_enabled(cpu)) {
2294 r = hyperv_init_vcpu(cpu);
2295 if (r) {
2296 return r;
2297 }
2298
2299 cpuid_i = hyperv_fill_cpuids(cs, cpuid_data.entries);
2300 kvm_base = KVM_CPUID_SIGNATURE_NEXT;
2301 has_msr_hv_hypercall = true;
2302 }
2303
2304 if (cs->kvm_state->xen_version) {
2305 #ifdef CONFIG_XEN_EMU
2306 struct kvm_cpuid_entry2 *xen_max_leaf;
2307
2308 memcpy(signature, "XenVMMXenVMM", 12);
2309
2310 xen_max_leaf = c = &cpuid_data.entries[cpuid_i++];
2311 c->function = kvm_base + XEN_CPUID_SIGNATURE;
2312 c->eax = kvm_base + XEN_CPUID_TIME;
2313 c->ebx = signature[0];
2314 c->ecx = signature[1];
2315 c->edx = signature[2];
2316
2317 c = &cpuid_data.entries[cpuid_i++];
2318 c->function = kvm_base + XEN_CPUID_VENDOR;
2319 c->eax = cs->kvm_state->xen_version;
2320 c->ebx = 0;
2321 c->ecx = 0;
2322 c->edx = 0;
2323
2324 c = &cpuid_data.entries[cpuid_i++];
2325 c->function = kvm_base + XEN_CPUID_HVM_MSR;
2326 /* Number of hypercall-transfer pages */
2327 c->eax = 1;
2328 /* Hypercall MSR base address */
2329 if (hyperv_enabled(cpu)) {
2330 c->ebx = XEN_HYPERCALL_MSR_HYPERV;
2331 kvm_xen_init(cs->kvm_state, c->ebx);
2332 } else {
2333 c->ebx = XEN_HYPERCALL_MSR;
2334 }
2335 c->ecx = 0;
2336 c->edx = 0;
2337
2338 c = &cpuid_data.entries[cpuid_i++];
2339 c->function = kvm_base + XEN_CPUID_TIME;
2340 c->eax = ((!!tsc_is_stable_and_known(env) << 1) |
2341 (!!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP) << 2));
2342 /* default=0 (emulate if necessary) */
2343 c->ebx = 0;
2344 /* guest tsc frequency */
2345 c->ecx = env->user_tsc_khz;
2346 /* guest tsc incarnation (migration count) */
2347 c->edx = 0;
2348
2349 c = &cpuid_data.entries[cpuid_i++];
2350 c->function = kvm_base + XEN_CPUID_HVM;
2351 xen_max_leaf->eax = kvm_base + XEN_CPUID_HVM;
2352 if (cs->kvm_state->xen_version >= XEN_VERSION(4, 5)) {
2353 c->function = kvm_base + XEN_CPUID_HVM;
2354
2355 if (cpu->xen_vapic) {
2356 c->eax |= XEN_HVM_CPUID_APIC_ACCESS_VIRT;
2357 c->eax |= XEN_HVM_CPUID_X2APIC_VIRT;
2358 }
2359
2360 c->eax |= XEN_HVM_CPUID_IOMMU_MAPPINGS;
2361
2362 if (cs->kvm_state->xen_version >= XEN_VERSION(4, 6)) {
2363 c->eax |= XEN_HVM_CPUID_VCPU_ID_PRESENT;
2364 c->ebx = cs->cpu_index;
2365 }
2366
2367 if (cs->kvm_state->xen_version >= XEN_VERSION(4, 17)) {
2368 c->eax |= XEN_HVM_CPUID_UPCALL_VECTOR;
2369 }
2370 }
2371
2372 r = kvm_xen_init_vcpu(cs);
2373 if (r) {
2374 return r;
2375 }
2376
2377 kvm_base += 0x100;
2378 #else /* CONFIG_XEN_EMU */
2379 /* This should never happen as kvm_arch_init() would have died first. */
2380 fprintf(stderr, "Cannot enable Xen CPUID without Xen support\n");
2381 abort();
2382 #endif
2383 } else if (cpu->expose_kvm) {
2384 memcpy(signature, "KVMKVMKVM\0\0\0", 12);
2385 c = &cpuid_data.entries[cpuid_i++];
2386 c->function = KVM_CPUID_SIGNATURE | kvm_base;
2387 c->eax = KVM_CPUID_FEATURES | kvm_base;
2388 c->ebx = signature[0];
2389 c->ecx = signature[1];
2390 c->edx = signature[2];
2391
2392 c = &cpuid_data.entries[cpuid_i++];
2393 c->function = KVM_CPUID_FEATURES | kvm_base;
2394 c->eax = env->features[FEAT_KVM];
2395 c->edx = env->features[FEAT_KVM_HINTS];
2396 }
2397
2398 if (cpu->kvm_pv_enforce_cpuid) {
2399 r = kvm_vcpu_enable_cap(cs, KVM_CAP_ENFORCE_PV_FEATURE_CPUID, 0, 1);
2400 if (r < 0) {
2401 fprintf(stderr,
2402 "failed to enable KVM_CAP_ENFORCE_PV_FEATURE_CPUID: %s",
2403 strerror(-r));
2404 abort();
2405 }
2406 }
2407
2408 cpuid_i = kvm_x86_build_cpuid(env, cpuid_data.entries, cpuid_i);
2409 cpuid_data.cpuid.nent = cpuid_i;
2410
2411 kvm_init_pmu_info(&cpuid_data.cpuid, cpu);
2412
2413 if (x86_cpu_family(env->cpuid_version) >= 6
2414 && (env->features[FEAT_1_EDX] & (CPUID_MCE | CPUID_MCA)) ==
2415 (CPUID_MCE | CPUID_MCA)) {
2416 uint64_t mcg_cap, unsupported_caps;
2417 int banks;
2418 int ret;
2419
2420 ret = kvm_get_mce_cap_supported(cs->kvm_state, &mcg_cap, &banks);
2421 if (ret < 0) {
2422 fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));
2423 return ret;
2424 }
2425
2426 if (banks < (env->mcg_cap & MCG_CAP_BANKS_MASK)) {
2427 error_report("kvm: Unsupported MCE bank count (QEMU = %d, KVM = %d)",
2428 (int)(env->mcg_cap & MCG_CAP_BANKS_MASK), banks);
2429 return -ENOTSUP;
2430 }
2431
2432 unsupported_caps = env->mcg_cap & ~(mcg_cap | MCG_CAP_BANKS_MASK);
2433 if (unsupported_caps) {
2434 if (unsupported_caps & MCG_LMCE_P) {
2435 error_report("kvm: LMCE not supported");
2436 return -ENOTSUP;
2437 }
2438 warn_report("Unsupported MCG_CAP bits: 0x%" PRIx64,
2439 unsupported_caps);
2440 }
2441
2442 env->mcg_cap &= mcg_cap | MCG_CAP_BANKS_MASK;
2443 ret = kvm_vcpu_ioctl(cs, KVM_X86_SETUP_MCE, &env->mcg_cap);
2444 if (ret < 0) {
2445 fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));
2446 return ret;
2447 }
2448 }
2449
2450 cpu->vmsentry = qemu_add_vm_change_state_handler(cpu_update_state, env);
2451
2452 c = cpuid_find_entry(&cpuid_data.cpuid, 1, 0);
2453 if (c) {
2454 has_msr_feature_control = !!(c->ecx & CPUID_EXT_VMX) ||
2455 !!(c->ecx & CPUID_EXT_SMX);
2456 }
2457
2458 c = cpuid_find_entry(&cpuid_data.cpuid, 7, 0);
2459 if (c && (c->ebx & CPUID_7_0_EBX_SGX)) {
2460 has_msr_feature_control = true;
2461 }
2462
2463 if (env->mcg_cap & MCG_LMCE_P) {
2464 has_msr_mcg_ext_ctl = has_msr_feature_control = true;
2465 }
2466
2467 if (!env->user_tsc_khz) {
2468 if ((env->features[FEAT_8000_0007_EDX] & CPUID_APM_INVTSC) &&
2469 invtsc_mig_blocker == NULL) {
2470 error_setg(&invtsc_mig_blocker,
2471 "State blocked by non-migratable CPU device"
2472 " (invtsc flag)");
2473 r = migrate_add_blocker(&invtsc_mig_blocker, &local_err);
2474 if (r < 0) {
2475 error_report_err(local_err);
2476 return r;
2477 }
2478 }
2479 }
2480
2481 if (cpu->vmware_cpuid_freq
2482 /* Guests depend on 0x40000000 to detect this feature, so only expose
2483 * it if KVM exposes leaf 0x40000000. (Conflicts with Hyper-V) */
2484 && cpu->expose_kvm
2485 && kvm_base == KVM_CPUID_SIGNATURE
2486 /* TSC clock must be stable and known for this feature. */
2487 && tsc_is_stable_and_known(env)) {
2488
2489 c = &cpuid_data.entries[cpuid_i++];
2490 c->function = KVM_CPUID_SIGNATURE | 0x10;
2491 c->eax = env->tsc_khz;
2492 c->ebx = env->apic_bus_freq / 1000; /* Hz to KHz */
2493 c->ecx = c->edx = 0;
2494
2495 c = cpuid_find_entry(&cpuid_data.cpuid, kvm_base, 0);
2496 c->eax = MAX(c->eax, KVM_CPUID_SIGNATURE | 0x10);
2497 }
2498
2499 cpuid_data.cpuid.nent = cpuid_i;
2500
2501 cpuid_data.cpuid.padding = 0;
2502 r = kvm_vcpu_ioctl(cs, KVM_SET_CPUID2, &cpuid_data);
2503 if (r) {
2504 goto fail;
2505 }
2506 kvm_init_xsave(env);
2507
2508 max_nested_state_len = kvm_max_nested_state_length();
2509 if (max_nested_state_len > 0) {
2510 assert(max_nested_state_len >= offsetof(struct kvm_nested_state, data));
2511
2512 if (cpu_has_vmx(env) || cpu_has_svm(env)) {
2513 env->nested_state = g_malloc0(max_nested_state_len);
2514 env->nested_state->size = max_nested_state_len;
2515
2516 kvm_init_nested_state(env);
2517 }
2518 }
2519
2520 cpu->kvm_msr_buf = g_malloc0(MSR_BUF_SIZE);
2521
2522 if (!(env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_RDTSCP)) {
2523 has_msr_tsc_aux = false;
2524 }
2525
2526 kvm_init_msrs(cpu);
2527
2528 return 0;
2529
2530 fail:
2531 migrate_del_blocker(&invtsc_mig_blocker);
2532
2533 return r;
2534 }
2535
2536 int kvm_arch_destroy_vcpu(CPUState *cs)
2537 {
2538 X86CPU *cpu = X86_CPU(cs);
2539 CPUX86State *env = &cpu->env;
2540
2541 g_free(env->xsave_buf);
2542
2543 g_free(cpu->kvm_msr_buf);
2544 cpu->kvm_msr_buf = NULL;
2545
2546 g_free(env->nested_state);
2547 env->nested_state = NULL;
2548
2549 qemu_del_vm_change_state_handler(cpu->vmsentry);
2550
2551 return 0;
2552 }
2553
2554 void kvm_arch_reset_vcpu(X86CPU *cpu)
2555 {
2556 CPUX86State *env = &cpu->env;
2557
2558 env->xcr0 = 1;
2559 if (kvm_irqchip_in_kernel()) {
2560 env->mp_state = cpu_is_bsp(cpu) ? KVM_MP_STATE_RUNNABLE :
2561 KVM_MP_STATE_UNINITIALIZED;
2562 } else {
2563 env->mp_state = KVM_MP_STATE_RUNNABLE;
2564 }
2565
2566 /* enabled by default */
2567 env->poll_control_msr = 1;
2568
2569 kvm_init_nested_state(env);
2570
2571 sev_es_set_reset_vector(CPU(cpu));
2572 }
2573
2574 void kvm_arch_after_reset_vcpu(X86CPU *cpu)
2575 {
2576 CPUX86State *env = &cpu->env;
2577 int i;
2578
2579 /*
2580 * Reset SynIC after all other devices have been reset to let them remove
2581 * their SINT routes first.
2582 */
2583 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
2584 for (i = 0; i < ARRAY_SIZE(env->msr_hv_synic_sint); i++) {
2585 env->msr_hv_synic_sint[i] = HV_SINT_MASKED;
2586 }
2587
2588 hyperv_x86_synic_reset(cpu);
2589 }
2590 }
2591
2592 void kvm_arch_reset_parked_vcpu(unsigned long vcpu_id, int kvm_fd)
2593 {
2594 g_autofree struct kvm_msrs *msrs = NULL;
2595
2596 msrs = g_malloc0(sizeof(*msrs) + sizeof(msrs->entries[0]));
2597 msrs->entries[0].index = MSR_IA32_TSC;
2598 msrs->entries[0].data = 1; /* match the value in x86_cpu_reset() */
2599 msrs->nmsrs++;
2600
2601 if (ioctl(kvm_fd, KVM_SET_MSRS, msrs) != 1) {
2602 warn_report("parked vCPU %lu TSC reset failed: %d",
2603 vcpu_id, errno);
2604 }
2605 }
2606
2607 void kvm_arch_do_init_vcpu(X86CPU *cpu)
2608 {
2609 CPUX86State *env = &cpu->env;
2610
2611 /* APs get directly into wait-for-SIPI state. */
2612 if (env->mp_state == KVM_MP_STATE_UNINITIALIZED) {
2613 env->mp_state = KVM_MP_STATE_INIT_RECEIVED;
2614 }
2615 }
2616
2617 static int kvm_get_supported_feature_msrs(KVMState *s)
2618 {
2619 int ret = 0;
2620
2621 if (kvm_feature_msrs != NULL) {
2622 return 0;
2623 }
2624
2625 if (!kvm_check_extension(s, KVM_CAP_GET_MSR_FEATURES)) {
2626 return 0;
2627 }
2628
2629 struct kvm_msr_list msr_list;
2630
2631 msr_list.nmsrs = 0;
2632 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, &msr_list);
2633 if (ret < 0 && ret != -E2BIG) {
2634 error_report("Fetch KVM feature MSR list failed: %s",
2635 strerror(-ret));
2636 return ret;
2637 }
2638
2639 assert(msr_list.nmsrs > 0);
2640 kvm_feature_msrs = g_malloc0(sizeof(msr_list) +
2641 msr_list.nmsrs * sizeof(msr_list.indices[0]));
2642
2643 kvm_feature_msrs->nmsrs = msr_list.nmsrs;
2644 ret = kvm_ioctl(s, KVM_GET_MSR_FEATURE_INDEX_LIST, kvm_feature_msrs);
2645
2646 if (ret < 0) {
2647 error_report("Fetch KVM feature MSR list failed: %s",
2648 strerror(-ret));
2649 g_free(kvm_feature_msrs);
2650 kvm_feature_msrs = NULL;
2651 return ret;
2652 }
2653
2654 return 0;
2655 }
2656
2657 static int kvm_get_supported_msrs(KVMState *s)
2658 {
2659 int ret = 0;
2660 struct kvm_msr_list msr_list, *kvm_msr_list;
2661
2662 /*
2663 * Obtain MSR list from KVM. These are the MSRs that we must
2664 * save/restore.
2665 */
2666 msr_list.nmsrs = 0;
2667 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, &msr_list);
2668 if (ret < 0 && ret != -E2BIG) {
2669 return ret;
2670 }
2671 /*
2672 * Old kernel modules had a bug and could write beyond the provided
2673 * memory. Allocate at least a safe amount of 1K.
2674 */
2675 kvm_msr_list = g_malloc0(MAX(1024, sizeof(msr_list) +
2676 msr_list.nmsrs *
2677 sizeof(msr_list.indices[0])));
2678
2679 kvm_msr_list->nmsrs = msr_list.nmsrs;
2680 ret = kvm_ioctl(s, KVM_GET_MSR_INDEX_LIST, kvm_msr_list);
2681 if (ret >= 0) {
2682 int i;
2683
2684 for (i = 0; i < kvm_msr_list->nmsrs; i++) {
2685 switch (kvm_msr_list->indices[i]) {
2686 case MSR_STAR:
2687 has_msr_star = true;
2688 break;
2689 case MSR_VM_HSAVE_PA:
2690 has_msr_hsave_pa = true;
2691 break;
2692 case MSR_TSC_AUX:
2693 has_msr_tsc_aux = true;
2694 break;
2695 case MSR_TSC_ADJUST:
2696 has_msr_tsc_adjust = true;
2697 break;
2698 case MSR_IA32_TSCDEADLINE:
2699 has_msr_tsc_deadline = true;
2700 break;
2701 case MSR_IA32_SMBASE:
2702 has_msr_smbase = true;
2703 break;
2704 case MSR_SMI_COUNT:
2705 has_msr_smi_count = true;
2706 break;
2707 case MSR_IA32_MISC_ENABLE:
2708 has_msr_misc_enable = true;
2709 break;
2710 case MSR_IA32_BNDCFGS:
2711 has_msr_bndcfgs = true;
2712 break;
2713 case MSR_IA32_XSS:
2714 has_msr_xss = true;
2715 break;
2716 case MSR_IA32_UMWAIT_CONTROL:
2717 has_msr_umwait = true;
2718 break;
2719 case HV_X64_MSR_CRASH_CTL:
2720 has_msr_hv_crash = true;
2721 break;
2722 case HV_X64_MSR_RESET:
2723 has_msr_hv_reset = true;
2724 break;
2725 case HV_X64_MSR_VP_INDEX:
2726 has_msr_hv_vpindex = true;
2727 break;
2728 case HV_X64_MSR_VP_RUNTIME:
2729 has_msr_hv_runtime = true;
2730 break;
2731 case HV_X64_MSR_SCONTROL:
2732 has_msr_hv_synic = true;
2733 break;
2734 case HV_X64_MSR_STIMER0_CONFIG:
2735 has_msr_hv_stimer = true;
2736 break;
2737 case HV_X64_MSR_TSC_FREQUENCY:
2738 has_msr_hv_frequencies = true;
2739 break;
2740 case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
2741 has_msr_hv_reenlightenment = true;
2742 break;
2743 case HV_X64_MSR_SYNDBG_OPTIONS:
2744 has_msr_hv_syndbg_options = true;
2745 break;
2746 case MSR_IA32_SPEC_CTRL:
2747 has_msr_spec_ctrl = true;
2748 break;
2749 case MSR_AMD64_TSC_RATIO:
2750 has_tsc_scale_msr = true;
2751 break;
2752 case MSR_IA32_TSX_CTRL:
2753 has_msr_tsx_ctrl = true;
2754 break;
2755 case MSR_VIRT_SSBD:
2756 has_msr_virt_ssbd = true;
2757 break;
2758 case MSR_IA32_ARCH_CAPABILITIES:
2759 has_msr_arch_capabs = true;
2760 break;
2761 case MSR_IA32_CORE_CAPABILITY:
2762 has_msr_core_capabs = true;
2763 break;
2764 case MSR_IA32_PERF_CAPABILITIES:
2765 has_msr_perf_capabs = true;
2766 break;
2767 case MSR_IA32_VMX_VMFUNC:
2768 has_msr_vmx_vmfunc = true;
2769 break;
2770 case MSR_IA32_UCODE_REV:
2771 has_msr_ucode_rev = true;
2772 break;
2773 case MSR_IA32_VMX_PROCBASED_CTLS2:
2774 has_msr_vmx_procbased_ctls2 = true;
2775 break;
2776 case MSR_IA32_PKRS:
2777 has_msr_pkrs = true;
2778 break;
2779 case MSR_K7_HWCR:
2780 has_msr_hwcr = true;
2781 }
2782 }
2783 }
2784
2785 g_free(kvm_msr_list);
2786
2787 return ret;
2788 }
2789
2790 static bool kvm_rdmsr_core_thread_count(X86CPU *cpu,
2791 uint32_t msr,
2792 uint64_t *val)
2793 {
2794 *val = cpu_x86_get_msr_core_thread_count(cpu);
2795
2796 return true;
2797 }
2798
2799 static bool kvm_rdmsr_rapl_power_unit(X86CPU *cpu,
2800 uint32_t msr,
2801 uint64_t *val)
2802 {
2803
2804 CPUState *cs = CPU(cpu);
2805
2806 *val = cs->kvm_state->msr_energy.msr_unit;
2807
2808 return true;
2809 }
2810
2811 static bool kvm_rdmsr_pkg_power_limit(X86CPU *cpu,
2812 uint32_t msr,
2813 uint64_t *val)
2814 {
2815
2816 CPUState *cs = CPU(cpu);
2817
2818 *val = cs->kvm_state->msr_energy.msr_limit;
2819
2820 return true;
2821 }
2822
2823 static bool kvm_rdmsr_pkg_power_info(X86CPU *cpu,
2824 uint32_t msr,
2825 uint64_t *val)
2826 {
2827
2828 CPUState *cs = CPU(cpu);
2829
2830 *val = cs->kvm_state->msr_energy.msr_info;
2831
2832 return true;
2833 }
2834
2835 static bool kvm_rdmsr_pkg_energy_status(X86CPU *cpu,
2836 uint32_t msr,
2837 uint64_t *val)
2838 {
2839
2840 CPUState *cs = CPU(cpu);
2841 *val = cs->kvm_state->msr_energy.msr_value[cs->cpu_index];
2842
2843 return true;
2844 }
2845
2846 static Notifier smram_machine_done;
2847 static KVMMemoryListener smram_listener;
2848 static AddressSpace smram_address_space;
2849 static MemoryRegion smram_as_root;
2850 static MemoryRegion smram_as_mem;
2851
2852 static void register_smram_listener(Notifier *n, void *unused)
2853 {
2854 CPUState *cpu;
2855 MemoryRegion *smram =
2856 (MemoryRegion *) object_resolve_path("/machine/smram", NULL);
2857
2858 /* Outer container... */
2859 memory_region_init(&smram_as_root, OBJECT(kvm_state), "mem-container-smram", ~0ull);
2860 memory_region_set_enabled(&smram_as_root, true);
2861
2862 /* ... with two regions inside: normal system memory with low
2863 * priority, and...
2864 */
2865 memory_region_init_alias(&smram_as_mem, OBJECT(kvm_state), "mem-smram",
2866 get_system_memory(), 0, ~0ull);
2867 memory_region_add_subregion_overlap(&smram_as_root, 0, &smram_as_mem, 0);
2868 memory_region_set_enabled(&smram_as_mem, true);
2869
2870 if (smram) {
2871 /* ... SMRAM with higher priority */
2872 memory_region_add_subregion_overlap(&smram_as_root, 0, smram, 10);
2873 memory_region_set_enabled(smram, true);
2874 }
2875
2876 address_space_init(&smram_address_space, &smram_as_root, "KVM-SMRAM");
2877 kvm_memory_listener_register(kvm_state, &smram_listener,
2878 &smram_address_space, X86ASIdx_SMM, "kvm-smram");
2879
2880 CPU_FOREACH(cpu) {
2881 cpu_address_space_init(cpu, X86ASIdx_SMM, "cpu-smm", &smram_as_root);
2882 }
2883 }
2884
2885 static int unregister_smram_listener(NotifierWithReturn *notifier,
2886 void *data, Error** errp)
2887 {
2888 if (!((VmfdChangeNotifier *)data)->pre) {
2889 return 0;
2890 }
2891
2892 memory_listener_unregister(&smram_listener.listener);
2893 return 0;
2894 }
2895
2896 /* It should only be called in cpu's hotplug callback */
2897 void kvm_smm_cpu_address_space_init(X86CPU *cpu)
2898 {
2899 cpu_address_space_init(CPU(cpu), X86ASIdx_SMM, "cpu-smm", &smram_as_root);
2900 }
2901
2902 static void *kvm_msr_energy_thread(void *data)
2903 {
2904 KVMState *s = data;
2905 struct KVMMsrEnergy *vmsr = &s->msr_energy;
2906
2907 g_autofree vmsr_package_energy_stat *pkg_stat = NULL;
2908 g_autofree vmsr_thread_stat *thd_stat = NULL;
2909 g_autofree CPUState *cpu = NULL;
2910 g_autofree unsigned int *vpkgs_energy_stat = NULL;
2911 unsigned int num_threads = 0;
2912
2913 X86CPUTopoIDs topo_ids;
2914
2915 rcu_register_thread();
2916
2917 /* Allocate memory for each package energy status */
2918 pkg_stat = g_new0(vmsr_package_energy_stat, vmsr->host_topo.maxpkgs);
2919
2920 /* Allocate memory for thread stats */
2921 thd_stat = g_new0(vmsr_thread_stat, 1);
2922
2923 /* Allocate memory for holding virtual package energy counter */
2924 vpkgs_energy_stat = g_new0(unsigned int, vmsr->guest_vsockets);
2925
2926 /* Populate the max tick of each packages */
2927 for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2928 /*
2929 * Max numbers of ticks per package
2930 * Time in second * Number of ticks/second * Number of cores/package
2931 * ex: 100 ticks/second/CPU, 12 CPUs per Package gives 1200 ticks max
2932 */
2933 vmsr->host_topo.maxticks[i] = (MSR_ENERGY_THREAD_SLEEP_US / 1000000)
2934 * sysconf(_SC_CLK_TCK)
2935 * vmsr->host_topo.pkg_cpu_count[i];
2936 }
2937
2938 while (true) {
2939 /* Get all qemu threads id */
2940 g_autofree pid_t *thread_ids
2941 = vmsr_get_thread_ids(vmsr->pid, &num_threads);
2942
2943 if (thread_ids == NULL) {
2944 goto clean;
2945 }
2946
2947 thd_stat = g_renew(vmsr_thread_stat, thd_stat, num_threads);
2948 /* Unlike g_new0, g_renew0 function doesn't exist yet... */
2949 memset(thd_stat, 0, num_threads * sizeof(vmsr_thread_stat));
2950
2951 /* Populate all the thread stats */
2952 for (int i = 0; i < num_threads; i++) {
2953 thd_stat[i].utime = g_new0(unsigned long long, 2);
2954 thd_stat[i].stime = g_new0(unsigned long long, 2);
2955 thd_stat[i].thread_id = thread_ids[i];
2956 vmsr_read_thread_stat(vmsr->pid,
2957 thd_stat[i].thread_id,
2958 &thd_stat[i].utime[0],
2959 &thd_stat[i].stime[0],
2960 &thd_stat[i].cpu_id);
2961 thd_stat[i].pkg_id =
2962 vmsr_get_physical_package_id(thd_stat[i].cpu_id);
2963 }
2964
2965 /* Retrieve all packages power plane energy counter */
2966 for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2967 for (int j = 0; j < num_threads; j++) {
2968 /*
2969 * Use the first thread we found that ran on the CPU
2970 * of the package to read the packages energy counter
2971 */
2972 if (thd_stat[j].pkg_id == i) {
2973 pkg_stat[i].e_start =
2974 vmsr_read_msr(MSR_PKG_ENERGY_STATUS,
2975 thd_stat[j].cpu_id,
2976 thd_stat[j].thread_id,
2977 s->msr_energy.sioc);
2978 break;
2979 }
2980 }
2981 }
2982
2983 /* Sleep a short period while the other threads are working */
2984 usleep(MSR_ENERGY_THREAD_SLEEP_US);
2985
2986 /*
2987 * Retrieve all packages power plane energy counter
2988 * Calculate the delta of all packages
2989 */
2990 for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
2991 for (int j = 0; j < num_threads; j++) {
2992 /*
2993 * Use the first thread we found that ran on the CPU
2994 * of the package to read the packages energy counter
2995 */
2996 if (thd_stat[j].pkg_id == i) {
2997 pkg_stat[i].e_end =
2998 vmsr_read_msr(MSR_PKG_ENERGY_STATUS,
2999 thd_stat[j].cpu_id,
3000 thd_stat[j].thread_id,
3001 s->msr_energy.sioc);
3002 /*
3003 * Prevent the case we have migrate the VM
3004 * during the sleep period or any other cases
3005 * were energy counter might be lower after
3006 * the sleep period.
3007 */
3008 if (pkg_stat[i].e_end > pkg_stat[i].e_start) {
3009 pkg_stat[i].e_delta =
3010 pkg_stat[i].e_end - pkg_stat[i].e_start;
3011 } else {
3012 pkg_stat[i].e_delta = 0;
3013 }
3014 break;
3015 }
3016 }
3017 }
3018
3019 /* Delta of ticks spend by each thread between the sample */
3020 for (int i = 0; i < num_threads; i++) {
3021 vmsr_read_thread_stat(vmsr->pid,
3022 thd_stat[i].thread_id,
3023 &thd_stat[i].utime[1],
3024 &thd_stat[i].stime[1],
3025 &thd_stat[i].cpu_id);
3026
3027 if (vmsr->pid < 0) {
3028 /*
3029 * We don't count the dead thread
3030 * i.e threads that existed before the sleep
3031 * and not anymore
3032 */
3033 thd_stat[i].delta_ticks = 0;
3034 } else {
3035 vmsr_delta_ticks(thd_stat, i);
3036 }
3037 }
3038
3039 /*
3040 * Identify the vcpu threads
3041 * Calculate the number of vcpu per package
3042 */
3043 CPU_FOREACH(cpu) {
3044 for (int i = 0; i < num_threads; i++) {
3045 if (cpu->thread_id == thd_stat[i].thread_id) {
3046 thd_stat[i].is_vcpu = true;
3047 thd_stat[i].vcpu_id = cpu->cpu_index;
3048 pkg_stat[thd_stat[i].pkg_id].nb_vcpu++;
3049 thd_stat[i].acpi_id = kvm_arch_vcpu_id(cpu);
3050 break;
3051 }
3052 }
3053 }
3054
3055 /* Retrieve the virtual package number of each vCPU */
3056 for (int i = 0; i < vmsr->guest_cpu_list->len; i++) {
3057 for (int j = 0; j < num_threads; j++) {
3058 if ((thd_stat[j].acpi_id ==
3059 vmsr->guest_cpu_list->cpus[i].arch_id)
3060 && (thd_stat[j].is_vcpu == true)) {
3061 x86_topo_ids_from_apicid(thd_stat[j].acpi_id,
3062 &vmsr->guest_topo_info, &topo_ids);
3063 thd_stat[j].vpkg_id = topo_ids.pkg_id;
3064 }
3065 }
3066 }
3067
3068 /* Calculate the total energy of all non-vCPU thread */
3069 for (int i = 0; i < num_threads; i++) {
3070 if ((thd_stat[i].is_vcpu != true) &&
3071 (thd_stat[i].delta_ticks > 0)) {
3072 double temp;
3073 temp = vmsr_get_ratio(pkg_stat[thd_stat[i].pkg_id].e_delta,
3074 thd_stat[i].delta_ticks,
3075 vmsr->host_topo.maxticks[thd_stat[i].pkg_id]);
3076 pkg_stat[thd_stat[i].pkg_id].e_ratio
3077 += (uint64_t)lround(temp);
3078 }
3079 }
3080
3081 /* Calculate the ratio per non-vCPU thread of each package */
3082 for (int i = 0; i < vmsr->host_topo.maxpkgs; i++) {
3083 if (pkg_stat[i].nb_vcpu > 0) {
3084 pkg_stat[i].e_ratio = pkg_stat[i].e_ratio / pkg_stat[i].nb_vcpu;
3085 }
3086 }
3087
3088 /*
3089 * Calculate the energy for each Package:
3090 * Energy Package = sum of each vCPU energy that belongs to the package
3091 */
3092 for (int i = 0; i < num_threads; i++) {
3093 if ((thd_stat[i].is_vcpu == true) && \
3094 (thd_stat[i].delta_ticks > 0)) {
3095 double temp;
3096 temp = vmsr_get_ratio(pkg_stat[thd_stat[i].pkg_id].e_delta,
3097 thd_stat[i].delta_ticks,
3098 vmsr->host_topo.maxticks[thd_stat[i].pkg_id]);
3099 vpkgs_energy_stat[thd_stat[i].vpkg_id] +=
3100 (uint64_t)lround(temp);
3101 vpkgs_energy_stat[thd_stat[i].vpkg_id] +=
3102 pkg_stat[thd_stat[i].pkg_id].e_ratio;
3103 }
3104 }
3105
3106 /*
3107 * Finally populate the vmsr register of each vCPU with the total
3108 * package value to emulate the real hardware where each CPU return the
3109 * value of the package it belongs.
3110 */
3111 for (int i = 0; i < num_threads; i++) {
3112 if ((thd_stat[i].is_vcpu == true) && \
3113 (thd_stat[i].delta_ticks > 0)) {
3114 vmsr->msr_value[thd_stat[i].vcpu_id] = \
3115 vpkgs_energy_stat[thd_stat[i].vpkg_id];
3116 }
3117 }
3118
3119 /* Freeing memory before zeroing the pointer */
3120 for (int i = 0; i < num_threads; i++) {
3121 g_free(thd_stat[i].utime);
3122 g_free(thd_stat[i].stime);
3123 }
3124 }
3125
3126 clean:
3127 rcu_unregister_thread();
3128 return NULL;
3129 }
3130
3131 static int kvm_msr_energy_thread_init(KVMState *s, MachineState *ms)
3132 {
3133 MachineClass *mc = MACHINE_GET_CLASS(ms);
3134 struct KVMMsrEnergy *r = &s->msr_energy;
3135
3136 /*
3137 * Sanity check
3138 * 1. Host cpu must be Intel cpu
3139 * 2. RAPL must be enabled on the Host
3140 */
3141 if (!is_host_cpu_intel()) {
3142 error_report("The RAPL feature can only be enabled on hosts "
3143 "with Intel CPU models");
3144 return -1;
3145 }
3146
3147 if (!is_rapl_enabled()) {
3148 return -1;
3149 }
3150
3151 /* Retrieve the virtual topology */
3152 vmsr_init_topo_info(&r->guest_topo_info, ms);
3153
3154 /* Retrieve the number of vcpu */
3155 r->guest_vcpus = ms->smp.cpus;
3156
3157 /* Retrieve the number of virtual sockets */
3158 r->guest_vsockets = ms->smp.sockets;
3159
3160 /* Allocate register memory (MSR_PKG_STATUS) for each vcpu */
3161 r->msr_value = g_new0(uint64_t, r->guest_vcpus);
3162
3163 /* Retrieve the CPUArchIDlist */
3164 r->guest_cpu_list = mc->possible_cpu_arch_ids(ms);
3165
3166 /* Max number of cpus on the Host */
3167 r->host_topo.maxcpus = vmsr_get_maxcpus();
3168 if (r->host_topo.maxcpus == 0) {
3169 error_report("host max cpus = 0");
3170 return -1;
3171 }
3172
3173 /* Max number of packages on the host */
3174 r->host_topo.maxpkgs = vmsr_get_max_physical_package(r->host_topo.maxcpus);
3175 if (r->host_topo.maxpkgs == 0) {
3176 error_report("host max pkgs = 0");
3177 return -1;
3178 }
3179
3180 /* Allocate memory for each package on the host */
3181 r->host_topo.pkg_cpu_count = g_new0(unsigned int, r->host_topo.maxpkgs);
3182 r->host_topo.maxticks = g_new0(unsigned int, r->host_topo.maxpkgs);
3183
3184 vmsr_count_cpus_per_package(r->host_topo.pkg_cpu_count,
3185 r->host_topo.maxpkgs);
3186 for (int i = 0; i < r->host_topo.maxpkgs; i++) {
3187 if (r->host_topo.pkg_cpu_count[i] == 0) {
3188 error_report("cpu per packages = 0 on package_%d", i);
3189 return -1;
3190 }
3191 }
3192
3193 /* Get QEMU PID*/
3194 r->pid = getpid();
3195
3196 /* Compute the socket path if necessary */
3197 if (s->msr_energy.socket_path == NULL) {
3198 s->msr_energy.socket_path = vmsr_compute_default_paths();
3199 }
3200
3201 /* Open socket with vmsr helper */
3202 s->msr_energy.sioc = vmsr_open_socket(s->msr_energy.socket_path);
3203
3204 if (s->msr_energy.sioc == NULL) {
3205 error_report("vmsr socket opening failed");
3206 return -1;
3207 }
3208
3209 /* Those MSR values should not change */
3210 r->msr_unit = vmsr_read_msr(MSR_RAPL_POWER_UNIT, 0, r->pid,
3211 s->msr_energy.sioc);
3212 r->msr_limit = vmsr_read_msr(MSR_PKG_POWER_LIMIT, 0, r->pid,
3213 s->msr_energy.sioc);
3214 r->msr_info = vmsr_read_msr(MSR_PKG_POWER_INFO, 0, r->pid,
3215 s->msr_energy.sioc);
3216 if (r->msr_unit == 0 || r->msr_limit == 0 || r->msr_info == 0) {
3217 error_report("can't read any virtual msr");
3218 return -1;
3219 }
3220
3221 qemu_thread_create(&r->msr_thr, "kvm-msr",
3222 kvm_msr_energy_thread,
3223 s, QEMU_THREAD_JOINABLE);
3224 return 0;
3225 }
3226
3227 int kvm_arch_get_default_type(MachineState *ms)
3228 {
3229 return 0;
3230 }
3231
3232 static int kvm_vm_enable_exception_payload(KVMState *s)
3233 {
3234 int ret = 0;
3235 has_exception_payload = kvm_check_extension(s, KVM_CAP_EXCEPTION_PAYLOAD);
3236 if (has_exception_payload) {
3237 ret = kvm_vm_enable_cap(s, KVM_CAP_EXCEPTION_PAYLOAD, 0, true);
3238 if (ret < 0) {
3239 error_report("kvm: Failed to enable exception payload cap: %s",
3240 strerror(-ret));
3241 }
3242 }
3243
3244 return ret;
3245 }
3246
3247 static int kvm_vm_enable_triple_fault_event(KVMState *s)
3248 {
3249 int ret = 0;
3250 has_triple_fault_event = \
3251 kvm_check_extension(s,
3252 KVM_CAP_X86_TRIPLE_FAULT_EVENT);
3253 if (has_triple_fault_event) {
3254 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_TRIPLE_FAULT_EVENT, 0, true);
3255 if (ret < 0) {
3256 error_report("kvm: Failed to enable triple fault event cap: %s",
3257 strerror(-ret));
3258 }
3259 }
3260 return ret;
3261 }
3262
3263 static int kvm_vm_set_identity_map_addr(KVMState *s, uint64_t identity_base)
3264 {
3265 return kvm_vm_ioctl(s, KVM_SET_IDENTITY_MAP_ADDR, &identity_base);
3266 }
3267
3268 static int kvm_vm_set_nr_mmu_pages(KVMState *s)
3269 {
3270 uint64_t shadow_mem;
3271 int ret = 0;
3272 shadow_mem = object_property_get_int(OBJECT(s),
3273 "kvm-shadow-mem",
3274 &error_abort);
3275 if (shadow_mem != -1) {
3276 shadow_mem /= 4096;
3277 ret = kvm_vm_ioctl(s, KVM_SET_NR_MMU_PAGES, shadow_mem);
3278 }
3279 return ret;
3280 }
3281
3282 static int kvm_vm_set_tss_addr(KVMState *s, uint64_t tss_base)
3283 {
3284 return kvm_vm_ioctl(s, KVM_SET_TSS_ADDR, tss_base);
3285 }
3286
3287 static int kvm_vm_enable_disable_exits(KVMState *s)
3288 {
3289 int disable_exits = kvm_check_extension(s, KVM_CAP_X86_DISABLE_EXITS);
3290
3291 if (disable_exits) {
3292 disable_exits &= (KVM_X86_DISABLE_EXITS_MWAIT |
3293 KVM_X86_DISABLE_EXITS_HLT |
3294 KVM_X86_DISABLE_EXITS_PAUSE |
3295 KVM_X86_DISABLE_EXITS_CSTATE);
3296 }
3297
3298 return kvm_vm_enable_cap(s, KVM_CAP_X86_DISABLE_EXITS, 0,
3299 disable_exits);
3300 }
3301
3302 static int kvm_vm_enable_bus_lock_exit(KVMState *s)
3303 {
3304 int ret = 0;
3305 ret = kvm_check_extension(s, KVM_CAP_X86_BUS_LOCK_EXIT);
3306 if (!(ret & KVM_BUS_LOCK_DETECTION_EXIT)) {
3307 error_report("kvm: bus lock detection unsupported");
3308 return -ENOTSUP;
3309 }
3310 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_BUS_LOCK_EXIT, 0,
3311 KVM_BUS_LOCK_DETECTION_EXIT);
3312 if (ret < 0) {
3313 error_report("kvm: Failed to enable bus lock detection cap: %s",
3314 strerror(-ret));
3315 }
3316
3317 return ret;
3318 }
3319
3320 static int kvm_vm_enable_notify_vmexit(KVMState *s)
3321 {
3322 int ret = 0;
3323 if (s->notify_vmexit != NOTIFY_VMEXIT_OPTION_DISABLE) {
3324 uint64_t notify_window_flags =
3325 ((uint64_t)s->notify_window << 32) |
3326 KVM_X86_NOTIFY_VMEXIT_ENABLED |
3327 KVM_X86_NOTIFY_VMEXIT_USER;
3328 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_NOTIFY_VMEXIT, 0,
3329 notify_window_flags);
3330 if (ret < 0) {
3331 error_report("kvm: Failed to enable notify vmexit cap: %s",
3332 strerror(-ret));
3333 }
3334 }
3335 return ret;
3336 }
3337
3338 static int kvm_vm_enable_userspace_msr(KVMState *s)
3339 {
3340 int ret;
3341
3342 ret = kvm_vm_enable_cap(s, KVM_CAP_X86_USER_SPACE_MSR, 0,
3343 KVM_MSR_EXIT_REASON_FILTER);
3344 if (ret < 0) {
3345 error_report("Could not enable user space MSRs: %s",
3346 strerror(-ret));
3347 exit(1);
3348 }
3349
3350 ret = kvm_filter_msr(s, MSR_CORE_THREAD_COUNT,
3351 kvm_rdmsr_core_thread_count, NULL);
3352 if (ret < 0) {
3353 error_report("Could not install MSR_CORE_THREAD_COUNT handler: %s",
3354 strerror(-ret));
3355 exit(1);
3356 }
3357
3358 return 0;
3359 }
3360
3361 static int kvm_vm_enable_energy_msrs(KVMState *s)
3362 {
3363 int ret;
3364
3365 if (s->msr_energy.enable == true) {
3366 ret = kvm_filter_msr(s, MSR_RAPL_POWER_UNIT,
3367 kvm_rdmsr_rapl_power_unit, NULL);
3368 if (ret < 0) {
3369 error_report("Could not install MSR_RAPL_POWER_UNIT handler: %s",
3370 strerror(-ret));
3371 return ret;
3372 }
3373
3374 ret = kvm_filter_msr(s, MSR_PKG_POWER_LIMIT,
3375 kvm_rdmsr_pkg_power_limit, NULL);
3376 if (ret < 0) {
3377 error_report("Could not install MSR_PKG_POWER_LIMIT handler: %s",
3378 strerror(-ret));
3379 return ret;
3380 }
3381
3382 ret = kvm_filter_msr(s, MSR_PKG_POWER_INFO,
3383 kvm_rdmsr_pkg_power_info, NULL);
3384 if (ret < 0) {
3385 error_report("Could not install MSR_PKG_POWER_INFO handler: %s",
3386 strerror(-ret));
3387 return ret;
3388 }
3389 ret = kvm_filter_msr(s, MSR_PKG_ENERGY_STATUS,
3390 kvm_rdmsr_pkg_energy_status, NULL);
3391 if (ret < 0) {
3392 error_report("Could not install MSR_PKG_ENERGY_STATUS handler: %s",
3393 strerror(-ret));
3394 return ret;
3395 }
3396 }
3397 return 0;
3398 }
3399
3400 int kvm_arch_on_vmfd_change(MachineState *ms, KVMState *s)
3401 {
3402 int ret;
3403
3404 ret = kvm_arch_init(ms, s);
3405 if (ret < 0) {
3406 return ret;
3407 }
3408
3409 if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
3410 X86MachineState *x86ms = X86_MACHINE(ms);
3411 /*
3412 * For confidential guests, reload bios ROM if IGVM is not specified.
3413 * If an IGVM file is specified then the firmware must be provided
3414 * in the IGVM file.
3415 */
3416 if (ms->cgs && !x86ms->igvm) {
3417 x86_bios_rom_reload(x86ms);
3418 }
3419 if (x86_machine_is_smm_enabled(x86ms)) {
3420 memory_listener_register(&smram_listener.listener,
3421 &smram_address_space);
3422 }
3423 kvm_set_max_apic_id(x86ms->apic_id_limit);
3424 }
3425
3426 trace_kvm_arch_on_vmfd_change();
3427 return 0;
3428 }
3429
3430 bool kvm_arch_supports_vmfd_change(void)
3431 {
3432 return true;
3433 }
3434
3435 static int xen_init(MachineState *ms, KVMState *s)
3436 {
3437 #ifdef CONFIG_XEN_EMU
3438 int ret = 0;
3439 if (!object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE)) {
3440 error_report("kvm: Xen support only available in PC machine");
3441 return -ENOTSUP;
3442 }
3443 /* hyperv_enabled() doesn't work yet. */
3444 uint32_t msr = XEN_HYPERCALL_MSR;
3445 ret = kvm_xen_init(s, msr);
3446 return ret;
3447 #else
3448 error_report("kvm: Xen support not enabled in qemu");
3449 return -ENOTSUP;
3450 #endif
3451 }
3452
3453 int kvm_arch_init(MachineState *ms, KVMState *s)
3454 {
3455 int ret;
3456 struct utsname utsname;
3457 Error *local_err = NULL;
3458 static bool first = true;
3459
3460 /*
3461 * Initialize confidential guest (SEV/TDX) context, if required
3462 */
3463 if (ms->cgs) {
3464 ret = confidential_guest_kvm_init(ms->cgs, &local_err);
3465 if (ret < 0) {
3466 error_report_err(local_err);
3467 return ret;
3468 }
3469 }
3470
3471 has_xcrs = kvm_check_extension(s, KVM_CAP_XCRS);
3472 has_sregs2 = kvm_check_extension(s, KVM_CAP_SREGS2) > 0;
3473
3474 hv_vpindex_settable = kvm_check_extension(s, KVM_CAP_HYPERV_VP_INDEX);
3475
3476 ret = kvm_vm_enable_exception_payload(s);
3477 if (ret < 0) {
3478 return ret;
3479 }
3480
3481 ret = kvm_vm_enable_triple_fault_event(s);
3482 if (ret < 0) {
3483 return ret;
3484 }
3485
3486 if (s->xen_version) {
3487 ret = xen_init(ms, s);
3488 if (ret < 0) {
3489 return ret;
3490 }
3491 }
3492
3493 ret = kvm_get_supported_msrs(s);
3494 if (ret < 0) {
3495 return ret;
3496 }
3497
3498 ret = kvm_get_supported_feature_msrs(s);
3499 if (ret < 0) {
3500 return ret;
3501 }
3502
3503 uname(&utsname);
3504 lm_capable_kernel = strcmp(utsname.machine, "x86_64") == 0;
3505
3506 ret = kvm_vm_set_identity_map_addr(s, KVM_IDENTITY_BASE);
3507 if (ret < 0) {
3508 return ret;
3509 }
3510
3511 /* Set TSS base one page after EPT identity map. */
3512 ret = kvm_vm_set_tss_addr(s, KVM_IDENTITY_BASE + 0x1000);
3513 if (ret < 0) {
3514 return ret;
3515 }
3516
3517 if (first) {
3518 /* Tell fw_cfg to notify the BIOS to reserve the range. */
3519 e820_add_entry(KVM_IDENTITY_BASE, 0x4000, E820_RESERVED);
3520 }
3521 ret = kvm_vm_set_nr_mmu_pages(s);
3522 if (ret < 0) {
3523 return ret;
3524 }
3525
3526 if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE) &&
3527 x86_machine_is_smm_enabled(X86_MACHINE(ms)) && first) {
3528 smram_machine_done.notify = register_smram_listener;
3529 qemu_add_machine_init_done_notifier(&smram_machine_done);
3530 }
3531
3532 if (enable_cpu_pm) {
3533 ret = kvm_vm_enable_disable_exits(s);
3534 if (ret < 0) {
3535 error_report("kvm: guest stopping CPU not supported: %s",
3536 strerror(-ret));
3537 return ret;
3538 }
3539 }
3540
3541 if (object_dynamic_cast(OBJECT(ms), TYPE_X86_MACHINE)) {
3542 X86MachineState *x86ms = X86_MACHINE(ms);
3543
3544 if (x86ms->bus_lock_ratelimit > 0) {
3545 ret = kvm_vm_enable_bus_lock_exit(s);
3546 if (ret < 0) {
3547 return ret;
3548 }
3549 ratelimit_init(&bus_lock_ratelimit_ctrl);
3550 ratelimit_set_speed(&bus_lock_ratelimit_ctrl,
3551 x86ms->bus_lock_ratelimit, BUS_LOCK_SLICE_TIME);
3552 }
3553 }
3554
3555 if (kvm_check_extension(s, KVM_CAP_X86_NOTIFY_VMEXIT)) {
3556 ret = kvm_vm_enable_notify_vmexit(s);
3557 if (ret < 0) {
3558 return ret;
3559 }
3560 }
3561
3562 if (kvm_vm_check_extension(s, KVM_CAP_X86_USER_SPACE_MSR)) {
3563 ret = kvm_vm_enable_userspace_msr(s);
3564 if (ret < 0) {
3565 return ret;
3566 }
3567
3568 if (s->msr_energy.enable == true) {
3569 ret = kvm_vm_enable_energy_msrs(s);
3570 if (ret < 0) {
3571 return ret;
3572 }
3573
3574 if (first) {
3575 ret = kvm_msr_energy_thread_init(s, ms);
3576 if (ret < 0) {
3577 error_report("kvm : "
3578 "error RAPL feature requirement not met");
3579 return ret;
3580 }
3581 }
3582 }
3583 }
3584
3585 pmu_cap = kvm_check_extension(s, KVM_CAP_PMU_CAPABILITY);
3586
3587 if (first) {
3588 kvm_vmfd_add_change_notifier(&kvm_vmfd_change_notifier);
3589 }
3590
3591 /*
3592 * Most x86 CPUs in current use have self-snoop, so honoring guest PAT is
3593 * preferable. As well, the bochs video driver bug which motivated making
3594 * this a default-enabled quirk in KVM was fixed long ago.
3595 */
3596 if (s->honor_guest_pat != ON_OFF_AUTO_OFF) {
3597 ret = kvm_check_extension(s, KVM_CAP_DISABLE_QUIRKS2);
3598 if (ret & KVM_X86_QUIRK_IGNORE_GUEST_PAT) {
3599 ret = kvm_vm_enable_cap(s, KVM_CAP_DISABLE_QUIRKS2, 0,
3600 KVM_X86_QUIRK_IGNORE_GUEST_PAT);
3601 if (ret < 0) {
3602 error_report("failed to disable KVM_X86_QUIRK_IGNORE_GUEST_PAT");
3603 return ret;
3604 }
3605 } else {
3606 if (s->honor_guest_pat == ON_OFF_AUTO_ON) {
3607 error_report("KVM does not support disabling ignore-guest-PAT quirk");
3608 return -EINVAL;
3609 }
3610 }
3611 }
3612
3613 first = false;
3614 return 0;
3615 }
3616
3617 static void set_v8086_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
3618 {
3619 lhs->selector = rhs->selector;
3620 lhs->base = rhs->base;
3621 lhs->limit = rhs->limit;
3622 lhs->type = 3;
3623 lhs->present = 1;
3624 lhs->dpl = 3;
3625 lhs->db = 0;
3626 lhs->s = 1;
3627 lhs->l = 0;
3628 lhs->g = 0;
3629 lhs->avl = 0;
3630 lhs->unusable = 0;
3631 }
3632
3633 static void set_seg(struct kvm_segment *lhs, const SegmentCache *rhs)
3634 {
3635 unsigned flags = rhs->flags;
3636 lhs->selector = rhs->selector;
3637 lhs->base = rhs->base;
3638 lhs->limit = rhs->limit;
3639 lhs->type = (flags >> DESC_TYPE_SHIFT) & 15;
3640 lhs->present = (flags & DESC_P_MASK) != 0;
3641 lhs->dpl = (flags >> DESC_DPL_SHIFT) & 3;
3642 lhs->db = (flags >> DESC_B_SHIFT) & 1;
3643 lhs->s = (flags & DESC_S_MASK) != 0;
3644 lhs->l = (flags >> DESC_L_SHIFT) & 1;
3645 lhs->g = (flags & DESC_G_MASK) != 0;
3646 lhs->avl = (flags & DESC_AVL_MASK) != 0;
3647 lhs->unusable = !lhs->present;
3648 lhs->padding = 0;
3649 }
3650
3651 static void get_seg(SegmentCache *lhs, const struct kvm_segment *rhs)
3652 {
3653 lhs->selector = rhs->selector;
3654 lhs->base = rhs->base;
3655 lhs->limit = rhs->limit;
3656 lhs->flags = (rhs->type << DESC_TYPE_SHIFT) |
3657 ((rhs->present && !rhs->unusable) * DESC_P_MASK) |
3658 (rhs->dpl << DESC_DPL_SHIFT) |
3659 (rhs->db << DESC_B_SHIFT) |
3660 (rhs->s * DESC_S_MASK) |
3661 (rhs->l << DESC_L_SHIFT) |
3662 (rhs->g * DESC_G_MASK) |
3663 (rhs->avl * DESC_AVL_MASK);
3664 }
3665
3666 static void kvm_getput_reg(__u64 *kvm_reg, target_ulong *qemu_reg, int set)
3667 {
3668 if (set) {
3669 *kvm_reg = *qemu_reg;
3670 } else {
3671 *qemu_reg = *kvm_reg;
3672 }
3673 }
3674
3675 static int kvm_getput_regs(X86CPU *cpu, int set)
3676 {
3677 CPUX86State *env = &cpu->env;
3678 struct kvm_regs regs;
3679 int ret = 0;
3680
3681 if (!set) {
3682 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_REGS, &regs);
3683 if (ret < 0) {
3684 return ret;
3685 }
3686 }
3687
3688 kvm_getput_reg(&regs.rax, &env->regs[R_EAX], set);
3689 kvm_getput_reg(&regs.rbx, &env->regs[R_EBX], set);
3690 kvm_getput_reg(&regs.rcx, &env->regs[R_ECX], set);
3691 kvm_getput_reg(&regs.rdx, &env->regs[R_EDX], set);
3692 kvm_getput_reg(&regs.rsi, &env->regs[R_ESI], set);
3693 kvm_getput_reg(&regs.rdi, &env->regs[R_EDI], set);
3694 kvm_getput_reg(&regs.rsp, &env->regs[R_ESP], set);
3695 kvm_getput_reg(&regs.rbp, &env->regs[R_EBP], set);
3696 #ifdef TARGET_X86_64
3697 kvm_getput_reg(&regs.r8, &env->regs[8], set);
3698 kvm_getput_reg(&regs.r9, &env->regs[9], set);
3699 kvm_getput_reg(&regs.r10, &env->regs[10], set);
3700 kvm_getput_reg(&regs.r11, &env->regs[11], set);
3701 kvm_getput_reg(&regs.r12, &env->regs[12], set);
3702 kvm_getput_reg(&regs.r13, &env->regs[13], set);
3703 kvm_getput_reg(&regs.r14, &env->regs[14], set);
3704 kvm_getput_reg(&regs.r15, &env->regs[15], set);
3705 #endif
3706
3707 kvm_getput_reg(&regs.rflags, &env->eflags, set);
3708 kvm_getput_reg(&regs.rip, &env->eip, set);
3709
3710 if (set) {
3711 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_REGS, &regs);
3712 }
3713
3714 return ret;
3715 }
3716
3717 static int kvm_put_xsave(X86CPU *cpu)
3718 {
3719 CPUX86State *env = &cpu->env;
3720 void *xsave = env->xsave_buf;
3721
3722 x86_cpu_xsave_all_areas(cpu, xsave, env->xsave_buf_len);
3723
3724 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XSAVE, xsave);
3725 }
3726
3727 static int kvm_put_xcrs(X86CPU *cpu)
3728 {
3729 CPUX86State *env = &cpu->env;
3730 struct kvm_xcrs xcrs = {};
3731
3732 if (!has_xcrs) {
3733 return 0;
3734 }
3735
3736 xcrs.nr_xcrs = 1;
3737 xcrs.flags = 0;
3738 xcrs.xcrs[0].xcr = 0;
3739 xcrs.xcrs[0].value = env->xcr0;
3740 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);
3741 }
3742
3743 static int kvm_put_sregs(X86CPU *cpu)
3744 {
3745 CPUX86State *env = &cpu->env;
3746 struct kvm_sregs sregs;
3747
3748 /*
3749 * The interrupt_bitmap is ignored because KVM_SET_SREGS is
3750 * always followed by KVM_SET_VCPU_EVENTS.
3751 */
3752 memset(sregs.interrupt_bitmap, 0, sizeof(sregs.interrupt_bitmap));
3753
3754 if ((env->eflags & VM_MASK)) {
3755 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
3756 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
3757 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
3758 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
3759 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
3760 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
3761 } else {
3762 set_seg(&sregs.cs, &env->segs[R_CS]);
3763 set_seg(&sregs.ds, &env->segs[R_DS]);
3764 set_seg(&sregs.es, &env->segs[R_ES]);
3765 set_seg(&sregs.fs, &env->segs[R_FS]);
3766 set_seg(&sregs.gs, &env->segs[R_GS]);
3767 set_seg(&sregs.ss, &env->segs[R_SS]);
3768 }
3769
3770 set_seg(&sregs.tr, &env->tr);
3771 set_seg(&sregs.ldt, &env->ldt);
3772
3773 sregs.idt.limit = env->idt.limit;
3774 sregs.idt.base = env->idt.base;
3775 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
3776 sregs.gdt.limit = env->gdt.limit;
3777 sregs.gdt.base = env->gdt.base;
3778 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
3779
3780 sregs.cr0 = env->cr[0];
3781 sregs.cr2 = env->cr[2];
3782 sregs.cr3 = env->cr[3];
3783 sregs.cr4 = env->cr[4];
3784
3785 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
3786 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
3787
3788 sregs.efer = env->efer;
3789
3790 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);
3791 }
3792
3793 static int kvm_put_sregs2(X86CPU *cpu)
3794 {
3795 CPUX86State *env = &cpu->env;
3796 struct kvm_sregs2 sregs;
3797 int i;
3798
3799 sregs.flags = 0;
3800
3801 if ((env->eflags & VM_MASK)) {
3802 set_v8086_seg(&sregs.cs, &env->segs[R_CS]);
3803 set_v8086_seg(&sregs.ds, &env->segs[R_DS]);
3804 set_v8086_seg(&sregs.es, &env->segs[R_ES]);
3805 set_v8086_seg(&sregs.fs, &env->segs[R_FS]);
3806 set_v8086_seg(&sregs.gs, &env->segs[R_GS]);
3807 set_v8086_seg(&sregs.ss, &env->segs[R_SS]);
3808 } else {
3809 set_seg(&sregs.cs, &env->segs[R_CS]);
3810 set_seg(&sregs.ds, &env->segs[R_DS]);
3811 set_seg(&sregs.es, &env->segs[R_ES]);
3812 set_seg(&sregs.fs, &env->segs[R_FS]);
3813 set_seg(&sregs.gs, &env->segs[R_GS]);
3814 set_seg(&sregs.ss, &env->segs[R_SS]);
3815 }
3816
3817 set_seg(&sregs.tr, &env->tr);
3818 set_seg(&sregs.ldt, &env->ldt);
3819
3820 sregs.idt.limit = env->idt.limit;
3821 sregs.idt.base = env->idt.base;
3822 memset(sregs.idt.padding, 0, sizeof sregs.idt.padding);
3823 sregs.gdt.limit = env->gdt.limit;
3824 sregs.gdt.base = env->gdt.base;
3825 memset(sregs.gdt.padding, 0, sizeof sregs.gdt.padding);
3826
3827 sregs.cr0 = env->cr[0];
3828 sregs.cr2 = env->cr[2];
3829 sregs.cr3 = env->cr[3];
3830 sregs.cr4 = env->cr[4];
3831
3832 sregs.cr8 = cpu_get_apic_tpr(cpu->apic_state);
3833 sregs.apic_base = cpu_get_apic_base(cpu->apic_state);
3834
3835 sregs.efer = env->efer;
3836
3837 if (env->pdptrs_valid) {
3838 for (i = 0; i < 4; i++) {
3839 sregs.pdptrs[i] = env->pdptrs[i];
3840 }
3841 sregs.flags |= KVM_SREGS2_FLAGS_PDPTRS_VALID;
3842 }
3843
3844 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS2, &sregs);
3845 }
3846
3847
3848 static void kvm_msr_buf_reset(X86CPU *cpu)
3849 {
3850 memset(cpu->kvm_msr_buf, 0, MSR_BUF_SIZE);
3851 }
3852
3853 static void kvm_msr_entry_add(X86CPU *cpu, uint32_t index, uint64_t value)
3854 {
3855 struct kvm_msrs *msrs = cpu->kvm_msr_buf;
3856 void *limit = ((void *)msrs) + MSR_BUF_SIZE;
3857 struct kvm_msr_entry *entry = &msrs->entries[msrs->nmsrs];
3858
3859 assert((void *)(entry + 1) <= limit);
3860
3861 entry->index = index;
3862 entry->reserved = 0;
3863 entry->data = value;
3864 msrs->nmsrs++;
3865 }
3866
3867 static int kvm_put_one_msr(X86CPU *cpu, int index, uint64_t value)
3868 {
3869 kvm_msr_buf_reset(cpu);
3870 kvm_msr_entry_add(cpu, index, value);
3871
3872 return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
3873 }
3874
3875 static int kvm_get_one_msr(X86CPU *cpu, int index, uint64_t *value)
3876 {
3877 int ret;
3878 struct {
3879 struct kvm_msrs info;
3880 struct kvm_msr_entry entries[1];
3881 } msr_data = {
3882 .info.nmsrs = 1,
3883 .entries[0].index = index,
3884 };
3885
3886 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, &msr_data);
3887 if (ret < 0) {
3888 return ret;
3889 }
3890 assert(ret == 1);
3891 *value = msr_data.entries[0].data;
3892 return ret;
3893 }
3894 void kvm_put_apicbase(X86CPU *cpu, uint64_t value)
3895 {
3896 int ret;
3897
3898 ret = kvm_put_one_msr(cpu, MSR_IA32_APICBASE, value);
3899 assert(ret == 1);
3900 }
3901
3902 static int kvm_put_tscdeadline_msr(X86CPU *cpu)
3903 {
3904 CPUX86State *env = &cpu->env;
3905 int ret;
3906
3907 if (!has_msr_tsc_deadline) {
3908 return 0;
3909 }
3910
3911 ret = kvm_put_one_msr(cpu, MSR_IA32_TSCDEADLINE, env->tsc_deadline);
3912 if (ret < 0) {
3913 return ret;
3914 }
3915
3916 assert(ret == 1);
3917 return 0;
3918 }
3919
3920 /*
3921 * Provide a separate write service for the feature control MSR in order to
3922 * kick the VCPU out of VMXON or even guest mode on reset. This has to be done
3923 * before writing any other state because forcibly leaving nested mode
3924 * invalidates the VCPU state.
3925 */
3926 static int kvm_put_msr_feature_control(X86CPU *cpu)
3927 {
3928 int ret;
3929
3930 if (!has_msr_feature_control) {
3931 return 0;
3932 }
3933
3934 ret = kvm_put_one_msr(cpu, MSR_IA32_FEATURE_CONTROL,
3935 cpu->env.msr_ia32_feature_control);
3936 if (ret < 0) {
3937 return ret;
3938 }
3939
3940 assert(ret == 1);
3941 return 0;
3942 }
3943
3944 static uint64_t make_vmx_msr_value(uint32_t index, uint32_t features)
3945 {
3946 uint32_t default1, can_be_one, can_be_zero;
3947 uint32_t must_be_one;
3948
3949 switch (index) {
3950 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3951 default1 = 0x00000016;
3952 break;
3953 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3954 default1 = 0x0401e172;
3955 break;
3956 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3957 default1 = 0x000011ff;
3958 break;
3959 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3960 default1 = 0x00036dff;
3961 break;
3962 case MSR_IA32_VMX_PROCBASED_CTLS2:
3963 default1 = 0;
3964 break;
3965 default:
3966 abort();
3967 }
3968
3969 /* If a feature bit is set, the control can be either set or clear.
3970 * Otherwise the value is limited to either 0 or 1 by default1.
3971 */
3972 can_be_one = features | default1;
3973 can_be_zero = features | ~default1;
3974 must_be_one = ~can_be_zero;
3975
3976 /*
3977 * Bit 0:31 -> 0 if the control bit can be zero (i.e. 1 if it must be one).
3978 * Bit 32:63 -> 1 if the control bit can be one.
3979 */
3980 return must_be_one | (((uint64_t)can_be_one) << 32);
3981 }
3982
3983 static void kvm_msr_entry_add_vmx(X86CPU *cpu, FeatureWordArray f)
3984 {
3985 uint64_t kvm_vmx_basic =
3986 kvm_arch_get_supported_msr_feature(kvm_state,
3987 MSR_IA32_VMX_BASIC);
3988
3989 if (!kvm_vmx_basic) {
3990 /* If the kernel doesn't support VMX feature (kvm_intel.nested=0),
3991 * then kvm_vmx_basic will be 0 and KVM_SET_MSR will fail.
3992 */
3993 return;
3994 }
3995
3996 uint64_t kvm_vmx_misc =
3997 kvm_arch_get_supported_msr_feature(kvm_state,
3998 MSR_IA32_VMX_MISC);
3999 uint64_t kvm_vmx_ept_vpid =
4000 kvm_arch_get_supported_msr_feature(kvm_state,
4001 MSR_IA32_VMX_EPT_VPID_CAP);
4002
4003 /*
4004 * If the guest is 64-bit, a value of 1 is allowed for the host address
4005 * space size vmexit control.
4006 */
4007 uint64_t fixed_vmx_exit = f[FEAT_8000_0001_EDX] & CPUID_EXT2_LM
4008 ? (uint64_t)VMX_VM_EXIT_HOST_ADDR_SPACE_SIZE << 32 : 0;
4009
4010 /*
4011 * Bits 0-30, 32-44 and 50-53 come from the host. KVM should
4012 * not change them for backwards compatibility.
4013 */
4014 uint64_t fixed_vmx_basic = kvm_vmx_basic &
4015 (MSR_VMX_BASIC_VMCS_REVISION_MASK |
4016 MSR_VMX_BASIC_VMXON_REGION_SIZE_MASK |
4017 MSR_VMX_BASIC_VMCS_MEM_TYPE_MASK);
4018
4019 /*
4020 * Same for bits 0-4 and 25-27. Bits 16-24 (CR3 target count) can
4021 * change in the future but are always zero for now, clear them to be
4022 * future proof. Bits 32-63 in theory could change, though KVM does
4023 * not support dual-monitor treatment and probably never will; mask
4024 * them out as well.
4025 */
4026 uint64_t fixed_vmx_misc = kvm_vmx_misc &
4027 (MSR_VMX_MISC_PREEMPTION_TIMER_SHIFT_MASK |
4028 MSR_VMX_MISC_MAX_MSR_LIST_SIZE_MASK);
4029
4030 /*
4031 * EPT memory types should not change either, so we do not bother
4032 * adding features for them.
4033 */
4034 uint64_t fixed_vmx_ept_mask =
4035 (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_ENABLE_EPT ?
4036 MSR_VMX_EPT_UC | MSR_VMX_EPT_WB : 0);
4037 uint64_t fixed_vmx_ept_vpid = kvm_vmx_ept_vpid & fixed_vmx_ept_mask;
4038
4039 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
4040 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
4041 f[FEAT_VMX_PROCBASED_CTLS]));
4042 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_PINBASED_CTLS,
4043 make_vmx_msr_value(MSR_IA32_VMX_TRUE_PINBASED_CTLS,
4044 f[FEAT_VMX_PINBASED_CTLS]));
4045 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_EXIT_CTLS,
4046 make_vmx_msr_value(MSR_IA32_VMX_TRUE_EXIT_CTLS,
4047 f[FEAT_VMX_EXIT_CTLS]) | fixed_vmx_exit);
4048 kvm_msr_entry_add(cpu, MSR_IA32_VMX_TRUE_ENTRY_CTLS,
4049 make_vmx_msr_value(MSR_IA32_VMX_TRUE_ENTRY_CTLS,
4050 f[FEAT_VMX_ENTRY_CTLS]));
4051 kvm_msr_entry_add(cpu, MSR_IA32_VMX_PROCBASED_CTLS2,
4052 make_vmx_msr_value(MSR_IA32_VMX_PROCBASED_CTLS2,
4053 f[FEAT_VMX_SECONDARY_CTLS]));
4054 kvm_msr_entry_add(cpu, MSR_IA32_VMX_EPT_VPID_CAP,
4055 f[FEAT_VMX_EPT_VPID_CAPS] | fixed_vmx_ept_vpid);
4056 kvm_msr_entry_add(cpu, MSR_IA32_VMX_BASIC,
4057 f[FEAT_VMX_BASIC] | fixed_vmx_basic);
4058 kvm_msr_entry_add(cpu, MSR_IA32_VMX_MISC,
4059 f[FEAT_VMX_MISC] | fixed_vmx_misc);
4060 if (has_msr_vmx_vmfunc) {
4061 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMFUNC, f[FEAT_VMX_VMFUNC]);
4062 }
4063
4064 /*
4065 * Just to be safe, write these with constant values. The CRn_FIXED1
4066 * MSRs are generated by KVM based on the vCPU's CPUID.
4067 */
4068 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR0_FIXED0,
4069 CR0_PE_MASK | CR0_PG_MASK | CR0_NE_MASK);
4070 kvm_msr_entry_add(cpu, MSR_IA32_VMX_CR4_FIXED0,
4071 CR4_VMXE_MASK);
4072
4073 if (f[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
4074 /* FRED injected-event data (0x2052). */
4075 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x52);
4076 } else if (f[FEAT_VMX_EXIT_CTLS] &
4077 VMX_VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) {
4078 /* Secondary VM-exit controls (0x2044). */
4079 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x44);
4080 } else if (f[FEAT_VMX_SECONDARY_CTLS] & VMX_SECONDARY_EXEC_TSC_SCALING) {
4081 /* TSC multiplier (0x2032). */
4082 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x32);
4083 } else {
4084 /* Preemption timer (0x482E). */
4085 kvm_msr_entry_add(cpu, MSR_IA32_VMX_VMCS_ENUM, 0x2E);
4086 }
4087 }
4088
4089 static void kvm_msr_entry_add_perf(X86CPU *cpu, FeatureWordArray f)
4090 {
4091 uint64_t kvm_perf_cap =
4092 kvm_arch_get_supported_msr_feature(kvm_state,
4093 MSR_IA32_PERF_CAPABILITIES);
4094
4095 if (kvm_perf_cap) {
4096 kvm_msr_entry_add(cpu, MSR_IA32_PERF_CAPABILITIES,
4097 kvm_perf_cap & f[FEAT_PERF_CAPABILITIES]);
4098 }
4099 }
4100
4101 static int kvm_buf_set_msrs(X86CPU *cpu)
4102 {
4103 int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, cpu->kvm_msr_buf);
4104 if (ret < 0) {
4105 return ret;
4106 }
4107
4108 if (ret < cpu->kvm_msr_buf->nmsrs) {
4109 struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];
4110 error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,
4111 (uint32_t)e->index, (uint64_t)e->data);
4112 }
4113
4114 assert(ret == cpu->kvm_msr_buf->nmsrs);
4115 return 0;
4116 }
4117
4118 static void kvm_init_msrs(X86CPU *cpu)
4119 {
4120 CPUX86State *env = &cpu->env;
4121
4122 kvm_msr_buf_reset(cpu);
4123
4124 if (!is_tdx_vm()) {
4125 if (has_msr_arch_capabs) {
4126 kvm_msr_entry_add(cpu, MSR_IA32_ARCH_CAPABILITIES,
4127 env->features[FEAT_ARCH_CAPABILITIES]);
4128 }
4129
4130 if (has_msr_core_capabs) {
4131 kvm_msr_entry_add(cpu, MSR_IA32_CORE_CAPABILITY,
4132 env->features[FEAT_CORE_CAPABILITY]);
4133 }
4134
4135 if (has_msr_perf_capabs && cpu->enable_pmu) {
4136 kvm_msr_entry_add_perf(cpu, env->features);
4137 }
4138
4139 /*
4140 * Older kernels do not include VMX MSRs in KVM_GET_MSR_INDEX_LIST, but
4141 * all kernels with MSR features should have them.
4142 */
4143 if (kvm_feature_msrs && cpu_has_vmx(env)) {
4144 kvm_msr_entry_add_vmx(cpu, env->features);
4145 }
4146 }
4147
4148 if (has_msr_ucode_rev) {
4149 kvm_msr_entry_add(cpu, MSR_IA32_UCODE_REV, cpu->ucode_rev);
4150 }
4151 assert(kvm_buf_set_msrs(cpu) == 0);
4152 }
4153
4154 static int kvm_put_msrs(X86CPU *cpu, KvmPutState level)
4155 {
4156 CPUX86State *env = &cpu->env;
4157 int i;
4158
4159 kvm_msr_buf_reset(cpu);
4160
4161 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);
4162 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);
4163 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);
4164 kvm_msr_entry_add(cpu, MSR_PAT, env->pat);
4165 if (has_msr_star) {
4166 kvm_msr_entry_add(cpu, MSR_STAR, env->star);
4167 }
4168 if (has_msr_hsave_pa) {
4169 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);
4170 }
4171 if (has_msr_tsc_aux) {
4172 kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);
4173 }
4174 if (has_msr_tsc_adjust) {
4175 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);
4176 }
4177 if (has_msr_misc_enable) {
4178 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,
4179 env->msr_ia32_misc_enable);
4180 }
4181 if (has_msr_smbase) {
4182 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);
4183 }
4184 if (has_msr_smi_count) {
4185 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, env->msr_smi_count);
4186 }
4187 if (has_msr_pkrs) {
4188 kvm_msr_entry_add(cpu, MSR_IA32_PKRS, env->pkrs);
4189 }
4190 if (has_msr_bndcfgs) {
4191 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);
4192 }
4193 if (has_msr_xss) {
4194 kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);
4195 }
4196 if (has_msr_umwait) {
4197 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, env->umwait);
4198 }
4199 if (has_msr_spec_ctrl) {
4200 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, env->spec_ctrl);
4201 }
4202 if (has_tsc_scale_msr) {
4203 kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, env->amd_tsc_scale_msr);
4204 }
4205
4206 if (has_msr_tsx_ctrl) {
4207 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, env->tsx_ctrl);
4208 }
4209 if (has_msr_virt_ssbd) {
4210 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, env->virt_ssbd);
4211 }
4212 if (has_msr_hwcr) {
4213 kvm_msr_entry_add(cpu, MSR_K7_HWCR, env->msr_hwcr);
4214 }
4215
4216 #ifdef TARGET_X86_64
4217 if (lm_capable_kernel) {
4218 kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);
4219 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);
4220 kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);
4221 kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);
4222 if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
4223 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, env->fred_rsp0);
4224 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, env->fred_rsp1);
4225 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, env->fred_rsp2);
4226 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, env->fred_rsp3);
4227 kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, env->fred_stklvls);
4228 kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, env->fred_ssp1);
4229 kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, env->fred_ssp2);
4230 kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, env->fred_ssp3);
4231 kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, env->fred_config);
4232
4233 if (!(env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_CET_SHSTK)) {
4234 /*
4235 * Aka MSR_IA32_FRED_SSP0. This MSR is accessible even if
4236 * CET shadow stack is not supported.
4237 */
4238 kvm_msr_entry_add(cpu, MSR_IA32_PL0_SSP, env->pl0_ssp);
4239 }
4240 }
4241 }
4242 #endif
4243
4244 /*
4245 * The following MSRs have side effects on the guest or are too heavy
4246 * for normal writeback. Limit them to reset or full state updates.
4247 */
4248 if (level >= KVM_PUT_RESET_STATE) {
4249 kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);
4250 if (env->features[FEAT_KVM] & (CPUID_KVM_CLOCK | CPUID_KVM_CLOCK2)) {
4251 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);
4252 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);
4253 }
4254 if (env->features[FEAT_KVM] & CPUID_KVM_ASYNCPF_INT) {
4255 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, env->async_pf_int_msr);
4256 }
4257 if (env->features[FEAT_KVM] & CPUID_KVM_ASYNCPF) {
4258 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);
4259 }
4260 if (env->features[FEAT_KVM] & CPUID_KVM_PV_EOI) {
4261 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);
4262 }
4263 if (env->features[FEAT_KVM] & CPUID_KVM_STEAL_TIME) {
4264 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);
4265 }
4266
4267 if (env->features[FEAT_KVM] & CPUID_KVM_POLL_CONTROL) {
4268 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, env->poll_control_msr);
4269 }
4270
4271 if ((IS_INTEL_CPU(env) || IS_ZHAOXIN_CPU(env)) && pmu_version > 0) {
4272 if (pmu_version > 1) {
4273 /* Stop the counter. */
4274 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
4275 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
4276 }
4277
4278 /* Set the counter values. */
4279 for (i = 0; i < num_pmu_fixed_counters; i++) {
4280 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,
4281 env->msr_fixed_counters[i]);
4282 }
4283 for (i = 0; i < num_pmu_gp_counters; i++) {
4284 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,
4285 env->msr_gp_counters[i]);
4286 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,
4287 env->msr_gp_evtsel[i]);
4288 }
4289 if (pmu_version > 1) {
4290 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,
4291 env->msr_global_status);
4292 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,
4293 env->msr_global_ovf_ctrl);
4294
4295 /* Now start the PMU. */
4296 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,
4297 env->msr_fixed_ctr_ctrl);
4298 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,
4299 env->msr_global_ctrl);
4300 }
4301 }
4302
4303 if (IS_AMD_CPU(env) && pmu_version > 0) {
4304 uint32_t sel_base = MSR_K7_EVNTSEL0;
4305 uint32_t ctr_base = MSR_K7_PERFCTR0;
4306 /*
4307 * The address of the next selector or counter register is
4308 * obtained by incrementing the address of the current selector
4309 * or counter register by one.
4310 */
4311 uint32_t step = 1;
4312
4313 /*
4314 * When PERFCORE or PerfMonV2 is enabled, AMD PMU uses a
4315 * separate set of addresses for the selector and counter
4316 * registers. Additionally, the address of the next selector or
4317 * counter register is determined by incrementing the address
4318 * of the current register by two.
4319 */
4320 if (num_pmu_gp_counters == AMD64_NUM_COUNTERS_CORE ||
4321 pmu_version > 1) {
4322 sel_base = MSR_F15H_PERF_CTL0;
4323 ctr_base = MSR_F15H_PERF_CTR0;
4324 step = 2;
4325 }
4326
4327 for (i = 0; i < num_pmu_gp_counters; i++) {
4328 kvm_msr_entry_add(cpu, ctr_base + i * step,
4329 env->msr_gp_counters[i]);
4330 kvm_msr_entry_add(cpu, sel_base + i * step,
4331 env->msr_gp_evtsel[i]);
4332 }
4333
4334 if (pmu_version > 1) {
4335 kvm_msr_entry_add(cpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
4336 env->msr_global_status);
4337 kvm_msr_entry_add(cpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
4338 env->msr_global_ovf_ctrl);
4339 kvm_msr_entry_add(cpu, MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
4340 env->msr_global_ctrl);
4341 }
4342 }
4343
4344 /*
4345 * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,
4346 * only sync them to KVM on the first cpu
4347 */
4348 if (current_cpu == first_cpu) {
4349 if (has_msr_hv_hypercall) {
4350 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,
4351 env->msr_hv_guest_os_id);
4352 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,
4353 env->msr_hv_hypercall);
4354 }
4355 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
4356 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,
4357 env->msr_hv_tsc);
4358 }
4359 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
4360 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL,
4361 env->msr_hv_reenlightenment_control);
4362 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL,
4363 env->msr_hv_tsc_emulation_control);
4364 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS,
4365 env->msr_hv_tsc_emulation_status);
4366 }
4367 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNDBG) &&
4368 has_msr_hv_syndbg_options) {
4369 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS,
4370 hyperv_syndbg_query_options());
4371 }
4372 }
4373 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
4374 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,
4375 env->msr_hv_vapic);
4376 }
4377 if (has_msr_hv_crash) {
4378 int j;
4379
4380 for (j = 0; j < HV_CRASH_PARAMS; j++)
4381 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,
4382 env->msr_hv_crash_params[j]);
4383
4384 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);
4385 }
4386 if (has_msr_hv_runtime) {
4387 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);
4388 }
4389 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VPINDEX)
4390 && hv_vpindex_settable) {
4391 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_INDEX,
4392 hyperv_vp_index(CPU(cpu)));
4393 }
4394 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
4395 int j;
4396
4397 kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);
4398
4399 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,
4400 env->msr_hv_synic_control);
4401 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,
4402 env->msr_hv_synic_evt_page);
4403 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,
4404 env->msr_hv_synic_msg_page);
4405
4406 for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {
4407 kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,
4408 env->msr_hv_synic_sint[j]);
4409 }
4410 }
4411 if (has_msr_hv_stimer) {
4412 int j;
4413
4414 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {
4415 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,
4416 env->msr_hv_stimer_config[j]);
4417 }
4418
4419 for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {
4420 kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,
4421 env->msr_hv_stimer_count[j]);
4422 }
4423 }
4424 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
4425 uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);
4426
4427 kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);
4428 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);
4429 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);
4430 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);
4431 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);
4432 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);
4433 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);
4434 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);
4435 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);
4436 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);
4437 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);
4438 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);
4439 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
4440 /* The CPU GPs if we write to a bit above the physical limit of
4441 * the host CPU (and KVM emulates that)
4442 */
4443 uint64_t mask = env->mtrr_var[i].mask;
4444 mask &= phys_mask;
4445
4446 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),
4447 env->mtrr_var[i].base);
4448 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), mask);
4449 }
4450 }
4451 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
4452 int addr_num = kvm_arch_get_supported_cpuid(kvm_state,
4453 0x14, 1, R_EAX) & 0x7;
4454
4455 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL,
4456 env->msr_rtit_ctrl);
4457 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS,
4458 env->msr_rtit_status);
4459 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE,
4460 env->msr_rtit_output_base);
4461 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK,
4462 env->msr_rtit_output_mask);
4463 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH,
4464 env->msr_rtit_cr3_match);
4465 for (i = 0; i < addr_num; i++) {
4466 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i,
4467 env->msr_rtit_addrs[i]);
4468 }
4469 }
4470
4471 if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
4472 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0,
4473 env->msr_ia32_sgxlepubkeyhash[0]);
4474 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1,
4475 env->msr_ia32_sgxlepubkeyhash[1]);
4476 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2,
4477 env->msr_ia32_sgxlepubkeyhash[2]);
4478 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3,
4479 env->msr_ia32_sgxlepubkeyhash[3]);
4480 }
4481
4482 if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4483 kvm_msr_entry_add(cpu, MSR_IA32_XFD,
4484 env->msr_xfd);
4485 kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR,
4486 env->msr_xfd_err);
4487 }
4488
4489 if (kvm_enabled() && cpu->enable_pmu &&
4490 (env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_ARCH_LBR)) {
4491 uint64_t depth;
4492 int ret;
4493
4494 /*
4495 * Only migrate Arch LBR states when the host Arch LBR depth
4496 * equals that of source guest's, this is to avoid mismatch
4497 * of guest/host config for the msr hence avoid unexpected
4498 * misbehavior.
4499 */
4500 ret = kvm_get_one_msr(cpu, MSR_ARCH_LBR_DEPTH, &depth);
4501
4502 if (ret == 1 && !!depth && depth == env->msr_lbr_depth) {
4503 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_CTL, env->msr_lbr_ctl);
4504 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_DEPTH, env->msr_lbr_depth);
4505
4506 for (i = 0; i < ARCH_LBR_NR_ENTRIES; i++) {
4507 if (!env->lbr_records[i].from) {
4508 continue;
4509 }
4510 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_FROM_0 + i,
4511 env->lbr_records[i].from);
4512 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_TO_0 + i,
4513 env->lbr_records[i].to);
4514 kvm_msr_entry_add(cpu, MSR_ARCH_LBR_INFO_0 + i,
4515 env->lbr_records[i].info);
4516 }
4517 }
4518 }
4519
4520 /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see
4521 * kvm_put_msr_feature_control. */
4522 }
4523
4524 if (env->mcg_cap) {
4525 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);
4526 kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);
4527 if (has_msr_mcg_ext_ctl) {
4528 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);
4529 }
4530 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
4531 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);
4532 }
4533 }
4534
4535 if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_CET_SHSTK ||
4536 env->features[FEAT_7_0_EDX] & CPUID_7_0_EDX_CET_IBT) {
4537 kvm_msr_entry_add(cpu, MSR_IA32_U_CET, env->u_cet);
4538 kvm_msr_entry_add(cpu, MSR_IA32_S_CET, env->s_cet);
4539
4540 if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_CET_SHSTK) {
4541 kvm_msr_entry_add(cpu, MSR_IA32_PL0_SSP, env->pl0_ssp);
4542 kvm_msr_entry_add(cpu, MSR_IA32_PL1_SSP, env->pl1_ssp);
4543 kvm_msr_entry_add(cpu, MSR_IA32_PL2_SSP, env->pl2_ssp);
4544 kvm_msr_entry_add(cpu, MSR_IA32_PL3_SSP, env->pl3_ssp);
4545
4546 #ifdef TARGET_X86_64
4547 if (lm_capable_kernel) {
4548 kvm_msr_entry_add(cpu, MSR_IA32_INT_SSP_TAB,
4549 env->int_ssp_table);
4550 }
4551 #endif
4552 }
4553 }
4554
4555 return kvm_buf_set_msrs(cpu);
4556 }
4557
4558 static int kvm_put_kvm_regs(X86CPU *cpu)
4559 {
4560 CPUX86State *env = &cpu->env;
4561 int ret;
4562
4563 if ((env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_CET_SHSTK)) {
4564 ret = kvm_set_one_reg(CPU(cpu), KVM_X86_REG_KVM(KVM_REG_GUEST_SSP),
4565 &env->guest_ssp);
4566 if (ret) {
4567 return ret;
4568 }
4569 }
4570 return 0;
4571 }
4572
4573 static int kvm_get_kvm_regs(X86CPU *cpu)
4574 {
4575 CPUX86State *env = &cpu->env;
4576 int ret;
4577
4578 if ((env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_CET_SHSTK)) {
4579 ret = kvm_get_one_reg(CPU(cpu), KVM_X86_REG_KVM(KVM_REG_GUEST_SSP),
4580 &env->guest_ssp);
4581 if (ret) {
4582 return ret;
4583 }
4584 }
4585 return 0;
4586 }
4587
4588 static int kvm_get_xsave(X86CPU *cpu)
4589 {
4590 CPUX86State *env = &cpu->env;
4591 void *xsave = env->xsave_buf;
4592 unsigned long type;
4593 int ret;
4594
4595 type = has_xsave2 ? KVM_GET_XSAVE2 : KVM_GET_XSAVE;
4596 ret = kvm_vcpu_ioctl(CPU(cpu), type, xsave);
4597 if (ret < 0) {
4598 return ret;
4599 }
4600 x86_cpu_xrstor_all_areas(cpu, xsave, env->xsave_buf_len);
4601
4602 return 0;
4603 }
4604
4605 static int kvm_get_xcrs(X86CPU *cpu)
4606 {
4607 CPUX86State *env = &cpu->env;
4608 int i, ret;
4609 struct kvm_xcrs xcrs;
4610
4611 if (!has_xcrs) {
4612 return 0;
4613 }
4614
4615 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);
4616 if (ret < 0) {
4617 return ret;
4618 }
4619
4620 for (i = 0; i < xcrs.nr_xcrs; i++) {
4621 /* Only support xcr0 now */
4622 if (xcrs.xcrs[i].xcr == 0) {
4623 env->xcr0 = xcrs.xcrs[i].value;
4624 break;
4625 }
4626 }
4627 return 0;
4628 }
4629
4630 static int kvm_get_sregs(X86CPU *cpu)
4631 {
4632 CPUX86State *env = &cpu->env;
4633 struct kvm_sregs sregs;
4634 int ret;
4635
4636 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS, &sregs);
4637 if (ret < 0) {
4638 return ret;
4639 }
4640
4641 /*
4642 * The interrupt_bitmap is ignored because KVM_GET_SREGS is
4643 * always preceded by KVM_GET_VCPU_EVENTS.
4644 */
4645
4646 get_seg(&env->segs[R_CS], &sregs.cs);
4647 get_seg(&env->segs[R_DS], &sregs.ds);
4648 get_seg(&env->segs[R_ES], &sregs.es);
4649 get_seg(&env->segs[R_FS], &sregs.fs);
4650 get_seg(&env->segs[R_GS], &sregs.gs);
4651 get_seg(&env->segs[R_SS], &sregs.ss);
4652
4653 get_seg(&env->tr, &sregs.tr);
4654 get_seg(&env->ldt, &sregs.ldt);
4655
4656 env->idt.limit = sregs.idt.limit;
4657 env->idt.base = sregs.idt.base;
4658 env->gdt.limit = sregs.gdt.limit;
4659 env->gdt.base = sregs.gdt.base;
4660
4661 env->cr[0] = sregs.cr0;
4662 env->cr[2] = sregs.cr2;
4663 env->cr[3] = sregs.cr3;
4664 env->cr[4] = sregs.cr4;
4665
4666 env->efer = sregs.efer;
4667 if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
4668 env->cr[0] & CR0_PG_MASK) {
4669 env->efer |= MSR_EFER_LMA;
4670 }
4671
4672 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
4673 x86_update_hflags(env);
4674
4675 return 0;
4676 }
4677
4678 static int kvm_get_sregs2(X86CPU *cpu)
4679 {
4680 CPUX86State *env = &cpu->env;
4681 struct kvm_sregs2 sregs;
4682 int i, ret;
4683
4684 ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_SREGS2, &sregs);
4685 if (ret < 0) {
4686 return ret;
4687 }
4688
4689 get_seg(&env->segs[R_CS], &sregs.cs);
4690 get_seg(&env->segs[R_DS], &sregs.ds);
4691 get_seg(&env->segs[R_ES], &sregs.es);
4692 get_seg(&env->segs[R_FS], &sregs.fs);
4693 get_seg(&env->segs[R_GS], &sregs.gs);
4694 get_seg(&env->segs[R_SS], &sregs.ss);
4695
4696 get_seg(&env->tr, &sregs.tr);
4697 get_seg(&env->ldt, &sregs.ldt);
4698
4699 env->idt.limit = sregs.idt.limit;
4700 env->idt.base = sregs.idt.base;
4701 env->gdt.limit = sregs.gdt.limit;
4702 env->gdt.base = sregs.gdt.base;
4703
4704 env->cr[0] = sregs.cr0;
4705 env->cr[2] = sregs.cr2;
4706 env->cr[3] = sregs.cr3;
4707 env->cr[4] = sregs.cr4;
4708
4709 env->efer = sregs.efer;
4710 if (sev_es_enabled() && env->efer & MSR_EFER_LME &&
4711 env->cr[0] & CR0_PG_MASK) {
4712 env->efer |= MSR_EFER_LMA;
4713 }
4714
4715 env->pdptrs_valid = sregs.flags & KVM_SREGS2_FLAGS_PDPTRS_VALID;
4716
4717 if (env->pdptrs_valid) {
4718 for (i = 0; i < 4; i++) {
4719 env->pdptrs[i] = sregs.pdptrs[i];
4720 }
4721 }
4722
4723 /* changes to apic base and cr8/tpr are read back via kvm_arch_post_run */
4724 x86_update_hflags(env);
4725
4726 return 0;
4727 }
4728
4729 static int kvm_get_msrs(X86CPU *cpu)
4730 {
4731 CPUX86State *env = &cpu->env;
4732 struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;
4733 int ret, i;
4734 uint64_t mtrr_top_bits;
4735
4736 kvm_msr_buf_reset(cpu);
4737
4738 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);
4739 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);
4740 kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);
4741 kvm_msr_entry_add(cpu, MSR_PAT, 0);
4742 if (has_msr_star) {
4743 kvm_msr_entry_add(cpu, MSR_STAR, 0);
4744 }
4745 if (has_msr_hsave_pa) {
4746 kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);
4747 }
4748 if (has_msr_tsc_aux) {
4749 kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);
4750 }
4751 if (has_msr_tsc_adjust) {
4752 kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);
4753 }
4754 if (has_msr_tsc_deadline) {
4755 kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);
4756 }
4757 if (has_msr_misc_enable) {
4758 kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);
4759 }
4760 if (has_msr_smbase) {
4761 kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);
4762 }
4763 if (has_msr_smi_count) {
4764 kvm_msr_entry_add(cpu, MSR_SMI_COUNT, 0);
4765 }
4766 if (has_msr_feature_control) {
4767 kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);
4768 }
4769 if (has_msr_pkrs) {
4770 kvm_msr_entry_add(cpu, MSR_IA32_PKRS, 0);
4771 }
4772 if (has_msr_bndcfgs) {
4773 kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);
4774 }
4775 if (has_msr_xss) {
4776 kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);
4777 }
4778 if (has_msr_umwait) {
4779 kvm_msr_entry_add(cpu, MSR_IA32_UMWAIT_CONTROL, 0);
4780 }
4781 if (has_msr_spec_ctrl) {
4782 kvm_msr_entry_add(cpu, MSR_IA32_SPEC_CTRL, 0);
4783 }
4784 if (has_tsc_scale_msr) {
4785 kvm_msr_entry_add(cpu, MSR_AMD64_TSC_RATIO, 0);
4786 }
4787
4788 if (has_msr_tsx_ctrl) {
4789 kvm_msr_entry_add(cpu, MSR_IA32_TSX_CTRL, 0);
4790 }
4791 if (has_msr_virt_ssbd) {
4792 kvm_msr_entry_add(cpu, MSR_VIRT_SSBD, 0);
4793 }
4794 if (!env->tsc_valid) {
4795 kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);
4796 env->tsc_valid = !runstate_is_running();
4797 }
4798 if (has_msr_hwcr) {
4799 kvm_msr_entry_add(cpu, MSR_K7_HWCR, 0);
4800 }
4801
4802 #ifdef TARGET_X86_64
4803 if (lm_capable_kernel) {
4804 kvm_msr_entry_add(cpu, MSR_CSTAR, 0);
4805 kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);
4806 kvm_msr_entry_add(cpu, MSR_FMASK, 0);
4807 kvm_msr_entry_add(cpu, MSR_LSTAR, 0);
4808 if (env->features[FEAT_7_1_EAX] & CPUID_7_1_EAX_FRED) {
4809 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP0, 0);
4810 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP1, 0);
4811 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP2, 0);
4812 kvm_msr_entry_add(cpu, MSR_IA32_FRED_RSP3, 0);
4813 kvm_msr_entry_add(cpu, MSR_IA32_FRED_STKLVLS, 0);
4814 kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP1, 0);
4815 kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP2, 0);
4816 kvm_msr_entry_add(cpu, MSR_IA32_FRED_SSP3, 0);
4817 kvm_msr_entry_add(cpu, MSR_IA32_FRED_CONFIG, 0);
4818
4819 if (!(env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_CET_SHSTK)) {
4820 /*
4821 * Aka MSR_IA32_FRED_SSP0. This MSR is accessible even if
4822 * CET shadow stack is not supported.
4823 */
4824 kvm_msr_entry_add(cpu, MSR_IA32_PL0_SSP, 0);
4825 }
4826 }
4827 }
4828 #endif
4829 if (env->features[FEAT_KVM] & (CPUID_KVM_CLOCK | CPUID_KVM_CLOCK2)) {
4830 kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);
4831 kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);
4832 }
4833 if (env->features[FEAT_KVM] & CPUID_KVM_ASYNCPF_INT) {
4834 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_INT, 0);
4835 }
4836 if (env->features[FEAT_KVM] & CPUID_KVM_ASYNCPF) {
4837 kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);
4838 }
4839 if (env->features[FEAT_KVM] & CPUID_KVM_PV_EOI) {
4840 kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);
4841 }
4842 if (env->features[FEAT_KVM] & CPUID_KVM_STEAL_TIME) {
4843 kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);
4844 }
4845 if (env->features[FEAT_KVM] & CPUID_KVM_POLL_CONTROL) {
4846 kvm_msr_entry_add(cpu, MSR_KVM_POLL_CONTROL, 1);
4847 }
4848
4849 if ((IS_INTEL_CPU(env) || IS_ZHAOXIN_CPU(env)) && pmu_version > 0) {
4850 if (pmu_version > 1) {
4851 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);
4852 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);
4853 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);
4854 kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);
4855 }
4856 for (i = 0; i < num_pmu_fixed_counters; i++) {
4857 kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);
4858 }
4859 for (i = 0; i < num_pmu_gp_counters; i++) {
4860 kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);
4861 kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);
4862 }
4863 }
4864
4865 if (IS_AMD_CPU(env) && pmu_version > 0) {
4866 uint32_t sel_base = MSR_K7_EVNTSEL0;
4867 uint32_t ctr_base = MSR_K7_PERFCTR0;
4868 /*
4869 * The address of the next selector or counter register is
4870 * obtained by incrementing the address of the current selector
4871 * or counter register by one.
4872 */
4873 uint32_t step = 1;
4874
4875 /*
4876 * When PERFCORE or PerfMonV2 is enabled, AMD PMU uses a separate
4877 * set of addresses for the selector and counter registers.
4878 * Additionally, the address of the next selector or counter
4879 * register is determined by incrementing the address of the
4880 * current register by two.
4881 */
4882 if (num_pmu_gp_counters == AMD64_NUM_COUNTERS_CORE ||
4883 pmu_version > 1) {
4884 sel_base = MSR_F15H_PERF_CTL0;
4885 ctr_base = MSR_F15H_PERF_CTR0;
4886 step = 2;
4887 }
4888
4889 for (i = 0; i < num_pmu_gp_counters; i++) {
4890 kvm_msr_entry_add(cpu, ctr_base + i * step, 0);
4891 kvm_msr_entry_add(cpu, sel_base + i * step, 0);
4892 }
4893
4894 if (pmu_version > 1) {
4895 kvm_msr_entry_add(cpu, MSR_AMD64_PERF_CNTR_GLOBAL_CTL, 0);
4896 kvm_msr_entry_add(cpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS, 0);
4897 kvm_msr_entry_add(cpu, MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR, 0);
4898 }
4899 }
4900
4901 if (env->mcg_cap) {
4902 kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);
4903 kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);
4904 if (has_msr_mcg_ext_ctl) {
4905 kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);
4906 }
4907 for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {
4908 kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);
4909 }
4910 }
4911
4912 if (has_msr_hv_hypercall) {
4913 kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);
4914 kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);
4915 }
4916 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_VAPIC)) {
4917 kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);
4918 }
4919 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_TIME)) {
4920 kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);
4921 }
4922 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_REENLIGHTENMENT)) {
4923 kvm_msr_entry_add(cpu, HV_X64_MSR_REENLIGHTENMENT_CONTROL, 0);
4924 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_CONTROL, 0);
4925 kvm_msr_entry_add(cpu, HV_X64_MSR_TSC_EMULATION_STATUS, 0);
4926 }
4927 if (has_msr_hv_syndbg_options) {
4928 kvm_msr_entry_add(cpu, HV_X64_MSR_SYNDBG_OPTIONS, 0);
4929 }
4930 if (has_msr_hv_crash) {
4931 int j;
4932
4933 for (j = 0; j < HV_CRASH_PARAMS; j++) {
4934 kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);
4935 }
4936 }
4937 if (has_msr_hv_runtime) {
4938 kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);
4939 }
4940 if (hyperv_feat_enabled(cpu, HYPERV_FEAT_SYNIC)) {
4941 uint32_t msr;
4942
4943 kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);
4944 kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);
4945 kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);
4946 for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {
4947 kvm_msr_entry_add(cpu, msr, 0);
4948 }
4949 }
4950 if (has_msr_hv_stimer) {
4951 uint32_t msr;
4952
4953 for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;
4954 msr++) {
4955 kvm_msr_entry_add(cpu, msr, 0);
4956 }
4957 }
4958 if (env->features[FEAT_1_EDX] & CPUID_MTRR) {
4959 kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);
4960 kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);
4961 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);
4962 kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);
4963 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);
4964 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);
4965 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);
4966 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);
4967 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);
4968 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);
4969 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);
4970 kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);
4971 for (i = 0; i < MSR_MTRRcap_VCNT; i++) {
4972 kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);
4973 kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);
4974 }
4975 }
4976
4977 if (env->features[FEAT_7_0_EBX] & CPUID_7_0_EBX_INTEL_PT) {
4978 int addr_num =
4979 kvm_arch_get_supported_cpuid(kvm_state, 0x14, 1, R_EAX) & 0x7;
4980
4981 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CTL, 0);
4982 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_STATUS, 0);
4983 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_BASE, 0);
4984 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_OUTPUT_MASK, 0);
4985 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_CR3_MATCH, 0);
4986 for (i = 0; i < addr_num; i++) {
4987 kvm_msr_entry_add(cpu, MSR_IA32_RTIT_ADDR0_A + i, 0);
4988 }
4989 }
4990
4991 if (env->features[FEAT_7_0_ECX] & CPUID_7_0_ECX_SGX_LC) {
4992 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH0, 0);
4993 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH1, 0);
4994 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH2, 0);
4995 kvm_msr_entry_add(cpu, MSR_IA32_SGXLEPUBKEYHASH3, 0);
4996 }
4997
4998 if (env->features[FEAT_XSAVE] & CPUID_D_1_EAX_XFD) {
4999 kvm_msr_entry_add(cpu, MSR_IA32_XFD, 0);
5000 kvm_msr_entry_add(cpu, MSR_IA32_XFD_ERR, 0);
Showing first 5,000 of 7,142 lines. View raw