xref: /linux/arch/x86/kvm/cpuid.c (revision e0c1b49f5b674cca7b10549c53b3791d0bbc90a8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  * cpuid support routines
5  *
6  * derived from arch/x86/kvm/x86.c
7  *
8  * Copyright 2011 Red Hat, Inc. and/or its affiliates.
9  * Copyright IBM Corporation, 2008
10  */
11 
12 #include <linux/kvm_host.h>
13 #include <linux/export.h>
14 #include <linux/vmalloc.h>
15 #include <linux/uaccess.h>
16 #include <linux/sched/stat.h>
17 
18 #include <asm/processor.h>
19 #include <asm/user.h>
20 #include <asm/fpu/xstate.h>
21 #include <asm/sgx.h>
22 #include "cpuid.h"
23 #include "lapic.h"
24 #include "mmu.h"
25 #include "trace.h"
26 #include "pmu.h"
27 
28 /*
29  * Unlike "struct cpuinfo_x86.x86_capability", kvm_cpu_caps doesn't need to be
30  * aligned to sizeof(unsigned long) because it's not accessed via bitops.
31  */
32 u32 kvm_cpu_caps[NR_KVM_CPU_CAPS] __read_mostly;
33 EXPORT_SYMBOL_GPL(kvm_cpu_caps);
34 
35 static u32 xstate_required_size(u64 xstate_bv, bool compacted)
36 {
37 	int feature_bit = 0;
38 	u32 ret = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
39 
40 	xstate_bv &= XFEATURE_MASK_EXTEND;
41 	while (xstate_bv) {
42 		if (xstate_bv & 0x1) {
43 		        u32 eax, ebx, ecx, edx, offset;
44 		        cpuid_count(0xD, feature_bit, &eax, &ebx, &ecx, &edx);
45 			offset = compacted ? ret : ebx;
46 			ret = max(ret, offset + eax);
47 		}
48 
49 		xstate_bv >>= 1;
50 		feature_bit++;
51 	}
52 
53 	return ret;
54 }
55 
56 /*
57  * This one is tied to SSB in the user API, and not
58  * visible in /proc/cpuinfo.
59  */
60 #define KVM_X86_FEATURE_PSFD		(13*32+28) /* Predictive Store Forwarding Disable */
61 
62 #define F feature_bit
63 #define SF(name) (boot_cpu_has(X86_FEATURE_##name) ? F(name) : 0)
64 
65 
66 static inline struct kvm_cpuid_entry2 *cpuid_entry2_find(
67 	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u32 index)
68 {
69 	struct kvm_cpuid_entry2 *e;
70 	int i;
71 
72 	for (i = 0; i < nent; i++) {
73 		e = &entries[i];
74 
75 		if (e->function == function &&
76 		    (!(e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) || e->index == index))
77 			return e;
78 	}
79 
80 	return NULL;
81 }
82 
83 static int kvm_check_cpuid(struct kvm_cpuid_entry2 *entries, int nent)
84 {
85 	struct kvm_cpuid_entry2 *best;
86 
87 	/*
88 	 * The existing code assumes virtual address is 48-bit or 57-bit in the
89 	 * canonical address checks; exit if it is ever changed.
90 	 */
91 	best = cpuid_entry2_find(entries, nent, 0x80000008, 0);
92 	if (best) {
93 		int vaddr_bits = (best->eax & 0xff00) >> 8;
94 
95 		if (vaddr_bits != 48 && vaddr_bits != 57 && vaddr_bits != 0)
96 			return -EINVAL;
97 	}
98 
99 	return 0;
100 }
101 
102 void kvm_update_pv_runtime(struct kvm_vcpu *vcpu)
103 {
104 	struct kvm_cpuid_entry2 *best;
105 
106 	best = kvm_find_cpuid_entry(vcpu, KVM_CPUID_FEATURES, 0);
107 
108 	/*
109 	 * save the feature bitmap to avoid cpuid lookup for every PV
110 	 * operation
111 	 */
112 	if (best)
113 		vcpu->arch.pv_cpuid.features = best->eax;
114 }
115 
116 void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu)
117 {
118 	struct kvm_cpuid_entry2 *best;
119 
120 	best = kvm_find_cpuid_entry(vcpu, 1, 0);
121 	if (best) {
122 		/* Update OSXSAVE bit */
123 		if (boot_cpu_has(X86_FEATURE_XSAVE))
124 			cpuid_entry_change(best, X86_FEATURE_OSXSAVE,
125 				   kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE));
126 
127 		cpuid_entry_change(best, X86_FEATURE_APIC,
128 			   vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE);
129 	}
130 
131 	best = kvm_find_cpuid_entry(vcpu, 7, 0);
132 	if (best && boot_cpu_has(X86_FEATURE_PKU) && best->function == 0x7)
133 		cpuid_entry_change(best, X86_FEATURE_OSPKE,
134 				   kvm_read_cr4_bits(vcpu, X86_CR4_PKE));
135 
136 	best = kvm_find_cpuid_entry(vcpu, 0xD, 0);
137 	if (best)
138 		best->ebx = xstate_required_size(vcpu->arch.xcr0, false);
139 
140 	best = kvm_find_cpuid_entry(vcpu, 0xD, 1);
141 	if (best && (cpuid_entry_has(best, X86_FEATURE_XSAVES) ||
142 		     cpuid_entry_has(best, X86_FEATURE_XSAVEC)))
143 		best->ebx = xstate_required_size(vcpu->arch.xcr0, true);
144 
145 	best = kvm_find_cpuid_entry(vcpu, KVM_CPUID_FEATURES, 0);
146 	if (kvm_hlt_in_guest(vcpu->kvm) && best &&
147 		(best->eax & (1 << KVM_FEATURE_PV_UNHALT)))
148 		best->eax &= ~(1 << KVM_FEATURE_PV_UNHALT);
149 
150 	if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT)) {
151 		best = kvm_find_cpuid_entry(vcpu, 0x1, 0);
152 		if (best)
153 			cpuid_entry_change(best, X86_FEATURE_MWAIT,
154 					   vcpu->arch.ia32_misc_enable_msr &
155 					   MSR_IA32_MISC_ENABLE_MWAIT);
156 	}
157 }
158 EXPORT_SYMBOL_GPL(kvm_update_cpuid_runtime);
159 
160 static void kvm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
161 {
162 	struct kvm_lapic *apic = vcpu->arch.apic;
163 	struct kvm_cpuid_entry2 *best;
164 
165 	best = kvm_find_cpuid_entry(vcpu, 1, 0);
166 	if (best && apic) {
167 		if (cpuid_entry_has(best, X86_FEATURE_TSC_DEADLINE_TIMER))
168 			apic->lapic_timer.timer_mode_mask = 3 << 17;
169 		else
170 			apic->lapic_timer.timer_mode_mask = 1 << 17;
171 
172 		kvm_apic_set_version(vcpu);
173 	}
174 
175 	best = kvm_find_cpuid_entry(vcpu, 0xD, 0);
176 	if (!best)
177 		vcpu->arch.guest_supported_xcr0 = 0;
178 	else
179 		vcpu->arch.guest_supported_xcr0 =
180 			(best->eax | ((u64)best->edx << 32)) & supported_xcr0;
181 
182 	/*
183 	 * Bits 127:0 of the allowed SECS.ATTRIBUTES (CPUID.0x12.0x1) enumerate
184 	 * the supported XSAVE Feature Request Mask (XFRM), i.e. the enclave's
185 	 * requested XCR0 value.  The enclave's XFRM must be a subset of XCRO
186 	 * at the time of EENTER, thus adjust the allowed XFRM by the guest's
187 	 * supported XCR0.  Similar to XCR0 handling, FP and SSE are forced to
188 	 * '1' even on CPUs that don't support XSAVE.
189 	 */
190 	best = kvm_find_cpuid_entry(vcpu, 0x12, 0x1);
191 	if (best) {
192 		best->ecx &= vcpu->arch.guest_supported_xcr0 & 0xffffffff;
193 		best->edx &= vcpu->arch.guest_supported_xcr0 >> 32;
194 		best->ecx |= XFEATURE_MASK_FPSSE;
195 	}
196 
197 	kvm_update_pv_runtime(vcpu);
198 
199 	vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
200 	vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
201 
202 	kvm_pmu_refresh(vcpu);
203 	vcpu->arch.cr4_guest_rsvd_bits =
204 	    __cr4_reserved_bits(guest_cpuid_has, vcpu);
205 
206 	kvm_hv_set_cpuid(vcpu);
207 
208 	/* Invoke the vendor callback only after the above state is updated. */
209 	static_call(kvm_x86_vcpu_after_set_cpuid)(vcpu);
210 
211 	/*
212 	 * Except for the MMU, which needs to do its thing any vendor specific
213 	 * adjustments to the reserved GPA bits.
214 	 */
215 	kvm_mmu_after_set_cpuid(vcpu);
216 }
217 
218 int cpuid_query_maxphyaddr(struct kvm_vcpu *vcpu)
219 {
220 	struct kvm_cpuid_entry2 *best;
221 
222 	best = kvm_find_cpuid_entry(vcpu, 0x80000000, 0);
223 	if (!best || best->eax < 0x80000008)
224 		goto not_found;
225 	best = kvm_find_cpuid_entry(vcpu, 0x80000008, 0);
226 	if (best)
227 		return best->eax & 0xff;
228 not_found:
229 	return 36;
230 }
231 
232 /*
233  * This "raw" version returns the reserved GPA bits without any adjustments for
234  * encryption technologies that usurp bits.  The raw mask should be used if and
235  * only if hardware does _not_ strip the usurped bits, e.g. in virtual MTRRs.
236  */
237 u64 kvm_vcpu_reserved_gpa_bits_raw(struct kvm_vcpu *vcpu)
238 {
239 	return rsvd_bits(cpuid_maxphyaddr(vcpu), 63);
240 }
241 
242 /* when an old userspace process fills a new kernel module */
243 int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
244 			     struct kvm_cpuid *cpuid,
245 			     struct kvm_cpuid_entry __user *entries)
246 {
247 	int r, i;
248 	struct kvm_cpuid_entry *e = NULL;
249 	struct kvm_cpuid_entry2 *e2 = NULL;
250 
251 	if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
252 		return -E2BIG;
253 
254 	if (cpuid->nent) {
255 		e = vmemdup_user(entries, array_size(sizeof(*e), cpuid->nent));
256 		if (IS_ERR(e))
257 			return PTR_ERR(e);
258 
259 		e2 = kvmalloc_array(cpuid->nent, sizeof(*e2), GFP_KERNEL_ACCOUNT);
260 		if (!e2) {
261 			r = -ENOMEM;
262 			goto out_free_cpuid;
263 		}
264 	}
265 	for (i = 0; i < cpuid->nent; i++) {
266 		e2[i].function = e[i].function;
267 		e2[i].eax = e[i].eax;
268 		e2[i].ebx = e[i].ebx;
269 		e2[i].ecx = e[i].ecx;
270 		e2[i].edx = e[i].edx;
271 		e2[i].index = 0;
272 		e2[i].flags = 0;
273 		e2[i].padding[0] = 0;
274 		e2[i].padding[1] = 0;
275 		e2[i].padding[2] = 0;
276 	}
277 
278 	r = kvm_check_cpuid(e2, cpuid->nent);
279 	if (r) {
280 		kvfree(e2);
281 		goto out_free_cpuid;
282 	}
283 
284 	kvfree(vcpu->arch.cpuid_entries);
285 	vcpu->arch.cpuid_entries = e2;
286 	vcpu->arch.cpuid_nent = cpuid->nent;
287 
288 	kvm_update_cpuid_runtime(vcpu);
289 	kvm_vcpu_after_set_cpuid(vcpu);
290 
291 out_free_cpuid:
292 	kvfree(e);
293 
294 	return r;
295 }
296 
297 int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
298 			      struct kvm_cpuid2 *cpuid,
299 			      struct kvm_cpuid_entry2 __user *entries)
300 {
301 	struct kvm_cpuid_entry2 *e2 = NULL;
302 	int r;
303 
304 	if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
305 		return -E2BIG;
306 
307 	if (cpuid->nent) {
308 		e2 = vmemdup_user(entries, array_size(sizeof(*e2), cpuid->nent));
309 		if (IS_ERR(e2))
310 			return PTR_ERR(e2);
311 	}
312 
313 	r = kvm_check_cpuid(e2, cpuid->nent);
314 	if (r) {
315 		kvfree(e2);
316 		return r;
317 	}
318 
319 	kvfree(vcpu->arch.cpuid_entries);
320 	vcpu->arch.cpuid_entries = e2;
321 	vcpu->arch.cpuid_nent = cpuid->nent;
322 
323 	kvm_update_cpuid_runtime(vcpu);
324 	kvm_vcpu_after_set_cpuid(vcpu);
325 
326 	return 0;
327 }
328 
329 int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
330 			      struct kvm_cpuid2 *cpuid,
331 			      struct kvm_cpuid_entry2 __user *entries)
332 {
333 	int r;
334 
335 	r = -E2BIG;
336 	if (cpuid->nent < vcpu->arch.cpuid_nent)
337 		goto out;
338 	r = -EFAULT;
339 	if (copy_to_user(entries, vcpu->arch.cpuid_entries,
340 			 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
341 		goto out;
342 	return 0;
343 
344 out:
345 	cpuid->nent = vcpu->arch.cpuid_nent;
346 	return r;
347 }
348 
349 /* Mask kvm_cpu_caps for @leaf with the raw CPUID capabilities of this CPU. */
350 static __always_inline void __kvm_cpu_cap_mask(unsigned int leaf)
351 {
352 	const struct cpuid_reg cpuid = x86_feature_cpuid(leaf * 32);
353 	struct kvm_cpuid_entry2 entry;
354 
355 	reverse_cpuid_check(leaf);
356 
357 	cpuid_count(cpuid.function, cpuid.index,
358 		    &entry.eax, &entry.ebx, &entry.ecx, &entry.edx);
359 
360 	kvm_cpu_caps[leaf] &= *__cpuid_entry_get_reg(&entry, cpuid.reg);
361 }
362 
363 static __always_inline
364 void kvm_cpu_cap_init_scattered(enum kvm_only_cpuid_leafs leaf, u32 mask)
365 {
366 	/* Use kvm_cpu_cap_mask for non-scattered leafs. */
367 	BUILD_BUG_ON(leaf < NCAPINTS);
368 
369 	kvm_cpu_caps[leaf] = mask;
370 
371 	__kvm_cpu_cap_mask(leaf);
372 }
373 
374 static __always_inline void kvm_cpu_cap_mask(enum cpuid_leafs leaf, u32 mask)
375 {
376 	/* Use kvm_cpu_cap_init_scattered for scattered leafs. */
377 	BUILD_BUG_ON(leaf >= NCAPINTS);
378 
379 	kvm_cpu_caps[leaf] &= mask;
380 
381 	__kvm_cpu_cap_mask(leaf);
382 }
383 
384 void kvm_set_cpu_caps(void)
385 {
386 #ifdef CONFIG_X86_64
387 	unsigned int f_gbpages = F(GBPAGES);
388 	unsigned int f_lm = F(LM);
389 #else
390 	unsigned int f_gbpages = 0;
391 	unsigned int f_lm = 0;
392 #endif
393 	memset(kvm_cpu_caps, 0, sizeof(kvm_cpu_caps));
394 
395 	BUILD_BUG_ON(sizeof(kvm_cpu_caps) - (NKVMCAPINTS * sizeof(*kvm_cpu_caps)) >
396 		     sizeof(boot_cpu_data.x86_capability));
397 
398 	memcpy(&kvm_cpu_caps, &boot_cpu_data.x86_capability,
399 	       sizeof(kvm_cpu_caps) - (NKVMCAPINTS * sizeof(*kvm_cpu_caps)));
400 
401 	kvm_cpu_cap_mask(CPUID_1_ECX,
402 		/*
403 		 * NOTE: MONITOR (and MWAIT) are emulated as NOP, but *not*
404 		 * advertised to guests via CPUID!
405 		 */
406 		F(XMM3) | F(PCLMULQDQ) | 0 /* DTES64, MONITOR */ |
407 		0 /* DS-CPL, VMX, SMX, EST */ |
408 		0 /* TM2 */ | F(SSSE3) | 0 /* CNXT-ID */ | 0 /* Reserved */ |
409 		F(FMA) | F(CX16) | 0 /* xTPR Update */ | F(PDCM) |
410 		F(PCID) | 0 /* Reserved, DCA */ | F(XMM4_1) |
411 		F(XMM4_2) | F(X2APIC) | F(MOVBE) | F(POPCNT) |
412 		0 /* Reserved*/ | F(AES) | F(XSAVE) | 0 /* OSXSAVE */ | F(AVX) |
413 		F(F16C) | F(RDRAND)
414 	);
415 	/* KVM emulates x2apic in software irrespective of host support. */
416 	kvm_cpu_cap_set(X86_FEATURE_X2APIC);
417 
418 	kvm_cpu_cap_mask(CPUID_1_EDX,
419 		F(FPU) | F(VME) | F(DE) | F(PSE) |
420 		F(TSC) | F(MSR) | F(PAE) | F(MCE) |
421 		F(CX8) | F(APIC) | 0 /* Reserved */ | F(SEP) |
422 		F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
423 		F(PAT) | F(PSE36) | 0 /* PSN */ | F(CLFLUSH) |
424 		0 /* Reserved, DS, ACPI */ | F(MMX) |
425 		F(FXSR) | F(XMM) | F(XMM2) | F(SELFSNOOP) |
426 		0 /* HTT, TM, Reserved, PBE */
427 	);
428 
429 	kvm_cpu_cap_mask(CPUID_7_0_EBX,
430 		F(FSGSBASE) | F(SGX) | F(BMI1) | F(HLE) | F(AVX2) | F(SMEP) |
431 		F(BMI2) | F(ERMS) | F(INVPCID) | F(RTM) | 0 /*MPX*/ | F(RDSEED) |
432 		F(ADX) | F(SMAP) | F(AVX512IFMA) | F(AVX512F) | F(AVX512PF) |
433 		F(AVX512ER) | F(AVX512CD) | F(CLFLUSHOPT) | F(CLWB) | F(AVX512DQ) |
434 		F(SHA_NI) | F(AVX512BW) | F(AVX512VL) | 0 /*INTEL_PT*/
435 	);
436 
437 	kvm_cpu_cap_mask(CPUID_7_ECX,
438 		F(AVX512VBMI) | F(LA57) | F(PKU) | 0 /*OSPKE*/ | F(RDPID) |
439 		F(AVX512_VPOPCNTDQ) | F(UMIP) | F(AVX512_VBMI2) | F(GFNI) |
440 		F(VAES) | F(VPCLMULQDQ) | F(AVX512_VNNI) | F(AVX512_BITALG) |
441 		F(CLDEMOTE) | F(MOVDIRI) | F(MOVDIR64B) | 0 /*WAITPKG*/ |
442 		F(SGX_LC) | F(BUS_LOCK_DETECT)
443 	);
444 	/* Set LA57 based on hardware capability. */
445 	if (cpuid_ecx(7) & F(LA57))
446 		kvm_cpu_cap_set(X86_FEATURE_LA57);
447 
448 	/*
449 	 * PKU not yet implemented for shadow paging and requires OSPKE
450 	 * to be set on the host. Clear it if that is not the case
451 	 */
452 	if (!tdp_enabled || !boot_cpu_has(X86_FEATURE_OSPKE))
453 		kvm_cpu_cap_clear(X86_FEATURE_PKU);
454 
455 	kvm_cpu_cap_mask(CPUID_7_EDX,
456 		F(AVX512_4VNNIW) | F(AVX512_4FMAPS) | F(SPEC_CTRL) |
457 		F(SPEC_CTRL_SSBD) | F(ARCH_CAPABILITIES) | F(INTEL_STIBP) |
458 		F(MD_CLEAR) | F(AVX512_VP2INTERSECT) | F(FSRM) |
459 		F(SERIALIZE) | F(TSXLDTRK) | F(AVX512_FP16)
460 	);
461 
462 	/* TSC_ADJUST and ARCH_CAPABILITIES are emulated in software. */
463 	kvm_cpu_cap_set(X86_FEATURE_TSC_ADJUST);
464 	kvm_cpu_cap_set(X86_FEATURE_ARCH_CAPABILITIES);
465 
466 	if (boot_cpu_has(X86_FEATURE_IBPB) && boot_cpu_has(X86_FEATURE_IBRS))
467 		kvm_cpu_cap_set(X86_FEATURE_SPEC_CTRL);
468 	if (boot_cpu_has(X86_FEATURE_STIBP))
469 		kvm_cpu_cap_set(X86_FEATURE_INTEL_STIBP);
470 	if (boot_cpu_has(X86_FEATURE_AMD_SSBD))
471 		kvm_cpu_cap_set(X86_FEATURE_SPEC_CTRL_SSBD);
472 
473 	kvm_cpu_cap_mask(CPUID_7_1_EAX,
474 		F(AVX_VNNI) | F(AVX512_BF16)
475 	);
476 
477 	kvm_cpu_cap_mask(CPUID_D_1_EAX,
478 		F(XSAVEOPT) | F(XSAVEC) | F(XGETBV1) | F(XSAVES)
479 	);
480 
481 	kvm_cpu_cap_init_scattered(CPUID_12_EAX,
482 		SF(SGX1) | SF(SGX2)
483 	);
484 
485 	kvm_cpu_cap_mask(CPUID_8000_0001_ECX,
486 		F(LAHF_LM) | F(CMP_LEGACY) | 0 /*SVM*/ | 0 /* ExtApicSpace */ |
487 		F(CR8_LEGACY) | F(ABM) | F(SSE4A) | F(MISALIGNSSE) |
488 		F(3DNOWPREFETCH) | F(OSVW) | 0 /* IBS */ | F(XOP) |
489 		0 /* SKINIT, WDT, LWP */ | F(FMA4) | F(TBM) |
490 		F(TOPOEXT) | F(PERFCTR_CORE)
491 	);
492 
493 	kvm_cpu_cap_mask(CPUID_8000_0001_EDX,
494 		F(FPU) | F(VME) | F(DE) | F(PSE) |
495 		F(TSC) | F(MSR) | F(PAE) | F(MCE) |
496 		F(CX8) | F(APIC) | 0 /* Reserved */ | F(SYSCALL) |
497 		F(MTRR) | F(PGE) | F(MCA) | F(CMOV) |
498 		F(PAT) | F(PSE36) | 0 /* Reserved */ |
499 		F(NX) | 0 /* Reserved */ | F(MMXEXT) | F(MMX) |
500 		F(FXSR) | F(FXSR_OPT) | f_gbpages | F(RDTSCP) |
501 		0 /* Reserved */ | f_lm | F(3DNOWEXT) | F(3DNOW)
502 	);
503 
504 	if (!tdp_enabled && IS_ENABLED(CONFIG_X86_64))
505 		kvm_cpu_cap_set(X86_FEATURE_GBPAGES);
506 
507 	kvm_cpu_cap_mask(CPUID_8000_0008_EBX,
508 		F(CLZERO) | F(XSAVEERPTR) |
509 		F(WBNOINVD) | F(AMD_IBPB) | F(AMD_IBRS) | F(AMD_SSBD) | F(VIRT_SSBD) |
510 		F(AMD_SSB_NO) | F(AMD_STIBP) | F(AMD_STIBP_ALWAYS_ON) |
511 		__feature_bit(KVM_X86_FEATURE_PSFD)
512 	);
513 
514 	/*
515 	 * AMD has separate bits for each SPEC_CTRL bit.
516 	 * arch/x86/kernel/cpu/bugs.c is kind enough to
517 	 * record that in cpufeatures so use them.
518 	 */
519 	if (boot_cpu_has(X86_FEATURE_IBPB))
520 		kvm_cpu_cap_set(X86_FEATURE_AMD_IBPB);
521 	if (boot_cpu_has(X86_FEATURE_IBRS))
522 		kvm_cpu_cap_set(X86_FEATURE_AMD_IBRS);
523 	if (boot_cpu_has(X86_FEATURE_STIBP))
524 		kvm_cpu_cap_set(X86_FEATURE_AMD_STIBP);
525 	if (boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD))
526 		kvm_cpu_cap_set(X86_FEATURE_AMD_SSBD);
527 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
528 		kvm_cpu_cap_set(X86_FEATURE_AMD_SSB_NO);
529 	/*
530 	 * The preference is to use SPEC CTRL MSR instead of the
531 	 * VIRT_SPEC MSR.
532 	 */
533 	if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) &&
534 	    !boot_cpu_has(X86_FEATURE_AMD_SSBD))
535 		kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
536 
537 	/*
538 	 * Hide all SVM features by default, SVM will set the cap bits for
539 	 * features it emulates and/or exposes for L1.
540 	 */
541 	kvm_cpu_cap_mask(CPUID_8000_000A_EDX, 0);
542 
543 	kvm_cpu_cap_mask(CPUID_8000_001F_EAX,
544 		0 /* SME */ | F(SEV) | 0 /* VM_PAGE_FLUSH */ | F(SEV_ES) |
545 		F(SME_COHERENT));
546 
547 	kvm_cpu_cap_mask(CPUID_C000_0001_EDX,
548 		F(XSTORE) | F(XSTORE_EN) | F(XCRYPT) | F(XCRYPT_EN) |
549 		F(ACE2) | F(ACE2_EN) | F(PHE) | F(PHE_EN) |
550 		F(PMM) | F(PMM_EN)
551 	);
552 
553 	/*
554 	 * Hide RDTSCP and RDPID if either feature is reported as supported but
555 	 * probing MSR_TSC_AUX failed.  This is purely a sanity check and
556 	 * should never happen, but the guest will likely crash if RDTSCP or
557 	 * RDPID is misreported, and KVM has botched MSR_TSC_AUX emulation in
558 	 * the past.  For example, the sanity check may fire if this instance of
559 	 * KVM is running as L1 on top of an older, broken KVM.
560 	 */
561 	if (WARN_ON((kvm_cpu_cap_has(X86_FEATURE_RDTSCP) ||
562 		     kvm_cpu_cap_has(X86_FEATURE_RDPID)) &&
563 		     !kvm_is_supported_user_return_msr(MSR_TSC_AUX))) {
564 		kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
565 		kvm_cpu_cap_clear(X86_FEATURE_RDPID);
566 	}
567 }
568 EXPORT_SYMBOL_GPL(kvm_set_cpu_caps);
569 
570 struct kvm_cpuid_array {
571 	struct kvm_cpuid_entry2 *entries;
572 	int maxnent;
573 	int nent;
574 };
575 
576 static struct kvm_cpuid_entry2 *do_host_cpuid(struct kvm_cpuid_array *array,
577 					      u32 function, u32 index)
578 {
579 	struct kvm_cpuid_entry2 *entry;
580 
581 	if (array->nent >= array->maxnent)
582 		return NULL;
583 
584 	entry = &array->entries[array->nent++];
585 
586 	entry->function = function;
587 	entry->index = index;
588 	entry->flags = 0;
589 
590 	cpuid_count(entry->function, entry->index,
591 		    &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
592 
593 	switch (function) {
594 	case 4:
595 	case 7:
596 	case 0xb:
597 	case 0xd:
598 	case 0xf:
599 	case 0x10:
600 	case 0x12:
601 	case 0x14:
602 	case 0x17:
603 	case 0x18:
604 	case 0x1f:
605 	case 0x8000001d:
606 		entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
607 		break;
608 	}
609 
610 	return entry;
611 }
612 
613 static int __do_cpuid_func_emulated(struct kvm_cpuid_array *array, u32 func)
614 {
615 	struct kvm_cpuid_entry2 *entry;
616 
617 	if (array->nent >= array->maxnent)
618 		return -E2BIG;
619 
620 	entry = &array->entries[array->nent];
621 	entry->function = func;
622 	entry->index = 0;
623 	entry->flags = 0;
624 
625 	switch (func) {
626 	case 0:
627 		entry->eax = 7;
628 		++array->nent;
629 		break;
630 	case 1:
631 		entry->ecx = F(MOVBE);
632 		++array->nent;
633 		break;
634 	case 7:
635 		entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
636 		entry->eax = 0;
637 		if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
638 			entry->ecx = F(RDPID);
639 		++array->nent;
640 		break;
641 	default:
642 		break;
643 	}
644 
645 	return 0;
646 }
647 
648 static inline int __do_cpuid_func(struct kvm_cpuid_array *array, u32 function)
649 {
650 	struct kvm_cpuid_entry2 *entry;
651 	int r, i, max_idx;
652 
653 	/* all calls to cpuid_count() should be made on the same cpu */
654 	get_cpu();
655 
656 	r = -E2BIG;
657 
658 	entry = do_host_cpuid(array, function, 0);
659 	if (!entry)
660 		goto out;
661 
662 	switch (function) {
663 	case 0:
664 		/* Limited to the highest leaf implemented in KVM. */
665 		entry->eax = min(entry->eax, 0x1fU);
666 		break;
667 	case 1:
668 		cpuid_entry_override(entry, CPUID_1_EDX);
669 		cpuid_entry_override(entry, CPUID_1_ECX);
670 		break;
671 	case 2:
672 		/*
673 		 * On ancient CPUs, function 2 entries are STATEFUL.  That is,
674 		 * CPUID(function=2, index=0) may return different results each
675 		 * time, with the least-significant byte in EAX enumerating the
676 		 * number of times software should do CPUID(2, 0).
677 		 *
678 		 * Modern CPUs, i.e. every CPU KVM has *ever* run on are less
679 		 * idiotic.  Intel's SDM states that EAX & 0xff "will always
680 		 * return 01H. Software should ignore this value and not
681 		 * interpret it as an informational descriptor", while AMD's
682 		 * APM states that CPUID(2) is reserved.
683 		 *
684 		 * WARN if a frankenstein CPU that supports virtualization and
685 		 * a stateful CPUID.0x2 is encountered.
686 		 */
687 		WARN_ON_ONCE((entry->eax & 0xff) > 1);
688 		break;
689 	/* functions 4 and 0x8000001d have additional index. */
690 	case 4:
691 	case 0x8000001d:
692 		/*
693 		 * Read entries until the cache type in the previous entry is
694 		 * zero, i.e. indicates an invalid entry.
695 		 */
696 		for (i = 1; entry->eax & 0x1f; ++i) {
697 			entry = do_host_cpuid(array, function, i);
698 			if (!entry)
699 				goto out;
700 		}
701 		break;
702 	case 6: /* Thermal management */
703 		entry->eax = 0x4; /* allow ARAT */
704 		entry->ebx = 0;
705 		entry->ecx = 0;
706 		entry->edx = 0;
707 		break;
708 	/* function 7 has additional index. */
709 	case 7:
710 		entry->eax = min(entry->eax, 1u);
711 		cpuid_entry_override(entry, CPUID_7_0_EBX);
712 		cpuid_entry_override(entry, CPUID_7_ECX);
713 		cpuid_entry_override(entry, CPUID_7_EDX);
714 
715 		/* KVM only supports 0x7.0 and 0x7.1, capped above via min(). */
716 		if (entry->eax == 1) {
717 			entry = do_host_cpuid(array, function, 1);
718 			if (!entry)
719 				goto out;
720 
721 			cpuid_entry_override(entry, CPUID_7_1_EAX);
722 			entry->ebx = 0;
723 			entry->ecx = 0;
724 			entry->edx = 0;
725 		}
726 		break;
727 	case 9:
728 		break;
729 	case 0xa: { /* Architectural Performance Monitoring */
730 		struct x86_pmu_capability cap;
731 		union cpuid10_eax eax;
732 		union cpuid10_edx edx;
733 
734 		perf_get_x86_pmu_capability(&cap);
735 
736 		/*
737 		 * Only support guest architectural pmu on a host
738 		 * with architectural pmu.
739 		 */
740 		if (!cap.version)
741 			memset(&cap, 0, sizeof(cap));
742 
743 		eax.split.version_id = min(cap.version, 2);
744 		eax.split.num_counters = cap.num_counters_gp;
745 		eax.split.bit_width = cap.bit_width_gp;
746 		eax.split.mask_length = cap.events_mask_len;
747 
748 		edx.split.num_counters_fixed = min(cap.num_counters_fixed, MAX_FIXED_COUNTERS);
749 		edx.split.bit_width_fixed = cap.bit_width_fixed;
750 		if (cap.version)
751 			edx.split.anythread_deprecated = 1;
752 		edx.split.reserved1 = 0;
753 		edx.split.reserved2 = 0;
754 
755 		entry->eax = eax.full;
756 		entry->ebx = cap.events_mask;
757 		entry->ecx = 0;
758 		entry->edx = edx.full;
759 		break;
760 	}
761 	/*
762 	 * Per Intel's SDM, the 0x1f is a superset of 0xb,
763 	 * thus they can be handled by common code.
764 	 */
765 	case 0x1f:
766 	case 0xb:
767 		/*
768 		 * Populate entries until the level type (ECX[15:8]) of the
769 		 * previous entry is zero.  Note, CPUID EAX.{0x1f,0xb}.0 is
770 		 * the starting entry, filled by the primary do_host_cpuid().
771 		 */
772 		for (i = 1; entry->ecx & 0xff00; ++i) {
773 			entry = do_host_cpuid(array, function, i);
774 			if (!entry)
775 				goto out;
776 		}
777 		break;
778 	case 0xd:
779 		entry->eax &= supported_xcr0;
780 		entry->ebx = xstate_required_size(supported_xcr0, false);
781 		entry->ecx = entry->ebx;
782 		entry->edx &= supported_xcr0 >> 32;
783 		if (!supported_xcr0)
784 			break;
785 
786 		entry = do_host_cpuid(array, function, 1);
787 		if (!entry)
788 			goto out;
789 
790 		cpuid_entry_override(entry, CPUID_D_1_EAX);
791 		if (entry->eax & (F(XSAVES)|F(XSAVEC)))
792 			entry->ebx = xstate_required_size(supported_xcr0 | supported_xss,
793 							  true);
794 		else {
795 			WARN_ON_ONCE(supported_xss != 0);
796 			entry->ebx = 0;
797 		}
798 		entry->ecx &= supported_xss;
799 		entry->edx &= supported_xss >> 32;
800 
801 		for (i = 2; i < 64; ++i) {
802 			bool s_state;
803 			if (supported_xcr0 & BIT_ULL(i))
804 				s_state = false;
805 			else if (supported_xss & BIT_ULL(i))
806 				s_state = true;
807 			else
808 				continue;
809 
810 			entry = do_host_cpuid(array, function, i);
811 			if (!entry)
812 				goto out;
813 
814 			/*
815 			 * The supported check above should have filtered out
816 			 * invalid sub-leafs.  Only valid sub-leafs should
817 			 * reach this point, and they should have a non-zero
818 			 * save state size.  Furthermore, check whether the
819 			 * processor agrees with supported_xcr0/supported_xss
820 			 * on whether this is an XCR0- or IA32_XSS-managed area.
821 			 */
822 			if (WARN_ON_ONCE(!entry->eax || (entry->ecx & 0x1) != s_state)) {
823 				--array->nent;
824 				continue;
825 			}
826 			entry->edx = 0;
827 		}
828 		break;
829 	case 0x12:
830 		/* Intel SGX */
831 		if (!kvm_cpu_cap_has(X86_FEATURE_SGX)) {
832 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
833 			break;
834 		}
835 
836 		/*
837 		 * Index 0: Sub-features, MISCSELECT (a.k.a extended features)
838 		 * and max enclave sizes.   The SGX sub-features and MISCSELECT
839 		 * are restricted by kernel and KVM capabilities (like most
840 		 * feature flags), while enclave size is unrestricted.
841 		 */
842 		cpuid_entry_override(entry, CPUID_12_EAX);
843 		entry->ebx &= SGX_MISC_EXINFO;
844 
845 		entry = do_host_cpuid(array, function, 1);
846 		if (!entry)
847 			goto out;
848 
849 		/*
850 		 * Index 1: SECS.ATTRIBUTES.  ATTRIBUTES are restricted a la
851 		 * feature flags.  Advertise all supported flags, including
852 		 * privileged attributes that require explicit opt-in from
853 		 * userspace.  ATTRIBUTES.XFRM is not adjusted as userspace is
854 		 * expected to derive it from supported XCR0.
855 		 */
856 		entry->eax &= SGX_ATTR_DEBUG | SGX_ATTR_MODE64BIT |
857 			      SGX_ATTR_PROVISIONKEY | SGX_ATTR_EINITTOKENKEY |
858 			      SGX_ATTR_KSS;
859 		entry->ebx &= 0;
860 		break;
861 	/* Intel PT */
862 	case 0x14:
863 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT)) {
864 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
865 			break;
866 		}
867 
868 		for (i = 1, max_idx = entry->eax; i <= max_idx; ++i) {
869 			if (!do_host_cpuid(array, function, i))
870 				goto out;
871 		}
872 		break;
873 	case KVM_CPUID_SIGNATURE: {
874 		static const char signature[12] = "KVMKVMKVM\0\0";
875 		const u32 *sigptr = (const u32 *)signature;
876 		entry->eax = KVM_CPUID_FEATURES;
877 		entry->ebx = sigptr[0];
878 		entry->ecx = sigptr[1];
879 		entry->edx = sigptr[2];
880 		break;
881 	}
882 	case KVM_CPUID_FEATURES:
883 		entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
884 			     (1 << KVM_FEATURE_NOP_IO_DELAY) |
885 			     (1 << KVM_FEATURE_CLOCKSOURCE2) |
886 			     (1 << KVM_FEATURE_ASYNC_PF) |
887 			     (1 << KVM_FEATURE_PV_EOI) |
888 			     (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT) |
889 			     (1 << KVM_FEATURE_PV_UNHALT) |
890 			     (1 << KVM_FEATURE_PV_TLB_FLUSH) |
891 			     (1 << KVM_FEATURE_ASYNC_PF_VMEXIT) |
892 			     (1 << KVM_FEATURE_PV_SEND_IPI) |
893 			     (1 << KVM_FEATURE_POLL_CONTROL) |
894 			     (1 << KVM_FEATURE_PV_SCHED_YIELD) |
895 			     (1 << KVM_FEATURE_ASYNC_PF_INT);
896 
897 		if (sched_info_on())
898 			entry->eax |= (1 << KVM_FEATURE_STEAL_TIME);
899 
900 		entry->ebx = 0;
901 		entry->ecx = 0;
902 		entry->edx = 0;
903 		break;
904 	case 0x80000000:
905 		entry->eax = min(entry->eax, 0x8000001f);
906 		break;
907 	case 0x80000001:
908 		cpuid_entry_override(entry, CPUID_8000_0001_EDX);
909 		cpuid_entry_override(entry, CPUID_8000_0001_ECX);
910 		break;
911 	case 0x80000006:
912 		/* L2 cache and TLB: pass through host info. */
913 		break;
914 	case 0x80000007: /* Advanced power management */
915 		/* invariant TSC is CPUID.80000007H:EDX[8] */
916 		entry->edx &= (1 << 8);
917 		/* mask against host */
918 		entry->edx &= boot_cpu_data.x86_power;
919 		entry->eax = entry->ebx = entry->ecx = 0;
920 		break;
921 	case 0x80000008: {
922 		unsigned g_phys_as = (entry->eax >> 16) & 0xff;
923 		unsigned virt_as = max((entry->eax >> 8) & 0xff, 48U);
924 		unsigned phys_as = entry->eax & 0xff;
925 
926 		/*
927 		 * If TDP (NPT) is disabled use the adjusted host MAXPHYADDR as
928 		 * the guest operates in the same PA space as the host, i.e.
929 		 * reductions in MAXPHYADDR for memory encryption affect shadow
930 		 * paging, too.
931 		 *
932 		 * If TDP is enabled but an explicit guest MAXPHYADDR is not
933 		 * provided, use the raw bare metal MAXPHYADDR as reductions to
934 		 * the HPAs do not affect GPAs.
935 		 */
936 		if (!tdp_enabled)
937 			g_phys_as = boot_cpu_data.x86_phys_bits;
938 		else if (!g_phys_as)
939 			g_phys_as = phys_as;
940 
941 		entry->eax = g_phys_as | (virt_as << 8);
942 		entry->edx = 0;
943 		cpuid_entry_override(entry, CPUID_8000_0008_EBX);
944 		break;
945 	}
946 	case 0x8000000A:
947 		if (!kvm_cpu_cap_has(X86_FEATURE_SVM)) {
948 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
949 			break;
950 		}
951 		entry->eax = 1; /* SVM revision 1 */
952 		entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
953 				   ASID emulation to nested SVM */
954 		entry->ecx = 0; /* Reserved */
955 		cpuid_entry_override(entry, CPUID_8000_000A_EDX);
956 		break;
957 	case 0x80000019:
958 		entry->ecx = entry->edx = 0;
959 		break;
960 	case 0x8000001a:
961 	case 0x8000001e:
962 		break;
963 	case 0x8000001F:
964 		if (!kvm_cpu_cap_has(X86_FEATURE_SEV)) {
965 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
966 		} else {
967 			cpuid_entry_override(entry, CPUID_8000_001F_EAX);
968 
969 			/*
970 			 * Enumerate '0' for "PA bits reduction", the adjusted
971 			 * MAXPHYADDR is enumerated directly (see 0x80000008).
972 			 */
973 			entry->ebx &= ~GENMASK(11, 6);
974 		}
975 		break;
976 	/*Add support for Centaur's CPUID instruction*/
977 	case 0xC0000000:
978 		/*Just support up to 0xC0000004 now*/
979 		entry->eax = min(entry->eax, 0xC0000004);
980 		break;
981 	case 0xC0000001:
982 		cpuid_entry_override(entry, CPUID_C000_0001_EDX);
983 		break;
984 	case 3: /* Processor serial number */
985 	case 5: /* MONITOR/MWAIT */
986 	case 0xC0000002:
987 	case 0xC0000003:
988 	case 0xC0000004:
989 	default:
990 		entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
991 		break;
992 	}
993 
994 	r = 0;
995 
996 out:
997 	put_cpu();
998 
999 	return r;
1000 }
1001 
1002 static int do_cpuid_func(struct kvm_cpuid_array *array, u32 func,
1003 			 unsigned int type)
1004 {
1005 	if (type == KVM_GET_EMULATED_CPUID)
1006 		return __do_cpuid_func_emulated(array, func);
1007 
1008 	return __do_cpuid_func(array, func);
1009 }
1010 
1011 #define CENTAUR_CPUID_SIGNATURE 0xC0000000
1012 
1013 static int get_cpuid_func(struct kvm_cpuid_array *array, u32 func,
1014 			  unsigned int type)
1015 {
1016 	u32 limit;
1017 	int r;
1018 
1019 	if (func == CENTAUR_CPUID_SIGNATURE &&
1020 	    boot_cpu_data.x86_vendor != X86_VENDOR_CENTAUR)
1021 		return 0;
1022 
1023 	r = do_cpuid_func(array, func, type);
1024 	if (r)
1025 		return r;
1026 
1027 	limit = array->entries[array->nent - 1].eax;
1028 	for (func = func + 1; func <= limit; ++func) {
1029 		r = do_cpuid_func(array, func, type);
1030 		if (r)
1031 			break;
1032 	}
1033 
1034 	return r;
1035 }
1036 
1037 static bool sanity_check_entries(struct kvm_cpuid_entry2 __user *entries,
1038 				 __u32 num_entries, unsigned int ioctl_type)
1039 {
1040 	int i;
1041 	__u32 pad[3];
1042 
1043 	if (ioctl_type != KVM_GET_EMULATED_CPUID)
1044 		return false;
1045 
1046 	/*
1047 	 * We want to make sure that ->padding is being passed clean from
1048 	 * userspace in case we want to use it for something in the future.
1049 	 *
1050 	 * Sadly, this wasn't enforced for KVM_GET_SUPPORTED_CPUID and so we
1051 	 * have to give ourselves satisfied only with the emulated side. /me
1052 	 * sheds a tear.
1053 	 */
1054 	for (i = 0; i < num_entries; i++) {
1055 		if (copy_from_user(pad, entries[i].padding, sizeof(pad)))
1056 			return true;
1057 
1058 		if (pad[0] || pad[1] || pad[2])
1059 			return true;
1060 	}
1061 	return false;
1062 }
1063 
1064 int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid,
1065 			    struct kvm_cpuid_entry2 __user *entries,
1066 			    unsigned int type)
1067 {
1068 	static const u32 funcs[] = {
1069 		0, 0x80000000, CENTAUR_CPUID_SIGNATURE, KVM_CPUID_SIGNATURE,
1070 	};
1071 
1072 	struct kvm_cpuid_array array = {
1073 		.nent = 0,
1074 	};
1075 	int r, i;
1076 
1077 	if (cpuid->nent < 1)
1078 		return -E2BIG;
1079 	if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
1080 		cpuid->nent = KVM_MAX_CPUID_ENTRIES;
1081 
1082 	if (sanity_check_entries(entries, cpuid->nent, type))
1083 		return -EINVAL;
1084 
1085 	array.entries = vzalloc(array_size(sizeof(struct kvm_cpuid_entry2),
1086 					   cpuid->nent));
1087 	if (!array.entries)
1088 		return -ENOMEM;
1089 
1090 	array.maxnent = cpuid->nent;
1091 
1092 	for (i = 0; i < ARRAY_SIZE(funcs); i++) {
1093 		r = get_cpuid_func(&array, funcs[i], type);
1094 		if (r)
1095 			goto out_free;
1096 	}
1097 	cpuid->nent = array.nent;
1098 
1099 	if (copy_to_user(entries, array.entries,
1100 			 array.nent * sizeof(struct kvm_cpuid_entry2)))
1101 		r = -EFAULT;
1102 
1103 out_free:
1104 	vfree(array.entries);
1105 	return r;
1106 }
1107 
1108 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
1109 					      u32 function, u32 index)
1110 {
1111 	return cpuid_entry2_find(vcpu->arch.cpuid_entries, vcpu->arch.cpuid_nent,
1112 				 function, index);
1113 }
1114 EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry);
1115 
1116 /*
1117  * Intel CPUID semantics treats any query for an out-of-range leaf as if the
1118  * highest basic leaf (i.e. CPUID.0H:EAX) were requested.  AMD CPUID semantics
1119  * returns all zeroes for any undefined leaf, whether or not the leaf is in
1120  * range.  Centaur/VIA follows Intel semantics.
1121  *
1122  * A leaf is considered out-of-range if its function is higher than the maximum
1123  * supported leaf of its associated class or if its associated class does not
1124  * exist.
1125  *
1126  * There are three primary classes to be considered, with their respective
1127  * ranges described as "<base> - <top>[,<base2> - <top2>] inclusive.  A primary
1128  * class exists if a guest CPUID entry for its <base> leaf exists.  For a given
1129  * class, CPUID.<base>.EAX contains the max supported leaf for the class.
1130  *
1131  *  - Basic:      0x00000000 - 0x3fffffff, 0x50000000 - 0x7fffffff
1132  *  - Hypervisor: 0x40000000 - 0x4fffffff
1133  *  - Extended:   0x80000000 - 0xbfffffff
1134  *  - Centaur:    0xc0000000 - 0xcfffffff
1135  *
1136  * The Hypervisor class is further subdivided into sub-classes that each act as
1137  * their own independent class associated with a 0x100 byte range.  E.g. if Qemu
1138  * is advertising support for both HyperV and KVM, the resulting Hypervisor
1139  * CPUID sub-classes are:
1140  *
1141  *  - HyperV:     0x40000000 - 0x400000ff
1142  *  - KVM:        0x40000100 - 0x400001ff
1143  */
1144 static struct kvm_cpuid_entry2 *
1145 get_out_of_range_cpuid_entry(struct kvm_vcpu *vcpu, u32 *fn_ptr, u32 index)
1146 {
1147 	struct kvm_cpuid_entry2 *basic, *class;
1148 	u32 function = *fn_ptr;
1149 
1150 	basic = kvm_find_cpuid_entry(vcpu, 0, 0);
1151 	if (!basic)
1152 		return NULL;
1153 
1154 	if (is_guest_vendor_amd(basic->ebx, basic->ecx, basic->edx) ||
1155 	    is_guest_vendor_hygon(basic->ebx, basic->ecx, basic->edx))
1156 		return NULL;
1157 
1158 	if (function >= 0x40000000 && function <= 0x4fffffff)
1159 		class = kvm_find_cpuid_entry(vcpu, function & 0xffffff00, 0);
1160 	else if (function >= 0xc0000000)
1161 		class = kvm_find_cpuid_entry(vcpu, 0xc0000000, 0);
1162 	else
1163 		class = kvm_find_cpuid_entry(vcpu, function & 0x80000000, 0);
1164 
1165 	if (class && function <= class->eax)
1166 		return NULL;
1167 
1168 	/*
1169 	 * Leaf specific adjustments are also applied when redirecting to the
1170 	 * max basic entry, e.g. if the max basic leaf is 0xb but there is no
1171 	 * entry for CPUID.0xb.index (see below), then the output value for EDX
1172 	 * needs to be pulled from CPUID.0xb.1.
1173 	 */
1174 	*fn_ptr = basic->eax;
1175 
1176 	/*
1177 	 * The class does not exist or the requested function is out of range;
1178 	 * the effective CPUID entry is the max basic leaf.  Note, the index of
1179 	 * the original requested leaf is observed!
1180 	 */
1181 	return kvm_find_cpuid_entry(vcpu, basic->eax, index);
1182 }
1183 
1184 bool kvm_cpuid(struct kvm_vcpu *vcpu, u32 *eax, u32 *ebx,
1185 	       u32 *ecx, u32 *edx, bool exact_only)
1186 {
1187 	u32 orig_function = *eax, function = *eax, index = *ecx;
1188 	struct kvm_cpuid_entry2 *entry;
1189 	bool exact, used_max_basic = false;
1190 
1191 	entry = kvm_find_cpuid_entry(vcpu, function, index);
1192 	exact = !!entry;
1193 
1194 	if (!entry && !exact_only) {
1195 		entry = get_out_of_range_cpuid_entry(vcpu, &function, index);
1196 		used_max_basic = !!entry;
1197 	}
1198 
1199 	if (entry) {
1200 		*eax = entry->eax;
1201 		*ebx = entry->ebx;
1202 		*ecx = entry->ecx;
1203 		*edx = entry->edx;
1204 		if (function == 7 && index == 0) {
1205 			u64 data;
1206 		        if (!__kvm_get_msr(vcpu, MSR_IA32_TSX_CTRL, &data, true) &&
1207 			    (data & TSX_CTRL_CPUID_CLEAR))
1208 				*ebx &= ~(F(RTM) | F(HLE));
1209 		}
1210 	} else {
1211 		*eax = *ebx = *ecx = *edx = 0;
1212 		/*
1213 		 * When leaf 0BH or 1FH is defined, CL is pass-through
1214 		 * and EDX is always the x2APIC ID, even for undefined
1215 		 * subleaves. Index 1 will exist iff the leaf is
1216 		 * implemented, so we pass through CL iff leaf 1
1217 		 * exists. EDX can be copied from any existing index.
1218 		 */
1219 		if (function == 0xb || function == 0x1f) {
1220 			entry = kvm_find_cpuid_entry(vcpu, function, 1);
1221 			if (entry) {
1222 				*ecx = index & 0xff;
1223 				*edx = entry->edx;
1224 			}
1225 		}
1226 	}
1227 	trace_kvm_cpuid(orig_function, index, *eax, *ebx, *ecx, *edx, exact,
1228 			used_max_basic);
1229 	return exact;
1230 }
1231 EXPORT_SYMBOL_GPL(kvm_cpuid);
1232 
1233 int kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
1234 {
1235 	u32 eax, ebx, ecx, edx;
1236 
1237 	if (cpuid_fault_enabled(vcpu) && !kvm_require_cpl(vcpu, 0))
1238 		return 1;
1239 
1240 	eax = kvm_rax_read(vcpu);
1241 	ecx = kvm_rcx_read(vcpu);
1242 	kvm_cpuid(vcpu, &eax, &ebx, &ecx, &edx, false);
1243 	kvm_rax_write(vcpu, eax);
1244 	kvm_rbx_write(vcpu, ebx);
1245 	kvm_rcx_write(vcpu, ecx);
1246 	kvm_rdx_write(vcpu, edx);
1247 	return kvm_skip_emulated_instruction(vcpu);
1248 }
1249 EXPORT_SYMBOL_GPL(kvm_emulate_cpuid);
1250