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