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