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