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