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