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