xref: /linux/arch/x86/kvm/cpuid.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
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/lockdep.h>
15 #include <linux/export.h>
16 #include <linux/vmalloc.h>
17 #include <linux/uaccess.h>
18 #include <linux/sched/stat.h>
19 
20 #include <asm/processor.h>
21 #include <asm/user.h>
22 #include <asm/fpu/xstate.h>
23 #include <asm/sgx.h>
24 #include <asm/cpuid/api.h>
25 #include "cpuid.h"
26 #include "lapic.h"
27 #include "mmu.h"
28 #include "trace.h"
29 #include "pmu.h"
30 #include "xen.h"
31 #include "x86.h"
32 
33 /*
34  * Unlike "struct cpuinfo_x86.x86_capability", kvm_cpu_caps doesn't need to be
35  * aligned to sizeof(unsigned long) because it's not accessed via bitops.
36  */
37 u32 kvm_cpu_caps[NR_KVM_CPU_CAPS] __read_mostly;
38 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_cpu_caps);
39 
40 bool kvm_is_configuring_cpu_caps __read_mostly;
41 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_is_configuring_cpu_caps);
42 
43 struct cpuid_xstate_sizes {
44 	u32 eax;
45 	u32 ebx;
46 	u32 ecx;
47 };
48 
49 static struct cpuid_xstate_sizes xstate_sizes[XFEATURE_MAX] __ro_after_init;
50 
51 void __init kvm_init_xstate_sizes(void)
52 {
53 	u32 ign;
54 	int i;
55 
56 	for (i = XFEATURE_YMM; i < ARRAY_SIZE(xstate_sizes); i++) {
57 		struct cpuid_xstate_sizes *xs = &xstate_sizes[i];
58 
59 		cpuid_count(0xD, i, &xs->eax, &xs->ebx, &xs->ecx, &ign);
60 	}
61 }
62 
63 u32 xstate_required_size(u64 xstate_bv, bool compacted)
64 {
65 	u32 ret = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
66 	int i;
67 
68 	xstate_bv &= XFEATURE_MASK_EXTEND;
69 	for (i = XFEATURE_YMM; i < ARRAY_SIZE(xstate_sizes) && xstate_bv; i++) {
70 		struct cpuid_xstate_sizes *xs = &xstate_sizes[i];
71 		u32 offset;
72 
73 		if (!(xstate_bv & BIT_ULL(i)))
74 			continue;
75 
76 		/* ECX[1]: 64B alignment in compacted form */
77 		if (compacted)
78 			offset = (xs->ecx & 0x2) ? ALIGN(ret, 64) : ret;
79 		else
80 			offset = xs->ebx;
81 		ret = max(ret, offset + xs->eax);
82 		xstate_bv &= ~BIT_ULL(i);
83 	}
84 
85 	return ret;
86 }
87 
88 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(
89 	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
90 {
91 	struct kvm_cpuid_entry2 *e;
92 	int i;
93 
94 	/*
95 	 * KVM has a semi-arbitrary rule that querying the guest's CPUID model
96 	 * with IRQs disabled is disallowed.  The CPUID model can legitimately
97 	 * have over one hundred entries, i.e. the lookup is slow, and IRQs are
98 	 * typically disabled in KVM only when KVM is in a performance critical
99 	 * path, e.g. the core VM-Enter/VM-Exit run loop.  Nothing will break
100 	 * if this rule is violated, this assertion is purely to flag potential
101 	 * performance issues.  If this fires, consider moving the lookup out
102 	 * of the hotpath, e.g. by caching information during CPUID updates.
103 	 */
104 	lockdep_assert_irqs_enabled();
105 
106 	for (i = 0; i < nent; i++) {
107 		e = &entries[i];
108 
109 		if (e->function != function)
110 			continue;
111 
112 		/*
113 		 * If the index isn't significant, use the first entry with a
114 		 * matching function.  It's userspace's responsibility to not
115 		 * provide "duplicate" entries in all cases.
116 		 */
117 		if (!(e->flags & KVM_CPUID_FLAG_SIGNIFCANT_INDEX) || e->index == index)
118 			return e;
119 
120 
121 		/*
122 		 * Similarly, use the first matching entry if KVM is doing a
123 		 * lookup (as opposed to emulating CPUID) for a function that's
124 		 * architecturally defined as not having a significant index.
125 		 */
126 		if (index == KVM_CPUID_INDEX_NOT_SIGNIFICANT) {
127 			/*
128 			 * Direct lookups from KVM should not diverge from what
129 			 * KVM defines internally (the architectural behavior).
130 			 */
131 			WARN_ON_ONCE(cpuid_function_is_indexed(function));
132 			return e;
133 		}
134 	}
135 
136 	return NULL;
137 }
138 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_find_cpuid_entry2);
139 
140 static int kvm_check_cpuid(struct kvm_vcpu *vcpu)
141 {
142 	struct kvm_cpuid_entry2 *best;
143 	u64 xfeatures;
144 
145 	/*
146 	 * The existing code assumes virtual address is 48-bit or 57-bit in the
147 	 * canonical address checks; exit if it is ever changed.
148 	 */
149 	best = kvm_find_cpuid_entry(vcpu, 0x80000008);
150 	if (best) {
151 		int vaddr_bits = (best->eax & 0xff00) >> 8;
152 
153 		if (vaddr_bits != 48 && vaddr_bits != 57 && vaddr_bits != 0)
154 			return -EINVAL;
155 	}
156 
157 	/*
158 	 * Exposing dynamic xfeatures to the guest requires additional
159 	 * enabling in the FPU, e.g. to expand the guest XSAVE state size.
160 	 */
161 	best = kvm_find_cpuid_entry_index(vcpu, 0xd, 0);
162 	if (!best)
163 		return 0;
164 
165 	xfeatures = best->eax | ((u64)best->edx << 32);
166 	xfeatures &= XFEATURE_MASK_USER_DYNAMIC;
167 	if (!xfeatures)
168 		return 0;
169 
170 	return fpu_enable_guest_xfd_features(&vcpu->arch.guest_fpu, xfeatures);
171 }
172 
173 static u32 kvm_apply_cpuid_pv_features_quirk(struct kvm_vcpu *vcpu);
174 static void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu);
175 
176 /* Check whether the supplied CPUID data is equal to what is already set for the vCPU. */
177 static int kvm_cpuid_check_equal(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
178 				 int nent)
179 {
180 	struct kvm_cpuid_entry2 *orig;
181 	int i;
182 
183 	/*
184 	 * Apply runtime CPUID updates to the incoming CPUID entries to avoid
185 	 * false positives due mismatches on KVM-owned feature flags.
186 	 *
187 	 * Note!  @e2 and @nent track the _old_ CPUID entries!
188 	 */
189 	kvm_update_cpuid_runtime(vcpu);
190 	kvm_apply_cpuid_pv_features_quirk(vcpu);
191 
192 	if (nent != vcpu->arch.cpuid_nent)
193 		return -EINVAL;
194 
195 	for (i = 0; i < nent; i++) {
196 		orig = &vcpu->arch.cpuid_entries[i];
197 		if (e2[i].function != orig->function ||
198 		    e2[i].index != orig->index ||
199 		    e2[i].flags != orig->flags ||
200 		    e2[i].eax != orig->eax || e2[i].ebx != orig->ebx ||
201 		    e2[i].ecx != orig->ecx || e2[i].edx != orig->edx)
202 			return -EINVAL;
203 	}
204 
205 	return 0;
206 }
207 
208 static struct kvm_hypervisor_cpuid kvm_get_hypervisor_cpuid(struct kvm_vcpu *vcpu,
209 							    const char *sig)
210 {
211 	struct kvm_hypervisor_cpuid cpuid = {};
212 	struct kvm_cpuid_entry2 *entry;
213 	u32 base;
214 
215 	for_each_possible_cpuid_base_hypervisor(base) {
216 		entry = kvm_find_cpuid_entry(vcpu, base);
217 
218 		if (entry) {
219 			u32 signature[3];
220 
221 			signature[0] = entry->ebx;
222 			signature[1] = entry->ecx;
223 			signature[2] = entry->edx;
224 
225 			if (!memcmp(signature, sig, sizeof(signature))) {
226 				cpuid.base = base;
227 				cpuid.limit = entry->eax;
228 				break;
229 			}
230 		}
231 	}
232 
233 	return cpuid;
234 }
235 
236 static u32 kvm_apply_cpuid_pv_features_quirk(struct kvm_vcpu *vcpu)
237 {
238 	struct kvm_hypervisor_cpuid kvm_cpuid;
239 	struct kvm_cpuid_entry2 *best;
240 
241 	kvm_cpuid = kvm_get_hypervisor_cpuid(vcpu, KVM_SIGNATURE);
242 	if (!kvm_cpuid.base)
243 		return 0;
244 
245 	best = kvm_find_cpuid_entry(vcpu, kvm_cpuid.base | KVM_CPUID_FEATURES);
246 	if (!best)
247 		return 0;
248 
249 	if (kvm_hlt_in_guest(vcpu->kvm))
250 		best->eax &= ~(1 << KVM_FEATURE_PV_UNHALT);
251 
252 	return best->eax;
253 }
254 
255 /*
256  * Calculate guest's supported XCR0 taking into account guest CPUID data and
257  * KVM's supported XCR0 (comprised of host's XCR0 and KVM_SUPPORTED_XCR0).
258  */
259 static u64 cpuid_get_supported_xcr0(struct kvm_vcpu *vcpu)
260 {
261 	struct kvm_cpuid_entry2 *best;
262 
263 	best = kvm_find_cpuid_entry_index(vcpu, 0xd, 0);
264 	if (!best)
265 		return 0;
266 
267 	return (best->eax | ((u64)best->edx << 32)) & kvm_caps.supported_xcr0;
268 }
269 
270 static u64 cpuid_get_supported_xss(struct kvm_vcpu *vcpu)
271 {
272 	struct kvm_cpuid_entry2 *best;
273 
274 	best = kvm_find_cpuid_entry_index(vcpu, 0xd, 1);
275 	if (!best)
276 		return 0;
277 
278 	return (best->ecx | ((u64)best->edx << 32)) & kvm_caps.supported_xss;
279 }
280 
281 static __always_inline void kvm_update_feature_runtime(struct kvm_vcpu *vcpu,
282 						       struct kvm_cpuid_entry2 *entry,
283 						       unsigned int x86_feature,
284 						       bool has_feature)
285 {
286 	cpuid_entry_change(entry, x86_feature, has_feature);
287 	guest_cpu_cap_change(vcpu, x86_feature, has_feature);
288 }
289 
290 static void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu)
291 {
292 	struct kvm_cpuid_entry2 *best;
293 
294 	vcpu->arch.cpuid_dynamic_bits_dirty = false;
295 
296 	best = kvm_find_cpuid_entry(vcpu, 1);
297 	if (best) {
298 		kvm_update_feature_runtime(vcpu, best, X86_FEATURE_OSXSAVE,
299 					   kvm_is_cr4_bit_set(vcpu, X86_CR4_OSXSAVE));
300 
301 		kvm_update_feature_runtime(vcpu, best, X86_FEATURE_APIC,
302 					   vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE);
303 
304 		if (!kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT))
305 			kvm_update_feature_runtime(vcpu, best, X86_FEATURE_MWAIT,
306 						   vcpu->arch.ia32_misc_enable_msr &
307 						   MSR_IA32_MISC_ENABLE_MWAIT);
308 	}
309 
310 	best = kvm_find_cpuid_entry_index(vcpu, 7, 0);
311 	if (best)
312 		kvm_update_feature_runtime(vcpu, best, X86_FEATURE_OSPKE,
313 					   kvm_is_cr4_bit_set(vcpu, X86_CR4_PKE));
314 
315 
316 	best = kvm_find_cpuid_entry_index(vcpu, 0xD, 0);
317 	if (best)
318 		best->ebx = xstate_required_size(vcpu->arch.xcr0, false);
319 
320 	best = kvm_find_cpuid_entry_index(vcpu, 0xD, 1);
321 	if (best && (cpuid_entry_has(best, X86_FEATURE_XSAVES) ||
322 		     cpuid_entry_has(best, X86_FEATURE_XSAVEC)))
323 		best->ebx = xstate_required_size(vcpu->arch.xcr0 |
324 						 vcpu->arch.ia32_xss, true);
325 }
326 
327 static bool kvm_cpuid_has_hyperv(struct kvm_vcpu *vcpu)
328 {
329 #ifdef CONFIG_KVM_HYPERV
330 	struct kvm_cpuid_entry2 *entry;
331 
332 	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_INTERFACE);
333 	return entry && entry->eax == HYPERV_CPUID_SIGNATURE_EAX;
334 #else
335 	return false;
336 #endif
337 }
338 
339 static bool guest_cpuid_is_amd_or_hygon(struct kvm_vcpu *vcpu)
340 {
341 	struct kvm_cpuid_entry2 *entry;
342 
343 	entry = kvm_find_cpuid_entry(vcpu, 0);
344 	if (!entry)
345 		return false;
346 
347 	return is_guest_vendor_amd(entry->ebx, entry->ecx, entry->edx) ||
348 	       is_guest_vendor_hygon(entry->ebx, entry->ecx, entry->edx);
349 }
350 
351 /*
352  * This isn't truly "unsafe", but except for the cpu_caps initialization code,
353  * all register lookups should use __cpuid_entry_get_reg(), which provides
354  * compile-time validation of the input.
355  */
356 static u32 cpuid_get_reg_unsafe(struct kvm_cpuid_entry2 *entry, u32 reg)
357 {
358 	switch (reg) {
359 	case CPUID_EAX:
360 		return entry->eax;
361 	case CPUID_EBX:
362 		return entry->ebx;
363 	case CPUID_ECX:
364 		return entry->ecx;
365 	case CPUID_EDX:
366 		return entry->edx;
367 	default:
368 		WARN_ON_ONCE(1);
369 		return 0;
370 	}
371 }
372 
373 static int cpuid_func_emulated(struct kvm_cpuid_entry2 *entry, u32 func, u32 index,
374 			       bool include_partially_emulated);
375 
376 void kvm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
377 {
378 	struct kvm_lapic *apic = vcpu->arch.apic;
379 	struct kvm_cpuid_entry2 *best;
380 	struct kvm_cpuid_entry2 *entry;
381 	bool allow_gbpages;
382 	int i;
383 
384 	memset(vcpu->arch.cpu_caps, 0, sizeof(vcpu->arch.cpu_caps));
385 	BUILD_BUG_ON(ARRAY_SIZE(reverse_cpuid) != NR_KVM_CPU_CAPS);
386 
387 	/*
388 	 * Reset guest capabilities to userspace's guest CPUID definition, i.e.
389 	 * honor userspace's definition for features that don't require KVM or
390 	 * hardware management/support (or that KVM simply doesn't care about).
391 	 */
392 	for (i = 0; i < NR_KVM_CPU_CAPS; i++) {
393 		const struct cpuid_reg cpuid = reverse_cpuid[i];
394 		struct kvm_cpuid_entry2 emulated;
395 
396 		if (!cpuid.function)
397 			continue;
398 
399 		entry = kvm_find_cpuid_entry_index(vcpu, cpuid.function, cpuid.index);
400 		if (!entry)
401 			continue;
402 
403 		cpuid_func_emulated(&emulated, cpuid.function, cpuid.index, true);
404 
405 		/*
406 		 * A vCPU has a feature if it's supported by KVM and is enabled
407 		 * in guest CPUID.  Note, this includes features that are
408 		 * supported by KVM but aren't advertised to userspace!
409 		 */
410 		vcpu->arch.cpu_caps[i] = kvm_cpu_caps[i] |
411 					 cpuid_get_reg_unsafe(&emulated, cpuid.reg);
412 		vcpu->arch.cpu_caps[i] &= cpuid_get_reg_unsafe(entry, cpuid.reg);
413 	}
414 
415 	kvm_update_cpuid_runtime(vcpu);
416 
417 	/*
418 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
419 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
420 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
421 	 * walk for performance and complexity reasons.  Not to mention KVM
422 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
423 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
424 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
425 	 * If TDP is disabled, honor *only* guest CPUID as KVM has full control
426 	 * and can install smaller shadow pages if the host lacks 1GiB support.
427 	 */
428 	allow_gbpages = tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
429 				      guest_cpu_cap_has(vcpu, X86_FEATURE_GBPAGES);
430 	guest_cpu_cap_change(vcpu, X86_FEATURE_GBPAGES, allow_gbpages);
431 
432 	best = kvm_find_cpuid_entry(vcpu, 1);
433 	if (best && apic) {
434 		if (cpuid_entry_has(best, X86_FEATURE_TSC_DEADLINE_TIMER))
435 			apic->lapic_timer.timer_mode_mask = 3 << 17;
436 		else
437 			apic->lapic_timer.timer_mode_mask = 1 << 17;
438 
439 		kvm_apic_set_version(vcpu);
440 	}
441 
442 	vcpu->arch.guest_supported_xcr0 = cpuid_get_supported_xcr0(vcpu);
443 	vcpu->arch.guest_supported_xss = cpuid_get_supported_xss(vcpu);
444 
445 	vcpu->arch.pv_cpuid.features = kvm_apply_cpuid_pv_features_quirk(vcpu);
446 
447 	vcpu->arch.is_amd_compatible = guest_cpuid_is_amd_or_hygon(vcpu);
448 	vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
449 	vcpu->arch.reserved_gpa_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu);
450 
451 	kvm_pmu_refresh(vcpu);
452 
453 #define __kvm_cpu_cap_has(UNUSED_, f) kvm_cpu_cap_has(f)
454 	vcpu->arch.cr4_guest_rsvd_bits = __cr4_reserved_bits(__kvm_cpu_cap_has, UNUSED_) |
455 					 __cr4_reserved_bits(guest_cpu_cap_has, vcpu);
456 #undef __kvm_cpu_cap_has
457 
458 	kvm_hv_set_cpuid(vcpu, kvm_cpuid_has_hyperv(vcpu));
459 
460 	/* Invoke the vendor callback only after the above state is updated. */
461 	kvm_x86_call(vcpu_after_set_cpuid)(vcpu);
462 
463 	/*
464 	 * Except for the MMU, which needs to do its thing any vendor specific
465 	 * adjustments to the reserved GPA bits.
466 	 */
467 	kvm_mmu_after_set_cpuid(vcpu);
468 
469 	kvm_make_request(KVM_REQ_RECALC_INTERCEPTS, vcpu);
470 }
471 
472 int cpuid_query_maxphyaddr(struct kvm_vcpu *vcpu)
473 {
474 	struct kvm_cpuid_entry2 *best;
475 
476 	best = kvm_find_cpuid_entry(vcpu, 0x80000000);
477 	if (!best || best->eax < 0x80000008)
478 		goto not_found;
479 	best = kvm_find_cpuid_entry(vcpu, 0x80000008);
480 	if (best)
481 		return best->eax & 0xff;
482 not_found:
483 	return 36;
484 }
485 
486 int cpuid_query_maxguestphyaddr(struct kvm_vcpu *vcpu)
487 {
488 	struct kvm_cpuid_entry2 *best;
489 
490 	best = kvm_find_cpuid_entry(vcpu, 0x80000000);
491 	if (!best || best->eax < 0x80000008)
492 		goto not_found;
493 	best = kvm_find_cpuid_entry(vcpu, 0x80000008);
494 	if (best)
495 		return (best->eax >> 16) & 0xff;
496 not_found:
497 	return 0;
498 }
499 
500 /*
501  * This "raw" version returns the reserved GPA bits without any adjustments for
502  * encryption technologies that usurp bits.  The raw mask should be used if and
503  * only if hardware does _not_ strip the usurped bits, e.g. in virtual MTRRs.
504  */
505 u64 kvm_vcpu_reserved_gpa_bits_raw(struct kvm_vcpu *vcpu)
506 {
507 	return rsvd_bits(cpuid_maxphyaddr(vcpu), 63);
508 }
509 
510 static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,
511                         int nent)
512 {
513 	u32 vcpu_caps[NR_KVM_CPU_CAPS];
514 	int r;
515 
516 	/*
517 	 * Apply pending runtime CPUID updates to the current CPUID entries to
518 	 * avoid false positives due to mismatches on KVM-owned feature flags.
519 	 */
520 	if (vcpu->arch.cpuid_dynamic_bits_dirty)
521 		kvm_update_cpuid_runtime(vcpu);
522 
523 	/*
524 	 * Swap the existing (old) entries with the incoming (new) entries in
525 	 * order to massage the new entries, e.g. to account for dynamic bits
526 	 * that KVM controls, without losing the current guest CPUID, which KVM
527 	 * needs to preserve in order to unwind on failure.
528 	 *
529 	 * Similarly, save the vCPU's current cpu_caps so that the capabilities
530 	 * can be updated alongside the CPUID entries when performing runtime
531 	 * updates.  Full initialization is done if and only if the vCPU hasn't
532 	 * run, i.e. only if userspace is potentially changing CPUID features.
533 	 */
534 	swap(vcpu->arch.cpuid_entries, e2);
535 	swap(vcpu->arch.cpuid_nent, nent);
536 
537 	memcpy(vcpu_caps, vcpu->arch.cpu_caps, sizeof(vcpu_caps));
538 	BUILD_BUG_ON(sizeof(vcpu_caps) != sizeof(vcpu->arch.cpu_caps));
539 
540 	/*
541 	 * KVM does not correctly handle changing guest CPUID after KVM_RUN or
542 	 * while L2 is active, as MAXPHYADDR, GBPAGES support, AMD reserved bit
543 	 * behavior, etc. aren't tracked in kvm_mmu_page_role, and L2 state
544 	 * can't be adjusted (without breaking L2 in some way).  As a result,
545 	 * KVM may reuse SPs/SPTEs and/or run L2 with bad/misconfigured state.
546 	 *
547 	 * In practice, no sane VMM mucks with the core vCPU model on the fly.
548 	 * It would've been better to forbid any KVM_SET_CPUID{,2} calls after
549 	 * KVM_RUN or KVM_SET_NESTED_STATE altogether, but unfortunately some
550 	 * VMMs (e.g. QEMU) reuse vCPU fds for CPU hotplug/unplug and do
551 	 * KVM_SET_CPUID{,2} again. To support this legacy behavior, check
552 	 * whether the supplied CPUID data is equal to what's already set.
553 	 */
554 	if (!kvm_can_set_cpuid_and_feature_msrs(vcpu)) {
555 		r = kvm_cpuid_check_equal(vcpu, e2, nent);
556 		if (r)
557 			goto err;
558 		goto success;
559 	}
560 
561 #ifdef CONFIG_KVM_HYPERV
562 	if (kvm_cpuid_has_hyperv(vcpu)) {
563 		r = kvm_hv_vcpu_init(vcpu);
564 		if (r)
565 			goto err;
566 	}
567 #endif
568 
569 	r = kvm_check_cpuid(vcpu);
570 	if (r)
571 		goto err;
572 
573 #ifdef CONFIG_KVM_XEN
574 	vcpu->arch.xen.cpuid = kvm_get_hypervisor_cpuid(vcpu, XEN_SIGNATURE);
575 #endif
576 	kvm_vcpu_after_set_cpuid(vcpu);
577 
578 success:
579 	kvfree(e2);
580 	return 0;
581 
582 err:
583 	memcpy(vcpu->arch.cpu_caps, vcpu_caps, sizeof(vcpu_caps));
584 	swap(vcpu->arch.cpuid_entries, e2);
585 	swap(vcpu->arch.cpuid_nent, nent);
586 	return r;
587 }
588 
589 /* when an old userspace process fills a new kernel module */
590 int kvm_vcpu_ioctl_set_cpuid(struct kvm_vcpu *vcpu,
591 			     struct kvm_cpuid *cpuid,
592 			     struct kvm_cpuid_entry __user *entries)
593 {
594 	int r, i;
595 	struct kvm_cpuid_entry *e = NULL;
596 	struct kvm_cpuid_entry2 *e2 = NULL;
597 
598 	if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
599 		return -E2BIG;
600 
601 	if (cpuid->nent) {
602 		e = vmemdup_array_user(entries, cpuid->nent, sizeof(*e));
603 		if (IS_ERR(e))
604 			return PTR_ERR(e);
605 
606 		e2 = kvmalloc_objs(*e2, cpuid->nent, GFP_KERNEL_ACCOUNT);
607 		if (!e2) {
608 			r = -ENOMEM;
609 			goto out_free_cpuid;
610 		}
611 	}
612 	for (i = 0; i < cpuid->nent; i++) {
613 		e2[i].function = e[i].function;
614 		e2[i].eax = e[i].eax;
615 		e2[i].ebx = e[i].ebx;
616 		e2[i].ecx = e[i].ecx;
617 		e2[i].edx = e[i].edx;
618 		e2[i].index = 0;
619 		e2[i].flags = 0;
620 		e2[i].padding[0] = 0;
621 		e2[i].padding[1] = 0;
622 		e2[i].padding[2] = 0;
623 	}
624 
625 	r = kvm_set_cpuid(vcpu, e2, cpuid->nent);
626 	if (r)
627 		kvfree(e2);
628 
629 out_free_cpuid:
630 	kvfree(e);
631 
632 	return r;
633 }
634 
635 int kvm_vcpu_ioctl_set_cpuid2(struct kvm_vcpu *vcpu,
636 			      struct kvm_cpuid2 *cpuid,
637 			      struct kvm_cpuid_entry2 __user *entries)
638 {
639 	struct kvm_cpuid_entry2 *e2 = NULL;
640 	int r;
641 
642 	if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
643 		return -E2BIG;
644 
645 	if (cpuid->nent) {
646 		e2 = vmemdup_array_user(entries, cpuid->nent, sizeof(*e2));
647 		if (IS_ERR(e2))
648 			return PTR_ERR(e2);
649 	}
650 
651 	r = kvm_set_cpuid(vcpu, e2, cpuid->nent);
652 	if (r)
653 		kvfree(e2);
654 
655 	return r;
656 }
657 
658 int kvm_vcpu_ioctl_get_cpuid2(struct kvm_vcpu *vcpu,
659 			      struct kvm_cpuid2 *cpuid,
660 			      struct kvm_cpuid_entry2 __user *entries)
661 {
662 	if (cpuid->nent < vcpu->arch.cpuid_nent)
663 		return -E2BIG;
664 
665 	if (vcpu->arch.cpuid_dynamic_bits_dirty)
666 		kvm_update_cpuid_runtime(vcpu);
667 
668 	if (copy_to_user(entries, vcpu->arch.cpuid_entries,
669 			 vcpu->arch.cpuid_nent * sizeof(struct kvm_cpuid_entry2)))
670 		return -EFAULT;
671 
672 	cpuid->nent = vcpu->arch.cpuid_nent;
673 	return 0;
674 }
675 
676 static __always_inline u32 raw_cpuid_get(struct cpuid_reg cpuid)
677 {
678 	struct kvm_cpuid_entry2 entry;
679 	u32 base;
680 
681 	/*
682 	 * KVM only supports features defined by Intel (0x0), AMD (0x80000000),
683 	 * and Centaur (0xc0000000).  WARN if a feature for new vendor base is
684 	 * defined, as this and other code would need to be updated.
685 	 */
686 	base = cpuid.function & 0xffff0000;
687 	if (WARN_ON_ONCE(base && base != 0x80000000 && base != 0xc0000000))
688 		return 0;
689 
690 	if (cpuid_eax(base) < cpuid.function)
691 		return 0;
692 
693 	cpuid_count(cpuid.function, cpuid.index,
694 		    &entry.eax, &entry.ebx, &entry.ecx, &entry.edx);
695 
696 	return *__cpuid_entry_get_reg(&entry, cpuid.reg);
697 }
698 
699 /*
700  * For kernel-defined leafs, mask KVM's supported feature set with the kernel's
701  * capabilities as well as raw CPUID.  For KVM-defined leafs, consult only raw
702  * CPUID, as KVM is the one and only authority (in the kernel).
703  */
704 #define kvm_cpu_cap_init(leaf, feature_initializers...)			\
705 do {									\
706 	const struct cpuid_reg cpuid = x86_feature_cpuid(leaf * 32);	\
707 	const u32 __maybe_unused kvm_cpu_cap_init_in_progress = leaf;	\
708 	const u32 *kernel_cpu_caps = boot_cpu_data.x86_capability;	\
709 	u32 kvm_cpu_cap_passthrough = 0;				\
710 	u32 kvm_cpu_cap_synthesized = 0;				\
711 	u32 kvm_cpu_cap_emulated = 0;					\
712 	u32 kvm_cpu_cap_features = 0;					\
713 									\
714 	feature_initializers						\
715 									\
716 	kvm_cpu_caps[leaf] = kvm_cpu_cap_features;			\
717 									\
718 	if (leaf < NCAPINTS)						\
719 		kvm_cpu_caps[leaf] &= kernel_cpu_caps[leaf];		\
720 									\
721 	kvm_cpu_caps[leaf] |= kvm_cpu_cap_passthrough;			\
722 	kvm_cpu_caps[leaf] &= (raw_cpuid_get(cpuid) |			\
723 			       kvm_cpu_cap_synthesized);		\
724 	kvm_cpu_caps[leaf] |= kvm_cpu_cap_emulated;			\
725 } while (0)
726 
727 /*
728  * Assert that the feature bit being declared, e.g. via F(), is in the CPUID
729  * word that's being initialized.  Exempt 0x8000_0001.EDX usage of 0x1.EDX
730  * features, as AMD duplicated many 0x1.EDX features into 0x8000_0001.EDX.
731  */
732 #define KVM_VALIDATE_CPU_CAP_USAGE(name)				\
733 do {									\
734 	u32 __leaf = __feature_leaf(X86_FEATURE_##name);		\
735 									\
736 	BUILD_BUG_ON(__leaf != kvm_cpu_cap_init_in_progress);		\
737 } while (0)
738 
739 #define F(name)							\
740 ({								\
741 	KVM_VALIDATE_CPU_CAP_USAGE(name);			\
742 	kvm_cpu_cap_features |= feature_bit(name);		\
743 })
744 
745 /* Scattered Flag - For features that are scattered by cpufeatures.h. */
746 #define SCATTERED_F(name)					\
747 ({								\
748 	BUILD_BUG_ON(X86_FEATURE_##name >= MAX_CPU_FEATURES);	\
749 	KVM_VALIDATE_CPU_CAP_USAGE(name);			\
750 	if (boot_cpu_has(X86_FEATURE_##name))			\
751 		F(name);					\
752 })
753 
754 /* Features that KVM supports only on 64-bit kernels. */
755 #define X86_64_F(name)						\
756 ({								\
757 	KVM_VALIDATE_CPU_CAP_USAGE(name);			\
758 	if (IS_ENABLED(CONFIG_X86_64))				\
759 		F(name);					\
760 })
761 
762 /*
763  * Emulated Feature - For features that KVM emulates in software irrespective
764  * of host CPU/kernel support.
765  */
766 #define EMULATED_F(name)					\
767 ({								\
768 	kvm_cpu_cap_emulated |= feature_bit(name);		\
769 	F(name);						\
770 })
771 
772 /*
773  * Synthesized Feature - For features that are synthesized into boot_cpu_data,
774  * i.e. may not be present in the raw CPUID, but can still be advertised to
775  * userspace.  Primarily used for mitigation related feature flags.
776  */
777 #define SYNTHESIZED_F(name)					\
778 ({								\
779 	kvm_cpu_cap_synthesized |= feature_bit(name);		\
780 								\
781 	BUILD_BUG_ON(X86_FEATURE_##name >= MAX_CPU_FEATURES);	\
782 	if (boot_cpu_has(X86_FEATURE_##name))			\
783 		F(name);					\
784 })
785 
786 /*
787  * Passthrough Feature - For features that KVM supports based purely on raw
788  * hardware CPUID, i.e. that KVM virtualizes even if the host kernel doesn't
789  * use the feature.  Simply force set the feature in KVM's capabilities, raw
790  * CPUID support will be factored in by kvm_cpu_cap_mask().
791  */
792 #define PASSTHROUGH_F(name)					\
793 ({								\
794 	kvm_cpu_cap_passthrough |= feature_bit(name);		\
795 	F(name);						\
796 })
797 
798 /*
799  * Aliased Features - For features in 0x8000_0001.EDX that are duplicates of
800  * identical 0x1.EDX features, and thus are aliased from 0x1 to 0x8000_0001.
801  */
802 #define ALIASED_1_EDX_F(name)							\
803 ({										\
804 	BUILD_BUG_ON(__feature_leaf(X86_FEATURE_##name) != CPUID_1_EDX);	\
805 	BUILD_BUG_ON(kvm_cpu_cap_init_in_progress != CPUID_8000_0001_EDX);	\
806 	kvm_cpu_cap_features |= feature_bit(name);				\
807 })
808 
809 /*
810  * Vendor Features - For features that KVM supports, but are added in later
811  * because they require additional vendor enabling.
812  */
813 #define VENDOR_F(name)						\
814 ({								\
815 	KVM_VALIDATE_CPU_CAP_USAGE(name);			\
816 })
817 
818 /*
819  * Runtime Features - For features that KVM dynamically sets/clears at runtime,
820  * e.g. when CR4 changes, but which are never advertised to userspace.
821  */
822 #define RUNTIME_F(name)						\
823 ({								\
824 	KVM_VALIDATE_CPU_CAP_USAGE(name);			\
825 })
826 
827 /*
828  * Undefine the MSR bit macro to avoid token concatenation issues when
829  * processing X86_FEATURE_SPEC_CTRL_SSBD.
830  */
831 #undef SPEC_CTRL_SSBD
832 
833 /* DS is defined by ptrace-abi.h on 32-bit builds. */
834 #undef DS
835 
836 void kvm_initialize_cpu_caps(void)
837 {
838 	memset(kvm_cpu_caps, 0, sizeof(kvm_cpu_caps));
839 
840 	WARN_ON_ONCE(kvm_is_configuring_cpu_caps);
841 	kvm_is_configuring_cpu_caps = true;
842 
843 	BUILD_BUG_ON(sizeof(kvm_cpu_caps) - (NKVMCAPINTS * sizeof(*kvm_cpu_caps)) >
844 		     sizeof(boot_cpu_data.x86_capability));
845 
846 	kvm_cpu_cap_init(CPUID_1_ECX,
847 		F(XMM3),
848 		F(PCLMULQDQ),
849 		VENDOR_F(DTES64),
850 		/*
851 		 * NOTE: MONITOR (and MWAIT) are emulated as NOP, but *not*
852 		 * advertised to guests via CPUID!  MWAIT is also technically a
853 		 * runtime flag thanks to IA32_MISC_ENABLES; mark it as such so
854 		 * that KVM is aware that it's a known, unadvertised flag.
855 		 */
856 		RUNTIME_F(MWAIT),
857 		/* DS-CPL */
858 		VENDOR_F(VMX),
859 		/* SMX, EST */
860 		/* TM2 */
861 		F(SSSE3),
862 		/* CNXT-ID */
863 		/* Reserved */
864 		F(FMA),
865 		F(CX16),
866 		/* xTPR Update */
867 		F(PDCM),
868 		F(PCID),
869 		/* Reserved, DCA */
870 		F(XMM4_1),
871 		F(XMM4_2),
872 		EMULATED_F(X2APIC),
873 		F(MOVBE),
874 		F(POPCNT),
875 		EMULATED_F(TSC_DEADLINE_TIMER),
876 		F(AES),
877 		F(XSAVE),
878 		RUNTIME_F(OSXSAVE),
879 		F(AVX),
880 		F(F16C),
881 		F(RDRAND),
882 		EMULATED_F(HYPERVISOR),
883 	);
884 
885 	kvm_cpu_cap_init(CPUID_1_EDX,
886 		F(FPU),
887 		F(VME),
888 		F(DE),
889 		F(PSE),
890 		F(TSC),
891 		F(MSR),
892 		F(PAE),
893 		F(MCE),
894 		F(CX8),
895 		F(APIC),
896 		/* Reserved */
897 		F(SEP),
898 		F(MTRR),
899 		F(PGE),
900 		F(MCA),
901 		F(CMOV),
902 		F(PAT),
903 		F(PSE36),
904 		/* PSN */
905 		F(CLFLUSH),
906 		/* Reserved */
907 		VENDOR_F(DS),
908 		/* ACPI */
909 		F(MMX),
910 		F(FXSR),
911 		F(XMM),
912 		F(XMM2),
913 		F(SELFSNOOP),
914 		/* HTT, TM, Reserved, PBE */
915 	);
916 
917 	kvm_cpu_cap_init(CPUID_7_0_EBX,
918 		F(FSGSBASE),
919 		EMULATED_F(TSC_ADJUST),
920 		F(SGX),
921 		F(BMI1),
922 		F(HLE),
923 		F(AVX2),
924 		F(FDP_EXCPTN_ONLY),
925 		F(SMEP),
926 		F(BMI2),
927 		F(ERMS),
928 		F(INVPCID),
929 		F(RTM),
930 		F(ZERO_FCS_FDS),
931 		VENDOR_F(MPX),
932 		F(AVX512F),
933 		F(AVX512DQ),
934 		F(RDSEED),
935 		F(ADX),
936 		F(SMAP),
937 		F(AVX512IFMA),
938 		F(CLFLUSHOPT),
939 		F(CLWB),
940 		VENDOR_F(INTEL_PT),
941 		F(AVX512PF),
942 		F(AVX512ER),
943 		F(AVX512CD),
944 		F(SHA_NI),
945 		F(AVX512BW),
946 		F(AVX512VL),
947 	);
948 
949 	kvm_cpu_cap_init(CPUID_7_ECX,
950 		F(AVX512VBMI),
951 		PASSTHROUGH_F(LA57),
952 		F(PKU),
953 		RUNTIME_F(OSPKE),
954 		F(RDPID),
955 		F(AVX512_VPOPCNTDQ),
956 		F(UMIP),
957 		F(AVX512_VBMI2),
958 		F(GFNI),
959 		F(VAES),
960 		F(VPCLMULQDQ),
961 		F(AVX512_VNNI),
962 		F(AVX512_BITALG),
963 		F(CLDEMOTE),
964 		F(MOVDIRI),
965 		F(MOVDIR64B),
966 		VENDOR_F(WAITPKG),
967 		F(SGX_LC),
968 		F(BUS_LOCK_DETECT),
969 		X86_64_F(SHSTK),
970 	);
971 
972 	/*
973 	 * PKU not yet implemented for shadow paging and requires OSPKE
974 	 * to be set on the host. Clear it if that is not the case
975 	 */
976 	if (!tdp_enabled || !boot_cpu_has(X86_FEATURE_OSPKE))
977 		kvm_cpu_cap_clear(X86_FEATURE_PKU);
978 
979 	/*
980 	 * Shadow Stacks aren't implemented in the Shadow MMU.  Shadow Stack
981 	 * accesses require "magic" Writable=0,Dirty=1 protection, which KVM
982 	 * doesn't know how to emulate or map.
983 	 */
984 	if (!tdp_enabled)
985 		kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
986 
987 	kvm_cpu_cap_init(CPUID_7_EDX,
988 		F(AVX512_4VNNIW),
989 		F(AVX512_4FMAPS),
990 		F(SPEC_CTRL),
991 		F(SPEC_CTRL_SSBD),
992 		EMULATED_F(ARCH_CAPABILITIES),
993 		F(INTEL_STIBP),
994 		F(MD_CLEAR),
995 		F(AVX512_VP2INTERSECT),
996 		F(FSRM),
997 		F(SERIALIZE),
998 		F(TSXLDTRK),
999 		F(AVX512_FP16),
1000 		F(AMX_TILE),
1001 		F(AMX_INT8),
1002 		F(AMX_BF16),
1003 		F(FLUSH_L1D),
1004 		F(IBT),
1005 	);
1006 
1007 	/*
1008 	 * Disable support for IBT and SHSTK if KVM is configured to emulate
1009 	 * accesses to reserved GPAs, as KVM's emulator doesn't support IBT or
1010 	 * SHSTK, nor does KVM handle Shadow Stack #PFs (see above).
1011 	 */
1012 	if (allow_smaller_maxphyaddr) {
1013 		kvm_cpu_cap_clear(X86_FEATURE_SHSTK);
1014 		kvm_cpu_cap_clear(X86_FEATURE_IBT);
1015 	}
1016 
1017 	if (boot_cpu_has(X86_FEATURE_AMD_IBPB_RET) &&
1018 	    boot_cpu_has(X86_FEATURE_AMD_IBPB) &&
1019 	    boot_cpu_has(X86_FEATURE_AMD_IBRS))
1020 		kvm_cpu_cap_set(X86_FEATURE_SPEC_CTRL);
1021 	if (boot_cpu_has(X86_FEATURE_STIBP))
1022 		kvm_cpu_cap_set(X86_FEATURE_INTEL_STIBP);
1023 	if (boot_cpu_has(X86_FEATURE_AMD_SSBD))
1024 		kvm_cpu_cap_set(X86_FEATURE_SPEC_CTRL_SSBD);
1025 
1026 	kvm_cpu_cap_init(CPUID_7_1_EAX,
1027 		F(SHA512),
1028 		F(SM3),
1029 		F(SM4),
1030 		F(AVX_VNNI),
1031 		F(AVX512_BF16),
1032 		F(CMPCCXADD),
1033 		F(FZRM),
1034 		F(FSRS),
1035 		F(FSRC),
1036 		F(WRMSRNS),
1037 		X86_64_F(LKGS),
1038 		F(AMX_FP16),
1039 		F(AVX_IFMA),
1040 		F(LAM),
1041 		F(MOVRS),
1042 	);
1043 
1044 	kvm_cpu_cap_init(CPUID_7_1_ECX,
1045 		SCATTERED_F(MSR_IMM),
1046 	);
1047 
1048 	kvm_cpu_cap_init(CPUID_7_1_EDX,
1049 		F(AVX_VNNI_INT8),
1050 		F(AVX_NE_CONVERT),
1051 		F(AMX_COMPLEX),
1052 		F(AVX_VNNI_INT16),
1053 		F(PREFETCHITI),
1054 		F(AVX10),
1055 	);
1056 
1057 	kvm_cpu_cap_init(CPUID_7_2_EDX,
1058 		F(INTEL_PSFD),
1059 		F(IPRED_CTRL),
1060 		F(RRSBA_CTRL),
1061 		F(DDPD_U),
1062 		F(BHI_CTRL),
1063 		F(MCDT_NO),
1064 	);
1065 
1066 	kvm_cpu_cap_init(CPUID_D_1_EAX,
1067 		F(XSAVEOPT),
1068 		F(XSAVEC),
1069 		F(XGETBV1),
1070 		F(XSAVES),
1071 		X86_64_F(XFD),
1072 	);
1073 
1074 	kvm_cpu_cap_init(CPUID_12_EAX,
1075 		SCATTERED_F(SGX1),
1076 		SCATTERED_F(SGX2),
1077 		SCATTERED_F(SGX_EDECCSSA),
1078 	);
1079 
1080 	kvm_cpu_cap_init(CPUID_1E_1_EAX,
1081 		F(AMX_INT8_ALIAS),
1082 		F(AMX_BF16_ALIAS),
1083 		F(AMX_COMPLEX_ALIAS),
1084 		F(AMX_FP16_ALIAS),
1085 		F(AMX_FP8),
1086 		F(AMX_TF32),
1087 		F(AMX_AVX512),
1088 		F(AMX_MOVRS),
1089 	);
1090 
1091 	kvm_cpu_cap_init(CPUID_24_0_EBX,
1092 		F(AVX10_128),
1093 		F(AVX10_256),
1094 		F(AVX10_512),
1095 	);
1096 
1097 	kvm_cpu_cap_init(CPUID_24_1_ECX,
1098 		F(AVX10_VNNI_INT),
1099 	);
1100 
1101 	kvm_cpu_cap_init(CPUID_8000_0001_ECX,
1102 		F(LAHF_LM),
1103 		F(CMP_LEGACY),
1104 		VENDOR_F(SVM),
1105 		/* ExtApicSpace */
1106 		F(CR8_LEGACY),
1107 		F(ABM),
1108 		F(SSE4A),
1109 		F(MISALIGNSSE),
1110 		F(3DNOWPREFETCH),
1111 		F(OSVW),
1112 		/* IBS */
1113 		F(XOP),
1114 		/* SKINIT, WDT, LWP */
1115 		F(FMA4),
1116 		F(TBM),
1117 		F(TOPOEXT),
1118 		VENDOR_F(PERFCTR_CORE),
1119 	);
1120 
1121 	kvm_cpu_cap_init(CPUID_8000_0001_EDX,
1122 		ALIASED_1_EDX_F(FPU),
1123 		ALIASED_1_EDX_F(VME),
1124 		ALIASED_1_EDX_F(DE),
1125 		ALIASED_1_EDX_F(PSE),
1126 		ALIASED_1_EDX_F(TSC),
1127 		ALIASED_1_EDX_F(MSR),
1128 		ALIASED_1_EDX_F(PAE),
1129 		ALIASED_1_EDX_F(MCE),
1130 		ALIASED_1_EDX_F(CX8),
1131 		ALIASED_1_EDX_F(APIC),
1132 		/* Reserved */
1133 		F(SYSCALL),
1134 		ALIASED_1_EDX_F(MTRR),
1135 		ALIASED_1_EDX_F(PGE),
1136 		ALIASED_1_EDX_F(MCA),
1137 		ALIASED_1_EDX_F(CMOV),
1138 		ALIASED_1_EDX_F(PAT),
1139 		ALIASED_1_EDX_F(PSE36),
1140 		/* Reserved */
1141 		F(NX),
1142 		/* Reserved */
1143 		F(MMXEXT),
1144 		ALIASED_1_EDX_F(MMX),
1145 		ALIASED_1_EDX_F(FXSR),
1146 		F(FXSR_OPT),
1147 		X86_64_F(GBPAGES),
1148 		F(RDTSCP),
1149 		/* Reserved */
1150 		X86_64_F(LM),
1151 		F(3DNOWEXT),
1152 		F(3DNOW),
1153 	);
1154 
1155 	if (!tdp_enabled && IS_ENABLED(CONFIG_X86_64))
1156 		kvm_cpu_cap_set(X86_FEATURE_GBPAGES);
1157 
1158 	kvm_cpu_cap_init(CPUID_8000_0007_EDX,
1159 		SCATTERED_F(CONSTANT_TSC),
1160 	);
1161 
1162 	kvm_cpu_cap_init(CPUID_8000_0008_EBX,
1163 		F(CLZERO),
1164 		F(XSAVEERPTR),
1165 		F(WBNOINVD),
1166 		F(AMD_IBPB),
1167 		F(AMD_IBRS),
1168 		F(AMD_SSBD),
1169 		F(VIRT_SSBD),
1170 		F(AMD_SSB_NO),
1171 		F(AMD_STIBP),
1172 		F(AMD_STIBP_ALWAYS_ON),
1173 		F(AMD_IBRS_SAME_MODE),
1174 		PASSTHROUGH_F(EFER_LMSLE_MBZ),
1175 		F(AMD_PSFD),
1176 		F(AMD_IBPB_RET),
1177 	);
1178 
1179 	/*
1180 	 * AMD has separate bits for each SPEC_CTRL bit.
1181 	 * arch/x86/kernel/cpu/bugs.c is kind enough to
1182 	 * record that in cpufeatures so use them.
1183 	 */
1184 	if (boot_cpu_has(X86_FEATURE_IBPB)) {
1185 		kvm_cpu_cap_set(X86_FEATURE_AMD_IBPB);
1186 		if (boot_cpu_has(X86_FEATURE_SPEC_CTRL) &&
1187 		    !boot_cpu_has_bug(X86_BUG_EIBRS_PBRSB))
1188 			kvm_cpu_cap_set(X86_FEATURE_AMD_IBPB_RET);
1189 	}
1190 	if (boot_cpu_has(X86_FEATURE_IBRS))
1191 		kvm_cpu_cap_set(X86_FEATURE_AMD_IBRS);
1192 	if (boot_cpu_has(X86_FEATURE_STIBP))
1193 		kvm_cpu_cap_set(X86_FEATURE_AMD_STIBP);
1194 	if (boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD))
1195 		kvm_cpu_cap_set(X86_FEATURE_AMD_SSBD);
1196 	if (!boot_cpu_has_bug(X86_BUG_SPEC_STORE_BYPASS))
1197 		kvm_cpu_cap_set(X86_FEATURE_AMD_SSB_NO);
1198 	/*
1199 	 * The preference is to use SPEC CTRL MSR instead of the
1200 	 * VIRT_SPEC MSR.
1201 	 */
1202 	if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) &&
1203 	    !boot_cpu_has(X86_FEATURE_AMD_SSBD))
1204 		kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
1205 
1206 	/* All SVM features required additional vendor module enabling. */
1207 	kvm_cpu_cap_init(CPUID_8000_000A_EDX,
1208 		VENDOR_F(NPT),
1209 		VENDOR_F(VMCBCLEAN),
1210 		VENDOR_F(FLUSHBYASID),
1211 		VENDOR_F(NRIPS),
1212 		VENDOR_F(TSCRATEMSR),
1213 		VENDOR_F(V_VMSAVE_VMLOAD),
1214 		VENDOR_F(LBRV),
1215 		VENDOR_F(PAUSEFILTER),
1216 		VENDOR_F(PFTHRESHOLD),
1217 		VENDOR_F(VGIF),
1218 		VENDOR_F(VNMI),
1219 		VENDOR_F(SVME_ADDR_CHK),
1220 	);
1221 
1222 	kvm_cpu_cap_init(CPUID_8000_001F_EAX,
1223 		VENDOR_F(SME),
1224 		VENDOR_F(SEV),
1225 		/* VM_PAGE_FLUSH */
1226 		VENDOR_F(SEV_ES),
1227 		F(SME_COHERENT),
1228 	);
1229 
1230 	kvm_cpu_cap_init(CPUID_8000_0021_EAX,
1231 		F(NO_NESTED_DATA_BP),
1232 		F(WRMSR_XX_BASE_NS),
1233 		/*
1234 		 * Synthesize "LFENCE is serializing" into the AMD-defined entry
1235 		 * in KVM's supported CPUID, i.e. if the feature is reported as
1236 		 * supported by the kernel.  LFENCE_RDTSC was a Linux-defined
1237 		 * synthetic feature long before AMD joined the bandwagon, e.g.
1238 		 * LFENCE is serializing on most CPUs that support SSE2.  On
1239 		 * CPUs that don't support AMD's leaf, ANDing with the raw host
1240 		 * CPUID will drop the flags, and reporting support in AMD's
1241 		 * leaf can make it easier for userspace to detect the feature.
1242 		 */
1243 		SYNTHESIZED_F(LFENCE_RDTSC),
1244 		/* SmmPgCfgLock */
1245 		/* 4: Resv */
1246 		SYNTHESIZED_F(VERW_CLEAR),
1247 		F(NULL_SEL_CLR_BASE),
1248 		/* UpperAddressIgnore */
1249 		F(AUTOIBRS),
1250 		EMULATED_F(NO_SMM_CTL_MSR),
1251 		/* PrefetchCtlMsr */
1252 		EMULATED_F(GP_ON_USER_CPUID),
1253 		/* EPSF */
1254 		F(PREFETCHI),
1255 		F(AVX512_BMM),
1256 		F(ERAPS),
1257 		SYNTHESIZED_F(SBPB),
1258 		SYNTHESIZED_F(IBPB_BRTYPE),
1259 		SYNTHESIZED_F(SRSO_NO),
1260 		F(SRSO_USER_KERNEL_NO),
1261 	);
1262 
1263 	kvm_cpu_cap_init(CPUID_8000_0021_ECX,
1264 		SYNTHESIZED_F(TSA_SQ_NO),
1265 		SYNTHESIZED_F(TSA_L1_NO),
1266 	);
1267 
1268 	kvm_cpu_cap_init(CPUID_8000_0022_EAX,
1269 		F(PERFMON_V2),
1270 	);
1271 
1272 	if (!static_cpu_has_bug(X86_BUG_NULL_SEG))
1273 		kvm_cpu_cap_set(X86_FEATURE_NULL_SEL_CLR_BASE);
1274 
1275 	kvm_cpu_cap_init(CPUID_C000_0001_EDX,
1276 		F(SM2),
1277 		F(SM2_EN),
1278 		F(XSTORE),
1279 		F(XSTORE_EN),
1280 		F(CCS),
1281 		F(CCS_EN),
1282 		F(XCRYPT),
1283 		F(XCRYPT_EN),
1284 		F(ACE2),
1285 		F(ACE2_EN),
1286 		F(PHE),
1287 		F(PHE_EN),
1288 		F(PMM),
1289 		F(PMM_EN),
1290 		F(RNG2),
1291 		F(RNG2_EN),
1292 		F(PHE2),
1293 		F(PHE2_EN),
1294 		F(RSA),
1295 		F(RSA_EN),
1296 	);
1297 
1298 	/*
1299 	 * Hide RDTSCP and RDPID if either feature is reported as supported but
1300 	 * probing MSR_TSC_AUX failed.  This is purely a sanity check and
1301 	 * should never happen, but the guest will likely crash if RDTSCP or
1302 	 * RDPID is misreported, and KVM has botched MSR_TSC_AUX emulation in
1303 	 * the past.  For example, the sanity check may fire if this instance of
1304 	 * KVM is running as L1 on top of an older, broken KVM.
1305 	 */
1306 	if (WARN_ON((kvm_cpu_cap_has(X86_FEATURE_RDTSCP) ||
1307 		     kvm_cpu_cap_has(X86_FEATURE_RDPID)) &&
1308 		     !kvm_is_supported_user_return_msr(MSR_TSC_AUX))) {
1309 		kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
1310 		kvm_cpu_cap_clear(X86_FEATURE_RDPID);
1311 	}
1312 }
1313 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_initialize_cpu_caps);
1314 
1315 #undef F
1316 #undef SCATTERED_F
1317 #undef X86_64_F
1318 #undef EMULATED_F
1319 #undef SYNTHESIZED_F
1320 #undef PASSTHROUGH_F
1321 #undef ALIASED_1_EDX_F
1322 #undef VENDOR_F
1323 #undef RUNTIME_F
1324 
1325 struct kvm_cpuid_array {
1326 	struct kvm_cpuid_entry2 *entries;
1327 	int maxnent;
1328 	int nent;
1329 };
1330 
1331 static struct kvm_cpuid_entry2 *get_next_cpuid(struct kvm_cpuid_array *array)
1332 {
1333 	if (array->nent >= array->maxnent)
1334 		return NULL;
1335 
1336 	return &array->entries[array->nent++];
1337 }
1338 
1339 static struct kvm_cpuid_entry2 *do_host_cpuid(struct kvm_cpuid_array *array,
1340 					      u32 function, u32 index)
1341 {
1342 	struct kvm_cpuid_entry2 *entry = get_next_cpuid(array);
1343 
1344 	if (!entry)
1345 		return NULL;
1346 
1347 	memset(entry, 0, sizeof(*entry));
1348 	entry->function = function;
1349 	entry->index = index;
1350 	switch (function & 0xC0000000) {
1351 	case 0x40000000:
1352 		/* Hypervisor leaves are always synthesized by __do_cpuid_func.  */
1353 		return entry;
1354 
1355 	case 0x80000000:
1356 		/*
1357 		 * 0x80000021 is sometimes synthesized by __do_cpuid_func, which
1358 		 * would result in out-of-bounds calls to do_host_cpuid.
1359 		 */
1360 		{
1361 			static int max_cpuid_80000000;
1362 			if (!READ_ONCE(max_cpuid_80000000))
1363 				WRITE_ONCE(max_cpuid_80000000, cpuid_eax(0x80000000));
1364 			if (function > READ_ONCE(max_cpuid_80000000))
1365 				return entry;
1366 		}
1367 		break;
1368 
1369 	default:
1370 		break;
1371 	}
1372 
1373 	cpuid_count(entry->function, entry->index,
1374 		    &entry->eax, &entry->ebx, &entry->ecx, &entry->edx);
1375 
1376 	if (cpuid_function_is_indexed(function))
1377 		entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1378 
1379 	return entry;
1380 }
1381 
1382 static int cpuid_func_emulated(struct kvm_cpuid_entry2 *entry, u32 func, u32 index,
1383 			       bool include_partially_emulated)
1384 {
1385 	memset(entry, 0, sizeof(*entry));
1386 
1387 	/* KVM doesn't currently emulate any non-zero indices. */
1388 	if (cpuid_function_is_indexed(func) && index)
1389 		return 0;
1390 
1391 	entry->function = func;
1392 	entry->index = 0;
1393 	entry->flags = 0;
1394 
1395 	switch (func) {
1396 	case 0:
1397 		entry->eax = 7;
1398 		return 1;
1399 	case 1:
1400 		entry->ecx = feature_bit(MOVBE);
1401 		/*
1402 		 * KVM allows userspace to enumerate MONITOR+MWAIT support to
1403 		 * the guest, but the MWAIT feature flag is never advertised
1404 		 * to userspace because MONITOR+MWAIT aren't virtualized by
1405 		 * hardware, can't be faithfully emulated in software (KVM
1406 		 * emulates them as NOPs), and allowing the guest to execute
1407 		 * them natively requires enabling a per-VM capability.
1408 		 */
1409 		if (include_partially_emulated)
1410 			entry->ecx |= feature_bit(MWAIT);
1411 		return 1;
1412 	case 7:
1413 		entry->flags |= KVM_CPUID_FLAG_SIGNIFCANT_INDEX;
1414 		entry->eax = 0;
1415 		if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP))
1416 			entry->ecx = feature_bit(RDPID);
1417 		return 1;
1418 	default:
1419 		return 0;
1420 	}
1421 }
1422 
1423 static int __do_cpuid_func_emulated(struct kvm_cpuid_array *array, u32 func)
1424 {
1425 	if (array->nent >= array->maxnent)
1426 		return -E2BIG;
1427 
1428 	array->nent += cpuid_func_emulated(&array->entries[array->nent], func, 0, false);
1429 	return 0;
1430 }
1431 
1432 static inline int __do_cpuid_func(struct kvm_cpuid_array *array, u32 function)
1433 {
1434 	struct kvm_cpuid_entry2 *entry;
1435 	int r, i, max_idx;
1436 
1437 	/* all calls to cpuid_count() should be made on the same cpu */
1438 	get_cpu();
1439 
1440 	r = -E2BIG;
1441 
1442 	entry = do_host_cpuid(array, function, 0);
1443 	if (!entry)
1444 		goto out;
1445 
1446 	switch (function) {
1447 	case 0:
1448 		/* Limited to the highest leaf implemented in KVM. */
1449 		entry->eax = min(entry->eax, 0x24U);
1450 		break;
1451 	case 1:
1452 		cpuid_entry_override(entry, CPUID_1_EDX);
1453 		cpuid_entry_override(entry, CPUID_1_ECX);
1454 		break;
1455 	case 2:
1456 		/*
1457 		 * On ancient CPUs, function 2 entries are STATEFUL.  That is,
1458 		 * CPUID(function=2, index=0) may return different results each
1459 		 * time, with the least-significant byte in EAX enumerating the
1460 		 * number of times software should do CPUID(2, 0).
1461 		 *
1462 		 * Modern CPUs, i.e. every CPU KVM has *ever* run on are less
1463 		 * idiotic.  Intel's SDM states that EAX & 0xff "will always
1464 		 * return 01H. Software should ignore this value and not
1465 		 * interpret it as an informational descriptor", while AMD's
1466 		 * APM states that CPUID(2) is reserved.
1467 		 *
1468 		 * WARN if a frankenstein CPU that supports virtualization and
1469 		 * a stateful CPUID.0x2 is encountered.
1470 		 */
1471 		WARN_ON_ONCE((entry->eax & 0xff) > 1);
1472 		break;
1473 	/* functions 4 and 0x8000001d have additional index. */
1474 	case 4:
1475 	case 0x8000001d:
1476 		/*
1477 		 * Read entries until the cache type in the previous entry is
1478 		 * zero, i.e. indicates an invalid entry.
1479 		 */
1480 		for (i = 1; entry->eax & 0x1f; ++i) {
1481 			entry = do_host_cpuid(array, function, i);
1482 			if (!entry)
1483 				goto out;
1484 		}
1485 		break;
1486 	case 6: /* Thermal management */
1487 		entry->eax = 0x4; /* allow ARAT */
1488 		entry->ebx = 0;
1489 		entry->ecx = 0;
1490 		entry->edx = 0;
1491 		break;
1492 	/* function 7 has additional index. */
1493 	case 7:
1494 		max_idx = entry->eax = min(entry->eax, 2u);
1495 		cpuid_entry_override(entry, CPUID_7_0_EBX);
1496 		cpuid_entry_override(entry, CPUID_7_ECX);
1497 		cpuid_entry_override(entry, CPUID_7_EDX);
1498 
1499 		/* KVM only supports up to 0x7.2, capped above via min(). */
1500 		if (max_idx >= 1) {
1501 			entry = do_host_cpuid(array, function, 1);
1502 			if (!entry)
1503 				goto out;
1504 
1505 			cpuid_entry_override(entry, CPUID_7_1_EAX);
1506 			cpuid_entry_override(entry, CPUID_7_1_ECX);
1507 			cpuid_entry_override(entry, CPUID_7_1_EDX);
1508 			entry->ebx = 0;
1509 		}
1510 		if (max_idx >= 2) {
1511 			entry = do_host_cpuid(array, function, 2);
1512 			if (!entry)
1513 				goto out;
1514 
1515 			cpuid_entry_override(entry, CPUID_7_2_EDX);
1516 			entry->ecx = 0;
1517 			entry->ebx = 0;
1518 			entry->eax = 0;
1519 		}
1520 		break;
1521 	case 0xa: { /* Architectural Performance Monitoring */
1522 		union cpuid10_eax eax = { };
1523 		union cpuid10_edx edx = { };
1524 
1525 		if (!enable_pmu || !cpu_feature_enabled(X86_FEATURE_ARCH_PERFMON)) {
1526 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1527 			break;
1528 		}
1529 
1530 		eax.split.version_id = kvm_pmu_cap.version;
1531 		eax.split.num_counters = kvm_pmu_cap.num_counters_gp;
1532 		eax.split.bit_width = kvm_pmu_cap.bit_width_gp;
1533 		eax.split.mask_length = kvm_pmu_cap.events_mask_len;
1534 		edx.split.num_counters_fixed = kvm_pmu_cap.num_counters_fixed;
1535 		edx.split.bit_width_fixed = kvm_pmu_cap.bit_width_fixed;
1536 
1537 		if (kvm_pmu_cap.version)
1538 			edx.split.anythread_deprecated = 1;
1539 
1540 		entry->eax = eax.full;
1541 		entry->ebx = kvm_pmu_cap.events_mask;
1542 		entry->ecx = 0;
1543 		entry->edx = edx.full;
1544 		break;
1545 	}
1546 	case 0x1f:
1547 	case 0xb:
1548 		/*
1549 		 * No topology; a valid topology is indicated by the presence
1550 		 * of subleaf 1.
1551 		 */
1552 		entry->eax = entry->ebx = entry->ecx = 0;
1553 		break;
1554 	case 0xd: {
1555 		u64 permitted_xcr0 = kvm_get_filtered_xcr0();
1556 		u64 permitted_xss = kvm_caps.supported_xss;
1557 
1558 		entry->eax &= permitted_xcr0;
1559 		entry->ebx = xstate_required_size(permitted_xcr0, false);
1560 		entry->ecx = entry->ebx;
1561 		entry->edx &= permitted_xcr0 >> 32;
1562 		if (!permitted_xcr0)
1563 			break;
1564 
1565 		entry = do_host_cpuid(array, function, 1);
1566 		if (!entry)
1567 			goto out;
1568 
1569 		cpuid_entry_override(entry, CPUID_D_1_EAX);
1570 		if (entry->eax & (feature_bit(XSAVES) | feature_bit(XSAVEC)))
1571 			entry->ebx = xstate_required_size(permitted_xcr0 | permitted_xss,
1572 							  true);
1573 		else {
1574 			WARN_ON_ONCE(permitted_xss != 0);
1575 			entry->ebx = 0;
1576 		}
1577 		entry->ecx &= permitted_xss;
1578 		entry->edx &= permitted_xss >> 32;
1579 
1580 		for (i = 2; i < 64; ++i) {
1581 			bool s_state;
1582 			if (permitted_xcr0 & BIT_ULL(i))
1583 				s_state = false;
1584 			else if (permitted_xss & BIT_ULL(i))
1585 				s_state = true;
1586 			else
1587 				continue;
1588 
1589 			entry = do_host_cpuid(array, function, i);
1590 			if (!entry)
1591 				goto out;
1592 
1593 			/*
1594 			 * The supported check above should have filtered out
1595 			 * invalid sub-leafs.  Only valid sub-leafs should
1596 			 * reach this point, and they should have a non-zero
1597 			 * save state size.  Furthermore, check whether the
1598 			 * processor agrees with permitted_xcr0/permitted_xss
1599 			 * on whether this is an XCR0- or IA32_XSS-managed area.
1600 			 */
1601 			if (WARN_ON_ONCE(!entry->eax || (entry->ecx & 0x1) != s_state)) {
1602 				--array->nent;
1603 				continue;
1604 			}
1605 
1606 			if (!kvm_cpu_cap_has(X86_FEATURE_XFD))
1607 				entry->ecx &= ~BIT_ULL(2);
1608 			entry->edx = 0;
1609 		}
1610 		break;
1611 	}
1612 	case 0x12:
1613 		/* Intel SGX */
1614 		if (!kvm_cpu_cap_has(X86_FEATURE_SGX)) {
1615 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1616 			break;
1617 		}
1618 
1619 		/*
1620 		 * Index 0: Sub-features, MISCSELECT (a.k.a extended features)
1621 		 * and max enclave sizes.   The SGX sub-features and MISCSELECT
1622 		 * are restricted by kernel and KVM capabilities (like most
1623 		 * feature flags), while enclave size is unrestricted.
1624 		 */
1625 		cpuid_entry_override(entry, CPUID_12_EAX);
1626 		entry->ebx &= SGX_MISC_EXINFO;
1627 
1628 		entry = do_host_cpuid(array, function, 1);
1629 		if (!entry)
1630 			goto out;
1631 
1632 		/*
1633 		 * Index 1: SECS.ATTRIBUTES.  ATTRIBUTES are restricted a la
1634 		 * feature flags.  Advertise all supported flags, including
1635 		 * privileged attributes that require explicit opt-in from
1636 		 * userspace.  ATTRIBUTES.XFRM is not adjusted as userspace is
1637 		 * expected to derive it from supported XCR0.
1638 		 */
1639 		entry->eax &= SGX_ATTR_PRIV_MASK | SGX_ATTR_UNPRIV_MASK;
1640 		entry->ebx &= 0;
1641 		break;
1642 	/* Intel PT */
1643 	case 0x14:
1644 		if (!kvm_cpu_cap_has(X86_FEATURE_INTEL_PT)) {
1645 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1646 			break;
1647 		}
1648 
1649 		for (i = 1, max_idx = entry->eax; i <= max_idx; ++i) {
1650 			if (!do_host_cpuid(array, function, i))
1651 				goto out;
1652 		}
1653 		break;
1654 	/* Intel AMX TILE */
1655 	case 0x1d:
1656 		if (!kvm_cpu_cap_has(X86_FEATURE_AMX_TILE)) {
1657 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1658 			break;
1659 		}
1660 
1661 		for (i = 1, max_idx = entry->eax; i <= max_idx; ++i) {
1662 			if (!do_host_cpuid(array, function, i))
1663 				goto out;
1664 		}
1665 		break;
1666 	case 0x1e: /* TMUL information */
1667 		if (!kvm_cpu_cap_has(X86_FEATURE_AMX_TILE)) {
1668 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1669 			break;
1670 		}
1671 
1672 		max_idx = entry->eax = min(entry->eax, 1u);
1673 
1674 		/* KVM only supports up to 0x1e.0x1, capped above via min(). */
1675 		if (max_idx >= 1) {
1676 			entry = do_host_cpuid(array, function, 1);
1677 			if (!entry)
1678 				goto out;
1679 
1680 			cpuid_entry_override(entry, CPUID_1E_1_EAX);
1681 			entry->ebx = 0;
1682 			entry->ecx = 0;
1683 			entry->edx = 0;
1684 		}
1685 		break;
1686 	case 0x24: {
1687 		u8 avx10_version;
1688 
1689 		if (!kvm_cpu_cap_has(X86_FEATURE_AVX10)) {
1690 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1691 			break;
1692 		}
1693 
1694 		max_idx = entry->eax = min(entry->eax, 1u);
1695 		/*
1696 		 * The AVX10 version is encoded in EBX[7:0].  Note, the version
1697 		 * is guaranteed to be >=1 if AVX10 is supported.  Note #2, the
1698 		 * version needs to be captured before overriding EBX features!
1699 		 */
1700 		avx10_version = min_t(u8, entry->ebx & 0xff, 2);
1701 		cpuid_entry_override(entry, CPUID_24_0_EBX);
1702 		entry->ebx |= avx10_version;
1703 
1704 		entry->ecx = 0;
1705 		entry->edx = 0;
1706 
1707 		/* KVM only supports up to 0x24.0x1, capped above via min(). */
1708 		if (max_idx >= 1) {
1709 			entry = do_host_cpuid(array, function, 1);
1710 			if (!entry)
1711 				goto out;
1712 
1713 			cpuid_entry_override(entry, CPUID_24_1_ECX);
1714 			entry->eax = 0;
1715 			entry->ebx = 0;
1716 			entry->edx = 0;
1717 		}
1718 		break;
1719 	}
1720 	case KVM_CPUID_SIGNATURE: {
1721 		const u32 *sigptr = (const u32 *)KVM_SIGNATURE;
1722 		entry->eax = KVM_CPUID_FEATURES;
1723 		entry->ebx = sigptr[0];
1724 		entry->ecx = sigptr[1];
1725 		entry->edx = sigptr[2];
1726 		break;
1727 	}
1728 	case KVM_CPUID_FEATURES:
1729 		entry->eax = (1 << KVM_FEATURE_CLOCKSOURCE) |
1730 			     (1 << KVM_FEATURE_NOP_IO_DELAY) |
1731 			     (1 << KVM_FEATURE_CLOCKSOURCE2) |
1732 			     (1 << KVM_FEATURE_ASYNC_PF) |
1733 			     (1 << KVM_FEATURE_PV_EOI) |
1734 			     (1 << KVM_FEATURE_CLOCKSOURCE_STABLE_BIT) |
1735 			     (1 << KVM_FEATURE_PV_UNHALT) |
1736 			     (1 << KVM_FEATURE_PV_TLB_FLUSH) |
1737 			     (1 << KVM_FEATURE_ASYNC_PF_VMEXIT) |
1738 			     (1 << KVM_FEATURE_PV_SEND_IPI) |
1739 			     (1 << KVM_FEATURE_POLL_CONTROL) |
1740 			     (1 << KVM_FEATURE_PV_SCHED_YIELD) |
1741 			     (1 << KVM_FEATURE_ASYNC_PF_INT);
1742 
1743 		if (sched_info_on())
1744 			entry->eax |= (1 << KVM_FEATURE_STEAL_TIME);
1745 
1746 		entry->ebx = 0;
1747 		entry->ecx = 0;
1748 		entry->edx = 0;
1749 		break;
1750 	case 0x80000000:
1751 		entry->eax = min(entry->eax, 0x80000022);
1752 		/*
1753 		 * Serializing LFENCE is reported in a multitude of ways, and
1754 		 * NullSegClearsBase is not reported in CPUID on Zen2; help
1755 		 * userspace by providing the CPUID leaf ourselves.
1756 		 *
1757 		 * However, only do it if the host has CPUID leaf 0x8000001d.
1758 		 * QEMU thinks that it can query the host blindly for that
1759 		 * CPUID leaf if KVM reports that it supports 0x8000001d or
1760 		 * above.  The processor merrily returns values from the
1761 		 * highest Intel leaf which QEMU tries to use as the guest's
1762 		 * 0x8000001d.  Even worse, this can result in an infinite
1763 		 * loop if said highest leaf has no subleaves indexed by ECX.
1764 		 */
1765 		if (entry->eax >= 0x8000001d &&
1766 		    (cpu_feature_enabled(X86_FEATURE_LFENCE_RDTSC)
1767 		     || !static_cpu_has_bug(X86_BUG_NULL_SEG)))
1768 			entry->eax = max(entry->eax, 0x80000021);
1769 		break;
1770 	case 0x80000001:
1771 		entry->ebx &= ~GENMASK(27, 16);
1772 		cpuid_entry_override(entry, CPUID_8000_0001_EDX);
1773 		cpuid_entry_override(entry, CPUID_8000_0001_ECX);
1774 		break;
1775 	case 0x80000005:
1776 		/*  Pass host L1 cache and TLB info. */
1777 		break;
1778 	case 0x80000006:
1779 		/* Drop reserved bits, pass host L2 cache and TLB info. */
1780 		entry->edx &= ~GENMASK(17, 16);
1781 		break;
1782 	case 0x80000007: /* Advanced power management */
1783 		cpuid_entry_override(entry, CPUID_8000_0007_EDX);
1784 
1785 		/* mask against host */
1786 		entry->edx &= boot_cpu_data.x86_power;
1787 		entry->eax = entry->ebx = entry->ecx = 0;
1788 		break;
1789 	case 0x80000008: {
1790 		/*
1791 		 * GuestPhysAddrSize (EAX[23:16]) is intended for software
1792 		 * use.
1793 		 *
1794 		 * KVM's ABI is to report the effective MAXPHYADDR for the
1795 		 * guest in PhysAddrSize (phys_as), and the maximum
1796 		 * *addressable* GPA in GuestPhysAddrSize (g_phys_as).
1797 		 *
1798 		 * GuestPhysAddrSize is valid if and only if TDP is enabled,
1799 		 * in which case the max GPA that can be addressed by KVM may
1800 		 * be less than the max GPA that can be legally generated by
1801 		 * the guest, e.g. if MAXPHYADDR>48 but the CPU doesn't
1802 		 * support 5-level TDP.
1803 		 */
1804 		unsigned int virt_as = max((entry->eax >> 8) & 0xff, 48U);
1805 		unsigned int phys_as, g_phys_as;
1806 
1807 		/*
1808 		 * If TDP (NPT) is disabled use the adjusted host MAXPHYADDR as
1809 		 * the guest operates in the same PA space as the host, i.e.
1810 		 * reductions in MAXPHYADDR for memory encryption affect shadow
1811 		 * paging, too.
1812 		 *
1813 		 * If TDP is enabled, use the raw bare metal MAXPHYADDR as
1814 		 * reductions to the HPAs do not affect GPAs.  The max
1815 		 * addressable GPA is the same as the max effective GPA, except
1816 		 * that it's capped at 48 bits if 5-level TDP isn't supported
1817 		 * (hardware processes bits 51:48 only when walking the fifth
1818 		 * level page table).
1819 		 */
1820 		if (!tdp_enabled) {
1821 			phys_as = boot_cpu_data.x86_phys_bits;
1822 			g_phys_as = 0;
1823 		} else {
1824 			phys_as = entry->eax & 0xff;
1825 			g_phys_as = phys_as;
1826 			if (kvm_mmu_get_max_tdp_level() < 5)
1827 				g_phys_as = min(g_phys_as, 48U);
1828 		}
1829 
1830 		entry->eax = phys_as | (virt_as << 8) | (g_phys_as << 16);
1831 		entry->ecx &= ~(GENMASK(31, 16) | GENMASK(11, 8));
1832 		entry->edx = 0;
1833 		cpuid_entry_override(entry, CPUID_8000_0008_EBX);
1834 		break;
1835 	}
1836 	case 0x8000000A:
1837 		if (!kvm_cpu_cap_has(X86_FEATURE_SVM)) {
1838 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1839 			break;
1840 		}
1841 		entry->eax = 1; /* SVM revision 1 */
1842 		entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
1843 				   ASID emulation to nested SVM */
1844 		entry->ecx = 0; /* Reserved */
1845 		cpuid_entry_override(entry, CPUID_8000_000A_EDX);
1846 		break;
1847 	case 0x80000019:
1848 		entry->ecx = entry->edx = 0;
1849 		break;
1850 	case 0x8000001a:
1851 		entry->eax &= GENMASK(2, 0);
1852 		entry->ebx = entry->ecx = entry->edx = 0;
1853 		break;
1854 	case 0x8000001e:
1855 		/* Do not return host topology information.  */
1856 		entry->eax = entry->ebx = entry->ecx = 0;
1857 		entry->edx = 0; /* reserved */
1858 		break;
1859 	case 0x8000001F:
1860 		if (!kvm_cpu_cap_has(X86_FEATURE_SEV)) {
1861 			entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1862 		} else {
1863 			cpuid_entry_override(entry, CPUID_8000_001F_EAX);
1864 			/* Clear NumVMPL since KVM does not support VMPL.  */
1865 			entry->ebx &= ~GENMASK(31, 12);
1866 			/*
1867 			 * Enumerate '0' for "PA bits reduction", the adjusted
1868 			 * MAXPHYADDR is enumerated directly (see 0x80000008).
1869 			 */
1870 			entry->ebx &= ~GENMASK(11, 6);
1871 		}
1872 		break;
1873 	case 0x80000020:
1874 		entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1875 		break;
1876 	case 0x80000021:
1877 		entry->edx = 0;
1878 		cpuid_entry_override(entry, CPUID_8000_0021_EAX);
1879 
1880 		if (kvm_cpu_cap_has(X86_FEATURE_ERAPS))
1881 			entry->ebx &= GENMASK(23, 16);
1882 		else
1883 			entry->ebx = 0;
1884 
1885 		cpuid_entry_override(entry, CPUID_8000_0021_ECX);
1886 		break;
1887 	/* AMD Extended Performance Monitoring and Debug */
1888 	case 0x80000022: {
1889 		union cpuid_0x80000022_ebx ebx = { };
1890 
1891 		entry->ecx = entry->edx = 0;
1892 		if (!enable_pmu || !kvm_cpu_cap_has(X86_FEATURE_PERFMON_V2)) {
1893 			entry->eax = entry->ebx = 0;
1894 			break;
1895 		}
1896 
1897 		cpuid_entry_override(entry, CPUID_8000_0022_EAX);
1898 
1899 		ebx.split.num_core_pmc = kvm_pmu_cap.num_counters_gp;
1900 		entry->ebx = ebx.full;
1901 		break;
1902 	}
1903 	/*Add support for Centaur's CPUID instruction*/
1904 	case 0xC0000000:
1905 		/*Just support up to 0xC0000004 now*/
1906 		entry->eax = min(entry->eax, 0xC0000004);
1907 		break;
1908 	case 0xC0000001:
1909 		cpuid_entry_override(entry, CPUID_C000_0001_EDX);
1910 		break;
1911 	case 3: /* Processor serial number */
1912 	case 5: /* MONITOR/MWAIT */
1913 	case 0xC0000002:
1914 	case 0xC0000003:
1915 	case 0xC0000004:
1916 	default:
1917 		entry->eax = entry->ebx = entry->ecx = entry->edx = 0;
1918 		break;
1919 	}
1920 
1921 	r = 0;
1922 
1923 out:
1924 	put_cpu();
1925 
1926 	return r;
1927 }
1928 
1929 static int do_cpuid_func(struct kvm_cpuid_array *array, u32 func,
1930 			 unsigned int type)
1931 {
1932 	if (type == KVM_GET_EMULATED_CPUID)
1933 		return __do_cpuid_func_emulated(array, func);
1934 
1935 	return __do_cpuid_func(array, func);
1936 }
1937 
1938 #define CENTAUR_CPUID_SIGNATURE 0xC0000000
1939 
1940 static int get_cpuid_func(struct kvm_cpuid_array *array, u32 func,
1941 			  unsigned int type)
1942 {
1943 	u32 limit;
1944 	int r;
1945 
1946 	if (func == CENTAUR_CPUID_SIGNATURE &&
1947 	    boot_cpu_data.x86_vendor != X86_VENDOR_CENTAUR &&
1948 	    boot_cpu_data.x86_vendor != X86_VENDOR_ZHAOXIN)
1949 		return 0;
1950 
1951 	r = do_cpuid_func(array, func, type);
1952 	if (r)
1953 		return r;
1954 
1955 	limit = array->entries[array->nent - 1].eax;
1956 	for (func = func + 1; func <= limit; ++func) {
1957 		r = do_cpuid_func(array, func, type);
1958 		if (r)
1959 			break;
1960 	}
1961 
1962 	return r;
1963 }
1964 
1965 static bool sanity_check_entries(struct kvm_cpuid_entry2 __user *entries,
1966 				 __u32 num_entries, unsigned int ioctl_type)
1967 {
1968 	int i;
1969 	__u32 pad[3];
1970 
1971 	if (ioctl_type != KVM_GET_EMULATED_CPUID)
1972 		return false;
1973 
1974 	/*
1975 	 * We want to make sure that ->padding is being passed clean from
1976 	 * userspace in case we want to use it for something in the future.
1977 	 *
1978 	 * Sadly, this wasn't enforced for KVM_GET_SUPPORTED_CPUID and so we
1979 	 * have to give ourselves satisfied only with the emulated side. /me
1980 	 * sheds a tear.
1981 	 */
1982 	for (i = 0; i < num_entries; i++) {
1983 		if (copy_from_user(pad, entries[i].padding, sizeof(pad)))
1984 			return true;
1985 
1986 		if (pad[0] || pad[1] || pad[2])
1987 			return true;
1988 	}
1989 	return false;
1990 }
1991 
1992 int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid,
1993 			    struct kvm_cpuid_entry2 __user *entries,
1994 			    unsigned int type)
1995 {
1996 	static const u32 funcs[] = {
1997 		0, 0x80000000, CENTAUR_CPUID_SIGNATURE, KVM_CPUID_SIGNATURE,
1998 	};
1999 
2000 	struct kvm_cpuid_array array = {
2001 		.nent = 0,
2002 	};
2003 	int r, i;
2004 
2005 	if (cpuid->nent < 1)
2006 		return -E2BIG;
2007 	if (cpuid->nent > KVM_MAX_CPUID_ENTRIES)
2008 		cpuid->nent = KVM_MAX_CPUID_ENTRIES;
2009 
2010 	if (sanity_check_entries(entries, cpuid->nent, type))
2011 		return -EINVAL;
2012 
2013 	array.entries = kvzalloc_objs(struct kvm_cpuid_entry2, cpuid->nent);
2014 	if (!array.entries)
2015 		return -ENOMEM;
2016 
2017 	array.maxnent = cpuid->nent;
2018 
2019 	for (i = 0; i < ARRAY_SIZE(funcs); i++) {
2020 		r = get_cpuid_func(&array, funcs[i], type);
2021 		if (r)
2022 			goto out_free;
2023 	}
2024 	cpuid->nent = array.nent;
2025 
2026 	if (copy_to_user(entries, array.entries,
2027 			 array.nent * sizeof(struct kvm_cpuid_entry2)))
2028 		r = -EFAULT;
2029 
2030 out_free:
2031 	kvfree(array.entries);
2032 	return r;
2033 }
2034 
2035 /*
2036  * Intel CPUID semantics treats any query for an out-of-range leaf as if the
2037  * highest basic leaf (i.e. CPUID.0H:EAX) were requested.  AMD CPUID semantics
2038  * returns all zeroes for any undefined leaf, whether or not the leaf is in
2039  * range.  Centaur/VIA follows Intel semantics.
2040  *
2041  * A leaf is considered out-of-range if its function is higher than the maximum
2042  * supported leaf of its associated class or if its associated class does not
2043  * exist.
2044  *
2045  * There are three primary classes to be considered, with their respective
2046  * ranges described as "<base> - <top>[,<base2> - <top2>] inclusive.  A primary
2047  * class exists if a guest CPUID entry for its <base> leaf exists.  For a given
2048  * class, CPUID.<base>.EAX contains the max supported leaf for the class.
2049  *
2050  *  - Basic:      0x00000000 - 0x3fffffff, 0x50000000 - 0x7fffffff
2051  *  - Hypervisor: 0x40000000 - 0x4fffffff
2052  *  - Extended:   0x80000000 - 0xbfffffff
2053  *  - Centaur:    0xc0000000 - 0xcfffffff
2054  *
2055  * The Hypervisor class is further subdivided into sub-classes that each act as
2056  * their own independent class associated with a 0x100 byte range.  E.g. if Qemu
2057  * is advertising support for both HyperV and KVM, the resulting Hypervisor
2058  * CPUID sub-classes are:
2059  *
2060  *  - HyperV:     0x40000000 - 0x400000ff
2061  *  - KVM:        0x40000100 - 0x400001ff
2062  */
2063 static struct kvm_cpuid_entry2 *
2064 get_out_of_range_cpuid_entry(struct kvm_vcpu *vcpu, u32 *fn_ptr, u32 index)
2065 {
2066 	struct kvm_cpuid_entry2 *basic, *class;
2067 	u32 function = *fn_ptr;
2068 
2069 	basic = kvm_find_cpuid_entry(vcpu, 0);
2070 	if (!basic)
2071 		return NULL;
2072 
2073 	if (is_guest_vendor_amd(basic->ebx, basic->ecx, basic->edx) ||
2074 	    is_guest_vendor_hygon(basic->ebx, basic->ecx, basic->edx))
2075 		return NULL;
2076 
2077 	if (function >= 0x40000000 && function <= 0x4fffffff)
2078 		class = kvm_find_cpuid_entry(vcpu, function & 0xffffff00);
2079 	else if (function >= 0xc0000000)
2080 		class = kvm_find_cpuid_entry(vcpu, 0xc0000000);
2081 	else
2082 		class = kvm_find_cpuid_entry(vcpu, function & 0x80000000);
2083 
2084 	if (class && function <= class->eax)
2085 		return NULL;
2086 
2087 	/*
2088 	 * Leaf specific adjustments are also applied when redirecting to the
2089 	 * max basic entry, e.g. if the max basic leaf is 0xb but there is no
2090 	 * entry for CPUID.0xb.index (see below), then the output value for EDX
2091 	 * needs to be pulled from CPUID.0xb.1.
2092 	 */
2093 	*fn_ptr = basic->eax;
2094 
2095 	/*
2096 	 * The class does not exist or the requested function is out of range;
2097 	 * the effective CPUID entry is the max basic leaf.  Note, the index of
2098 	 * the original requested leaf is observed!
2099 	 */
2100 	return kvm_find_cpuid_entry_index(vcpu, basic->eax, index);
2101 }
2102 
2103 bool kvm_cpuid(struct kvm_vcpu *vcpu, u32 *eax, u32 *ebx,
2104 	       u32 *ecx, u32 *edx, bool exact_only)
2105 {
2106 	u32 orig_function = *eax, function = *eax, index = *ecx;
2107 	struct kvm_cpuid_entry2 *entry;
2108 	bool exact, used_max_basic = false;
2109 
2110 	if (vcpu->arch.cpuid_dynamic_bits_dirty)
2111 		kvm_update_cpuid_runtime(vcpu);
2112 
2113 	entry = kvm_find_cpuid_entry_index(vcpu, function, index);
2114 	exact = !!entry;
2115 
2116 	if (!entry && !exact_only) {
2117 		entry = get_out_of_range_cpuid_entry(vcpu, &function, index);
2118 		used_max_basic = !!entry;
2119 	}
2120 
2121 	if (entry) {
2122 		*eax = entry->eax;
2123 		*ebx = entry->ebx;
2124 		*ecx = entry->ecx;
2125 		*edx = entry->edx;
2126 		if (function == 7 && index == 0) {
2127 			u64 data;
2128 			if ((*ebx & (feature_bit(RTM) | feature_bit(HLE))) &&
2129 			    !kvm_msr_read(vcpu, MSR_IA32_TSX_CTRL, &data) &&
2130 			    (data & TSX_CTRL_CPUID_CLEAR))
2131 				*ebx &= ~(feature_bit(RTM) | feature_bit(HLE));
2132 		} else if (function == 0x80000007) {
2133 			if (kvm_hv_invtsc_suppressed(vcpu))
2134 				*edx &= ~feature_bit(CONSTANT_TSC);
2135 		}
2136 	} else {
2137 		*eax = *ebx = *ecx = *edx = 0;
2138 		/*
2139 		 * When leaf 0BH or 1FH is defined, CL is pass-through
2140 		 * and EDX is always the x2APIC ID, even for undefined
2141 		 * subleaves. Index 1 will exist iff the leaf is
2142 		 * implemented, so we pass through CL iff leaf 1
2143 		 * exists. EDX can be copied from any existing index.
2144 		 */
2145 		if (function == 0xb || function == 0x1f) {
2146 			entry = kvm_find_cpuid_entry_index(vcpu, function, 1);
2147 			if (entry) {
2148 				*ecx = index & 0xff;
2149 				*edx = entry->edx;
2150 			}
2151 		}
2152 	}
2153 	trace_kvm_cpuid(orig_function, index, *eax, *ebx, *ecx, *edx, exact,
2154 			used_max_basic);
2155 	return exact;
2156 }
2157 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_cpuid);
2158 
2159 int kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
2160 {
2161 	u32 eax, ebx, ecx, edx;
2162 
2163 	if (!kvm_is_cpuid_allowed(vcpu)) {
2164 		kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
2165 		return 1;
2166 	}
2167 
2168 	eax = kvm_eax_read(vcpu);
2169 	ecx = kvm_ecx_read(vcpu);
2170 	kvm_cpuid(vcpu, &eax, &ebx, &ecx, &edx, false);
2171 	kvm_eax_write(vcpu, eax);
2172 	kvm_ebx_write(vcpu, ebx);
2173 	kvm_ecx_write(vcpu, ecx);
2174 	kvm_edx_write(vcpu, edx);
2175 	return kvm_skip_emulated_instruction(vcpu);
2176 }
2177 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_cpuid);
2178