1/*-
2 * Copyright (c) 2011 NetApp, Inc.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 * $FreeBSD: stable/11/sys/amd64/vmm/x86.c 361132 2020-05-17 11:13:12Z grehan $
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: stable/11/sys/amd64/vmm/x86.c 361132 2020-05-17 11:13:12Z grehan $");
31
32#include <sys/param.h>
33#include <sys/pcpu.h>
34#include <sys/systm.h>
35#include <sys/sysctl.h>
36
37#include <machine/clock.h>
38#include <machine/cpufunc.h>
39#include <machine/md_var.h>
40#include <machine/segments.h>
41#include <machine/specialreg.h>
42
43#include <machine/vmm.h>
44
45#include "vmm_host.h"
46#include "vmm_ktr.h"
47#include "vmm_util.h"
48#include "x86.h"
49
50SYSCTL_DECL(_hw_vmm);
51static SYSCTL_NODE(_hw_vmm, OID_AUTO, topology, CTLFLAG_RD, 0, NULL);
52
53#define	CPUID_VM_HIGH		0x40000000
54
55static const char bhyve_id[12] = "bhyve bhyve ";
56
57static uint64_t bhyve_xcpuids;
58SYSCTL_ULONG(_hw_vmm, OID_AUTO, bhyve_xcpuids, CTLFLAG_RW, &bhyve_xcpuids, 0,
59    "Number of times an unknown cpuid leaf was accessed");
60
61#if __FreeBSD_version < 1200060	/* Remove after 11 EOL helps MFCing */
62extern u_int threads_per_core;
63SYSCTL_UINT(_hw_vmm_topology, OID_AUTO, threads_per_core, CTLFLAG_RDTUN,
64    &threads_per_core, 0, NULL);
65
66extern u_int cores_per_package;
67SYSCTL_UINT(_hw_vmm_topology, OID_AUTO, cores_per_package, CTLFLAG_RDTUN,
68    &cores_per_package, 0, NULL);
69#endif
70
71static int cpuid_leaf_b = 1;
72SYSCTL_INT(_hw_vmm_topology, OID_AUTO, cpuid_leaf_b, CTLFLAG_RDTUN,
73    &cpuid_leaf_b, 0, NULL);
74
75/*
76 * Round up to the next power of two, if necessary, and then take log2.
77 * Returns -1 if argument is zero.
78 */
79static __inline int
80log2(u_int x)
81{
82
83	return (fls(x << (1 - powerof2(x))) - 1);
84}
85
86int
87x86_emulate_cpuid(struct vm *vm, int vcpu_id,
88		  uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx)
89{
90	const struct xsave_limits *limits;
91	uint64_t cr4;
92	int error, enable_invpcid, level, width, x2apic_id;
93	unsigned int func, regs[4], logical_cpus;
94	enum x2apic_state x2apic_state;
95	uint16_t cores, maxcpus, sockets, threads;
96
97	VCPU_CTR2(vm, vcpu_id, "cpuid %#x,%#x", *eax, *ecx);
98
99	/*
100	 * Requests for invalid CPUID levels should map to the highest
101	 * available level instead.
102	 */
103	if (cpu_exthigh != 0 && *eax >= 0x80000000) {
104		if (*eax > cpu_exthigh)
105			*eax = cpu_exthigh;
106	} else if (*eax >= 0x40000000) {
107		if (*eax > CPUID_VM_HIGH)
108			*eax = CPUID_VM_HIGH;
109	} else if (*eax > cpu_high) {
110		*eax = cpu_high;
111	}
112
113	func = *eax;
114
115	/*
116	 * In general the approach used for CPU topology is to
117	 * advertise a flat topology where all CPUs are packages with
118	 * no multi-core or SMT.
119	 */
120	switch (func) {
121		/*
122		 * Pass these through to the guest
123		 */
124		case CPUID_0000_0000:
125		case CPUID_0000_0002:
126		case CPUID_0000_0003:
127		case CPUID_8000_0000:
128		case CPUID_8000_0002:
129		case CPUID_8000_0003:
130		case CPUID_8000_0004:
131		case CPUID_8000_0006:
132			cpuid_count(*eax, *ecx, regs);
133			break;
134		case CPUID_8000_0008:
135			cpuid_count(*eax, *ecx, regs);
136			if (vmm_is_amd()) {
137				/*
138				 * As on Intel (0000_0007:0, EDX), mask out
139				 * unsupported or unsafe AMD extended features
140				 * (8000_0008 EBX).
141				 */
142				regs[1] &= (AMDFEID_CLZERO | AMDFEID_IRPERF |
143				    AMDFEID_XSAVEERPTR);
144
145				vm_get_topology(vm, &sockets, &cores, &threads,
146				    &maxcpus);
147				/*
148				 * Here, width is ApicIdCoreIdSize, present on
149				 * at least Family 15h and newer.  It
150				 * represents the "number of bits in the
151				 * initial apicid that indicate thread id
152				 * within a package."
153				 *
154				 * Our topo_probe_amd() uses it for
155				 * pkg_id_shift and other OSes may rely on it.
156				 */
157				width = MIN(0xF, log2(threads * cores));
158				if (width < 0x4)
159					width = 0;
160				logical_cpus = MIN(0xFF, threads * cores - 1);
161				regs[2] = (width << AMDID_COREID_SIZE_SHIFT) | logical_cpus;
162			}
163			break;
164
165		case CPUID_8000_0001:
166			cpuid_count(*eax, *ecx, regs);
167
168			/*
169			 * Hide SVM from guest.
170			 */
171			regs[2] &= ~AMDID2_SVM;
172
173			/*
174			 * Don't advertise extended performance counter MSRs
175			 * to the guest.
176			 */
177			regs[2] &= ~AMDID2_PCXC;
178			regs[2] &= ~AMDID2_PNXC;
179			regs[2] &= ~AMDID2_PTSCEL2I;
180
181			/*
182			 * Don't advertise Instruction Based Sampling feature.
183			 */
184			regs[2] &= ~AMDID2_IBS;
185
186			/* NodeID MSR not available */
187			regs[2] &= ~AMDID2_NODE_ID;
188
189			/* Don't advertise the OS visible workaround feature */
190			regs[2] &= ~AMDID2_OSVW;
191
192			/* Hide mwaitx/monitorx capability from the guest */
193			regs[2] &= ~AMDID2_MWAITX;
194
195			/*
196			 * Hide rdtscp/ia32_tsc_aux until we know how
197			 * to deal with them.
198			 */
199			regs[3] &= ~AMDID_RDTSCP;
200			break;
201
202		case CPUID_8000_0007:
203			/*
204			 * AMD uses this leaf to advertise the processor's
205			 * power monitoring and RAS capabilities. These
206			 * features are hardware-specific and exposing
207			 * them to a guest doesn't make a lot of sense.
208			 *
209			 * Intel uses this leaf only to advertise the
210			 * "Invariant TSC" feature with all other bits
211			 * being reserved (set to zero).
212			 */
213			regs[0] = 0;
214			regs[1] = 0;
215			regs[2] = 0;
216			regs[3] = 0;
217
218			/*
219			 * "Invariant TSC" can be advertised to the guest if:
220			 * - host TSC frequency is invariant
221			 * - host TSCs are synchronized across physical cpus
222			 *
223			 * XXX This still falls short because the vcpu
224			 * can observe the TSC moving backwards as it
225			 * migrates across physical cpus. But at least
226			 * it should discourage the guest from using the
227			 * TSC to keep track of time.
228			 */
229			if (tsc_is_invariant && smp_tsc)
230				regs[3] |= AMDPM_TSC_INVARIANT;
231			break;
232
233		case CPUID_8000_001D:
234			/* AMD Cache topology, like 0000_0004 for Intel. */
235			if (!vmm_is_amd())
236				goto default_leaf;
237
238			/*
239			 * Similar to Intel, generate a ficticious cache
240			 * topology for the guest with L3 shared by the
241			 * package, and L1 and L2 local to a core.
242			 */
243			vm_get_topology(vm, &sockets, &cores, &threads,
244			    &maxcpus);
245			switch (*ecx) {
246			case 0:
247				logical_cpus = threads;
248				level = 1;
249				func = 1;	/* data cache */
250				break;
251			case 1:
252				logical_cpus = threads;
253				level = 2;
254				func = 3;	/* unified cache */
255				break;
256			case 2:
257				logical_cpus = threads * cores;
258				level = 3;
259				func = 3;	/* unified cache */
260				break;
261			default:
262				logical_cpus = 0;
263				level = 0;
264				func = 0;
265				break;
266			}
267
268			logical_cpus = MIN(0xfff, logical_cpus - 1);
269			regs[0] = (logical_cpus << 14) | (1 << 8) |
270			    (level << 5) | func;
271			regs[1] = (func > 0) ? (CACHE_LINE_SIZE - 1) : 0;
272			regs[2] = 0;
273			regs[3] = 0;
274			break;
275
276		case CPUID_8000_001E:
277			/* AMD Family 16h+ additional identifiers */
278			if (!vmm_is_amd() || CPUID_TO_FAMILY(cpu_id) < 0x16)
279				goto default_leaf;
280
281			vm_get_topology(vm, &sockets, &cores, &threads,
282			    &maxcpus);
283			regs[0] = vcpu_id;
284			threads = MIN(0xFF, threads - 1);
285			regs[1] = (threads << 8) |
286			    (vcpu_id >> log2(threads + 1));
287			/*
288			 * XXX Bhyve topology cannot yet represent >1 node per
289			 * processor.
290			 */
291			regs[2] = 0;
292			regs[3] = 0;
293			break;
294
295		case CPUID_0000_0001:
296			do_cpuid(1, regs);
297
298			error = vm_get_x2apic_state(vm, vcpu_id, &x2apic_state);
299			if (error) {
300				panic("x86_emulate_cpuid: error %d "
301				      "fetching x2apic state", error);
302			}
303
304			/*
305			 * Override the APIC ID only in ebx
306			 */
307			regs[1] &= ~(CPUID_LOCAL_APIC_ID);
308			regs[1] |= (vcpu_id << CPUID_0000_0001_APICID_SHIFT);
309
310			/*
311			 * Don't expose VMX, SpeedStep, TME or SMX capability.
312			 * Advertise x2APIC capability and Hypervisor guest.
313			 */
314			regs[2] &= ~(CPUID2_VMX | CPUID2_EST | CPUID2_TM2);
315			regs[2] &= ~(CPUID2_SMX);
316
317			regs[2] |= CPUID2_HV;
318
319			if (x2apic_state != X2APIC_DISABLED)
320				regs[2] |= CPUID2_X2APIC;
321			else
322				regs[2] &= ~CPUID2_X2APIC;
323
324			/*
325			 * Only advertise CPUID2_XSAVE in the guest if
326			 * the host is using XSAVE.
327			 */
328			if (!(regs[2] & CPUID2_OSXSAVE))
329				regs[2] &= ~CPUID2_XSAVE;
330
331			/*
332			 * If CPUID2_XSAVE is being advertised and the
333			 * guest has set CR4_XSAVE, set
334			 * CPUID2_OSXSAVE.
335			 */
336			regs[2] &= ~CPUID2_OSXSAVE;
337			if (regs[2] & CPUID2_XSAVE) {
338				error = vm_get_register(vm, vcpu_id,
339				    VM_REG_GUEST_CR4, &cr4);
340				if (error)
341					panic("x86_emulate_cpuid: error %d "
342					      "fetching %%cr4", error);
343				if (cr4 & CR4_XSAVE)
344					regs[2] |= CPUID2_OSXSAVE;
345			}
346
347			/*
348			 * Hide monitor/mwait until we know how to deal with
349			 * these instructions.
350			 */
351			regs[2] &= ~CPUID2_MON;
352
353                        /*
354			 * Hide the performance and debug features.
355			 */
356			regs[2] &= ~CPUID2_PDCM;
357
358			/*
359			 * No TSC deadline support in the APIC yet
360			 */
361			regs[2] &= ~CPUID2_TSCDLT;
362
363			/*
364			 * Hide thermal monitoring
365			 */
366			regs[3] &= ~(CPUID_ACPI | CPUID_TM);
367
368			/*
369			 * Hide the debug store capability.
370			 */
371			regs[3] &= ~CPUID_DS;
372
373			/*
374			 * Advertise the Machine Check and MTRR capability.
375			 *
376			 * Some guest OSes (e.g. Windows) will not boot if
377			 * these features are absent.
378			 */
379			regs[3] |= (CPUID_MCA | CPUID_MCE | CPUID_MTRR);
380
381			vm_get_topology(vm, &sockets, &cores, &threads,
382			    &maxcpus);
383			logical_cpus = threads * cores;
384			regs[1] &= ~CPUID_HTT_CORES;
385			regs[1] |= (logical_cpus & 0xff) << 16;
386			regs[3] |= CPUID_HTT;
387			break;
388
389		case CPUID_0000_0004:
390			cpuid_count(*eax, *ecx, regs);
391
392			if (regs[0] || regs[1] || regs[2] || regs[3]) {
393				vm_get_topology(vm, &sockets, &cores, &threads,
394				    &maxcpus);
395				regs[0] &= 0x3ff;
396				regs[0] |= (cores - 1) << 26;
397				/*
398				 * Cache topology:
399				 * - L1 and L2 are shared only by the logical
400				 *   processors in a single core.
401				 * - L3 and above are shared by all logical
402				 *   processors in the package.
403				 */
404				logical_cpus = threads;
405				level = (regs[0] >> 5) & 0x7;
406				if (level >= 3)
407					logical_cpus *= cores;
408				regs[0] |= (logical_cpus - 1) << 14;
409			}
410			break;
411
412		case CPUID_0000_0007:
413			regs[0] = 0;
414			regs[1] = 0;
415			regs[2] = 0;
416			regs[3] = 0;
417
418			/* leaf 0 */
419			if (*ecx == 0) {
420				cpuid_count(*eax, *ecx, regs);
421
422				/* Only leaf 0 is supported */
423				regs[0] = 0;
424
425				/*
426				 * Expose known-safe features.
427				 */
428				regs[1] &= (CPUID_STDEXT_FSGSBASE |
429				    CPUID_STDEXT_BMI1 | CPUID_STDEXT_HLE |
430				    CPUID_STDEXT_AVX2 | CPUID_STDEXT_BMI2 |
431				    CPUID_STDEXT_ERMS | CPUID_STDEXT_RTM |
432				    CPUID_STDEXT_AVX512F |
433				    CPUID_STDEXT_RDSEED |
434				    CPUID_STDEXT_AVX512PF |
435				    CPUID_STDEXT_AVX512ER |
436				    CPUID_STDEXT_AVX512CD | CPUID_STDEXT_SHA);
437				regs[2] = 0;
438				regs[3] &= CPUID_STDEXT3_MD_CLEAR;
439
440				/* Advertise INVPCID if it is enabled. */
441				error = vm_get_capability(vm, vcpu_id,
442				    VM_CAP_ENABLE_INVPCID, &enable_invpcid);
443				if (error == 0 && enable_invpcid)
444					regs[1] |= CPUID_STDEXT_INVPCID;
445			}
446			break;
447
448		case CPUID_0000_0006:
449			regs[0] = CPUTPM1_ARAT;
450			regs[1] = 0;
451			regs[2] = 0;
452			regs[3] = 0;
453			break;
454
455		case CPUID_0000_000A:
456			/*
457			 * Handle the access, but report 0 for
458			 * all options
459			 */
460			regs[0] = 0;
461			regs[1] = 0;
462			regs[2] = 0;
463			regs[3] = 0;
464			break;
465
466		case CPUID_0000_000B:
467			/*
468			 * Intel processor topology enumeration
469			 */
470			if (vmm_is_intel()) {
471				vm_get_topology(vm, &sockets, &cores, &threads,
472				    &maxcpus);
473				if (*ecx == 0) {
474					logical_cpus = threads;
475					width = log2(logical_cpus);
476					level = CPUID_TYPE_SMT;
477					x2apic_id = vcpu_id;
478				}
479
480				if (*ecx == 1) {
481					logical_cpus = threads * cores;
482					width = log2(logical_cpus);
483					level = CPUID_TYPE_CORE;
484					x2apic_id = vcpu_id;
485				}
486
487				if (!cpuid_leaf_b || *ecx >= 2) {
488					width = 0;
489					logical_cpus = 0;
490					level = 0;
491					x2apic_id = 0;
492				}
493
494				regs[0] = width & 0x1f;
495				regs[1] = logical_cpus & 0xffff;
496				regs[2] = (level << 8) | (*ecx & 0xff);
497				regs[3] = x2apic_id;
498			} else {
499				regs[0] = 0;
500				regs[1] = 0;
501				regs[2] = 0;
502				regs[3] = 0;
503			}
504			break;
505
506		case CPUID_0000_000D:
507			limits = vmm_get_xsave_limits();
508			if (!limits->xsave_enabled) {
509				regs[0] = 0;
510				regs[1] = 0;
511				regs[2] = 0;
512				regs[3] = 0;
513				break;
514			}
515
516			cpuid_count(*eax, *ecx, regs);
517			switch (*ecx) {
518			case 0:
519				/*
520				 * Only permit the guest to use bits
521				 * that are active in the host in
522				 * %xcr0.  Also, claim that the
523				 * maximum save area size is
524				 * equivalent to the host's current
525				 * save area size.  Since this runs
526				 * "inside" of vmrun(), it runs with
527				 * the guest's xcr0, so the current
528				 * save area size is correct as-is.
529				 */
530				regs[0] &= limits->xcr0_allowed;
531				regs[2] = limits->xsave_max_size;
532				regs[3] &= (limits->xcr0_allowed >> 32);
533				break;
534			case 1:
535				/* Only permit XSAVEOPT. */
536				regs[0] &= CPUID_EXTSTATE_XSAVEOPT;
537				regs[1] = 0;
538				regs[2] = 0;
539				regs[3] = 0;
540				break;
541			default:
542				/*
543				 * If the leaf is for a permitted feature,
544				 * pass through as-is, otherwise return
545				 * all zeroes.
546				 */
547				if (!(limits->xcr0_allowed & (1ul << *ecx))) {
548					regs[0] = 0;
549					regs[1] = 0;
550					regs[2] = 0;
551					regs[3] = 0;
552				}
553				break;
554			}
555			break;
556
557		case CPUID_0000_0015:
558			/*
559			 * Don't report CPU TSC/Crystal ratio and clock
560			 * values since guests may use these to derive the
561			 * local APIC frequency..
562			 */
563			regs[0] = 0;
564			regs[1] = 0;
565			regs[2] = 0;
566			regs[3] = 0;
567			break;
568
569		case 0x40000000:
570			regs[0] = CPUID_VM_HIGH;
571			bcopy(bhyve_id, &regs[1], 4);
572			bcopy(bhyve_id + 4, &regs[2], 4);
573			bcopy(bhyve_id + 8, &regs[3], 4);
574			break;
575
576		default:
577default_leaf:
578			/*
579			 * The leaf value has already been clamped so
580			 * simply pass this through, keeping count of
581			 * how many unhandled leaf values have been seen.
582			 */
583			atomic_add_long(&bhyve_xcpuids, 1);
584			cpuid_count(*eax, *ecx, regs);
585			break;
586	}
587
588	*eax = regs[0];
589	*ebx = regs[1];
590	*ecx = regs[2];
591	*edx = regs[3];
592
593	return (1);
594}
595
596bool
597vm_cpuid_capability(struct vm *vm, int vcpuid, enum vm_cpuid_capability cap)
598{
599	bool rv;
600
601	KASSERT(cap > 0 && cap < VCC_LAST, ("%s: invalid vm_cpu_capability %d",
602	    __func__, cap));
603
604	/*
605	 * Simply passthrough the capabilities of the host cpu for now.
606	 */
607	rv = false;
608	switch (cap) {
609	case VCC_NO_EXECUTE:
610		if (amd_feature & AMDID_NX)
611			rv = true;
612		break;
613	case VCC_FFXSR:
614		if (amd_feature & AMDID_FFXSR)
615			rv = true;
616		break;
617	case VCC_TCE:
618		if (amd_feature2 & AMDID2_TCE)
619			rv = true;
620		break;
621	default:
622		panic("%s: unknown vm_cpu_capability %d", __func__, cap);
623	}
624	return (rv);
625}
626