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