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