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