xref: /illumos-gate/usr/src/uts/intel/io/vmm/intel/vmx.c (revision 50fe091cff3f2dccec5f588584a3ccb4f9933570)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  * Copyright (c) 2018 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 /*
30  * This file and its contents are supplied under the terms of the
31  * Common Development and Distribution License ("CDDL"), version 1.0.
32  * You may only use this file in accordance with the terms of version
33  * 1.0 of the CDDL.
34  *
35  * A full copy of the text of the CDDL should have accompanied this
36  * source.  A copy of the CDDL is also available via the Internet at
37  * http://www.illumos.org/license/CDDL.
38  */
39 /* This file is dual-licensed; see usr/src/contrib/bhyve/LICENSE */
40 
41 /*
42  * Copyright 2015 Pluribus Networks Inc.
43  * Copyright 2018 Joyent, Inc.
44  * Copyright 2022 Oxide Computer Company
45  * Copyright 2022 MNX Cloud, Inc.
46  */
47 
48 #include <sys/cdefs.h>
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/kmem.h>
54 #include <sys/pcpu.h>
55 #include <sys/proc.h>
56 #include <sys/sysctl.h>
57 
58 #include <sys/x86_archext.h>
59 #include <sys/smp_impldefs.h>
60 #include <sys/smt.h>
61 #include <sys/hma.h>
62 #include <sys/trap.h>
63 #include <sys/archsystm.h>
64 
65 #include <machine/psl.h>
66 #include <machine/cpufunc.h>
67 #include <machine/md_var.h>
68 #include <machine/reg.h>
69 #include <machine/segments.h>
70 #include <machine/specialreg.h>
71 #include <machine/vmparam.h>
72 #include <sys/vmm_vm.h>
73 #include <sys/vmm_kernel.h>
74 
75 #include <machine/vmm.h>
76 #include <machine/vmm_dev.h>
77 #include <sys/vmm_instruction_emul.h>
78 #include "vmm_lapic.h"
79 #include "vmm_host.h"
80 #include "vmm_ioport.h"
81 #include "vmm_stat.h"
82 #include "vatpic.h"
83 #include "vlapic.h"
84 #include "vlapic_priv.h"
85 
86 #include "vmcs.h"
87 #include "vmx.h"
88 #include "vmx_msr.h"
89 #include "vmx_controls.h"
90 
91 #define	PINBASED_CTLS_ONE_SETTING					\
92 	(PINBASED_EXTINT_EXITING	|				\
93 	PINBASED_NMI_EXITING		|				\
94 	PINBASED_VIRTUAL_NMI)
95 #define	PINBASED_CTLS_ZERO_SETTING	0
96 
97 #define	PROCBASED_CTLS_WINDOW_SETTING					\
98 	(PROCBASED_INT_WINDOW_EXITING	|				\
99 	PROCBASED_NMI_WINDOW_EXITING)
100 
101 /*
102  * Distinct from FreeBSD bhyve, we consider several additional proc-based
103  * controls necessary:
104  * - TSC offsetting
105  * - HLT exiting
106  */
107 #define	PROCBASED_CTLS_ONE_SETTING					\
108 	(PROCBASED_SECONDARY_CONTROLS	|				\
109 	PROCBASED_TSC_OFFSET		|				\
110 	PROCBASED_HLT_EXITING		|				\
111 	PROCBASED_MWAIT_EXITING		|				\
112 	PROCBASED_MONITOR_EXITING	|				\
113 	PROCBASED_IO_EXITING		|				\
114 	PROCBASED_MSR_BITMAPS		|				\
115 	PROCBASED_CTLS_WINDOW_SETTING	|				\
116 	PROCBASED_CR8_LOAD_EXITING	|				\
117 	PROCBASED_CR8_STORE_EXITING)
118 
119 #define	PROCBASED_CTLS_ZERO_SETTING	\
120 	(PROCBASED_CR3_LOAD_EXITING |	\
121 	PROCBASED_CR3_STORE_EXITING |	\
122 	PROCBASED_IO_BITMAPS)
123 
124 /*
125  * EPT and Unrestricted Guest are considered necessities.  The latter is not a
126  * requirement on FreeBSD, where grub2-bhyve is used to load guests directly
127  * without a bootrom starting in real mode.
128  */
129 #define	PROCBASED_CTLS2_ONE_SETTING		\
130 	(PROCBASED2_ENABLE_EPT |		\
131 	PROCBASED2_UNRESTRICTED_GUEST)
132 #define	PROCBASED_CTLS2_ZERO_SETTING	0
133 
134 #define	VM_EXIT_CTLS_ONE_SETTING					\
135 	(VM_EXIT_SAVE_DEBUG_CONTROLS		|			\
136 	VM_EXIT_HOST_LMA			|			\
137 	VM_EXIT_LOAD_PAT			|			\
138 	VM_EXIT_SAVE_EFER			|			\
139 	VM_EXIT_LOAD_EFER			|			\
140 	VM_EXIT_ACKNOWLEDGE_INTERRUPT)
141 
142 #define	VM_EXIT_CTLS_ZERO_SETTING	0
143 
144 #define	VM_ENTRY_CTLS_ONE_SETTING					\
145 	(VM_ENTRY_LOAD_DEBUG_CONTROLS		|			\
146 	VM_ENTRY_LOAD_EFER)
147 
148 #define	VM_ENTRY_CTLS_ZERO_SETTING					\
149 	(VM_ENTRY_INTO_SMM			|			\
150 	VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
151 
152 /*
153  * Cover the EPT capabilities used by bhyve at present:
154  * - 4-level page walks
155  * - write-back memory type
156  * - INVEPT operations (all types)
157  * - INVVPID operations (single-context only)
158  */
159 #define	EPT_CAPS_REQUIRED			\
160 	(IA32_VMX_EPT_VPID_PWL4 |		\
161 	IA32_VMX_EPT_VPID_TYPE_WB |		\
162 	IA32_VMX_EPT_VPID_INVEPT |		\
163 	IA32_VMX_EPT_VPID_INVEPT_SINGLE |	\
164 	IA32_VMX_EPT_VPID_INVEPT_ALL |		\
165 	IA32_VMX_EPT_VPID_INVVPID |		\
166 	IA32_VMX_EPT_VPID_INVVPID_SINGLE)
167 
168 #define	HANDLED		1
169 #define	UNHANDLED	0
170 
171 SYSCTL_DECL(_hw_vmm);
172 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
173     NULL);
174 
175 /*
176  * TSC scaling related constants
177  */
178 #define	INTEL_TSCM_INT_SIZE	16
179 #define	INTEL_TSCM_FRAC_SIZE	48
180 
181 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
182 static uint32_t exit_ctls, entry_ctls;
183 
184 static uint64_t cr0_ones_mask, cr0_zeros_mask;
185 
186 static uint64_t cr4_ones_mask, cr4_zeros_mask;
187 
188 /*
189  * Optional capabilities
190  */
191 
192 /* PAUSE triggers a VM-exit */
193 static int cap_pause_exit;
194 
195 /* WBINVD triggers a VM-exit */
196 static int cap_wbinvd_exit;
197 
198 /* Monitor trap flag */
199 static int cap_monitor_trap;
200 
201 /* Guests are allowed to use INVPCID */
202 static int cap_invpcid;
203 
204 /* Extra capabilities (VMX_CAP_*) beyond the minimum */
205 static enum vmx_caps vmx_capabilities;
206 
207 /* APICv posted interrupt vector */
208 static int pirvec = -1;
209 
210 static uint_t vpid_alloc_failed;
211 
212 int guest_l1d_flush;
213 int guest_l1d_flush_sw;
214 
215 /* MSR save region is composed of an array of 'struct msr_entry' */
216 struct msr_entry {
217 	uint32_t	index;
218 	uint32_t	reserved;
219 	uint64_t	val;
220 };
221 
222 static struct msr_entry msr_load_list[1] __aligned(16);
223 
224 /*
225  * The definitions of SDT probes for VMX.
226  */
227 
228 /* BEGIN CSTYLED */
229 SDT_PROBE_DEFINE3(vmm, vmx, exit, entry,
230     "struct vmx *", "int", "struct vm_exit *");
231 
232 SDT_PROBE_DEFINE4(vmm, vmx, exit, taskswitch,
233     "struct vmx *", "int", "struct vm_exit *", "struct vm_task_switch *");
234 
235 SDT_PROBE_DEFINE4(vmm, vmx, exit, craccess,
236     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
237 
238 SDT_PROBE_DEFINE4(vmm, vmx, exit, rdmsr,
239     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
240 
241 SDT_PROBE_DEFINE5(vmm, vmx, exit, wrmsr,
242     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "uint64_t");
243 
244 SDT_PROBE_DEFINE3(vmm, vmx, exit, halt,
245     "struct vmx *", "int", "struct vm_exit *");
246 
247 SDT_PROBE_DEFINE3(vmm, vmx, exit, mtrap,
248     "struct vmx *", "int", "struct vm_exit *");
249 
250 SDT_PROBE_DEFINE3(vmm, vmx, exit, pause,
251     "struct vmx *", "int", "struct vm_exit *");
252 
253 SDT_PROBE_DEFINE3(vmm, vmx, exit, intrwindow,
254     "struct vmx *", "int", "struct vm_exit *");
255 
256 SDT_PROBE_DEFINE4(vmm, vmx, exit, interrupt,
257     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
258 
259 SDT_PROBE_DEFINE3(vmm, vmx, exit, nmiwindow,
260     "struct vmx *", "int", "struct vm_exit *");
261 
262 SDT_PROBE_DEFINE3(vmm, vmx, exit, inout,
263     "struct vmx *", "int", "struct vm_exit *");
264 
265 SDT_PROBE_DEFINE3(vmm, vmx, exit, cpuid,
266     "struct vmx *", "int", "struct vm_exit *");
267 
268 SDT_PROBE_DEFINE5(vmm, vmx, exit, exception,
269     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "int");
270 
271 SDT_PROBE_DEFINE5(vmm, vmx, exit, nestedfault,
272     "struct vmx *", "int", "struct vm_exit *", "uint64_t", "uint64_t");
273 
274 SDT_PROBE_DEFINE4(vmm, vmx, exit, mmiofault,
275     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
276 
277 SDT_PROBE_DEFINE3(vmm, vmx, exit, eoi,
278     "struct vmx *", "int", "struct vm_exit *");
279 
280 SDT_PROBE_DEFINE3(vmm, vmx, exit, apicaccess,
281     "struct vmx *", "int", "struct vm_exit *");
282 
283 SDT_PROBE_DEFINE4(vmm, vmx, exit, apicwrite,
284     "struct vmx *", "int", "struct vm_exit *", "struct vlapic *");
285 
286 SDT_PROBE_DEFINE3(vmm, vmx, exit, xsetbv,
287     "struct vmx *", "int", "struct vm_exit *");
288 
289 SDT_PROBE_DEFINE3(vmm, vmx, exit, monitor,
290     "struct vmx *", "int", "struct vm_exit *");
291 
292 SDT_PROBE_DEFINE3(vmm, vmx, exit, mwait,
293     "struct vmx *", "int", "struct vm_exit *");
294 
295 SDT_PROBE_DEFINE3(vmm, vmx, exit, vminsn,
296     "struct vmx *", "int", "struct vm_exit *");
297 
298 SDT_PROBE_DEFINE4(vmm, vmx, exit, unknown,
299     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
300 
301 SDT_PROBE_DEFINE4(vmm, vmx, exit, return,
302     "struct vmx *", "int", "struct vm_exit *", "int");
303 /* END CSTYLED */
304 
305 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
306 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
307 static void vmx_apply_tsc_adjust(struct vmx *, int);
308 static void vmx_apicv_sync_tmr(struct vlapic *vlapic);
309 static void vmx_tpr_shadow_enter(struct vlapic *vlapic);
310 static void vmx_tpr_shadow_exit(struct vlapic *vlapic);
311 
312 static void
vmx_allow_x2apic_msrs(struct vmx * vmx,int vcpuid)313 vmx_allow_x2apic_msrs(struct vmx *vmx, int vcpuid)
314 {
315 	/*
316 	 * Allow readonly access to the following x2APIC MSRs from the guest.
317 	 */
318 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ID);
319 	guest_msr_ro(vmx, vcpuid, MSR_APIC_VERSION);
320 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LDR);
321 	guest_msr_ro(vmx, vcpuid, MSR_APIC_SVR);
322 
323 	for (uint_t i = 0; i < 8; i++) {
324 		guest_msr_ro(vmx, vcpuid, MSR_APIC_ISR0 + i);
325 		guest_msr_ro(vmx, vcpuid, MSR_APIC_TMR0 + i);
326 		guest_msr_ro(vmx, vcpuid, MSR_APIC_IRR0 + i);
327 	}
328 
329 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ESR);
330 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_TIMER);
331 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_THERMAL);
332 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_PCINT);
333 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_LINT0);
334 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_LINT1);
335 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_ERROR);
336 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ICR_TIMER);
337 	guest_msr_ro(vmx, vcpuid, MSR_APIC_DCR_TIMER);
338 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ICR);
339 
340 	/*
341 	 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
342 	 *
343 	 * These registers get special treatment described in the section
344 	 * "Virtualizing MSR-Based APIC Accesses".
345 	 */
346 	guest_msr_rw(vmx, vcpuid, MSR_APIC_TPR);
347 	guest_msr_rw(vmx, vcpuid, MSR_APIC_EOI);
348 	guest_msr_rw(vmx, vcpuid, MSR_APIC_SELF_IPI);
349 }
350 
351 static ulong_t
vmx_fix_cr0(ulong_t cr0)352 vmx_fix_cr0(ulong_t cr0)
353 {
354 	return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
355 }
356 
357 /*
358  * Given a live (VMCS-active) cr0 value, and its shadow counterpart, calculate
359  * the value observable from the guest.
360  */
361 static ulong_t
vmx_unshadow_cr0(uint64_t cr0,uint64_t shadow)362 vmx_unshadow_cr0(uint64_t cr0, uint64_t shadow)
363 {
364 	return ((cr0 & ~cr0_ones_mask) |
365 	    (shadow & (cr0_zeros_mask | cr0_ones_mask)));
366 }
367 
368 static ulong_t
vmx_fix_cr4(ulong_t cr4)369 vmx_fix_cr4(ulong_t cr4)
370 {
371 	return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
372 }
373 
374 /*
375  * Given a live (VMCS-active) cr4 value, and its shadow counterpart, calculate
376  * the value observable from the guest.
377  */
378 static ulong_t
vmx_unshadow_cr4(uint64_t cr4,uint64_t shadow)379 vmx_unshadow_cr4(uint64_t cr4, uint64_t shadow)
380 {
381 	return ((cr4 & ~cr4_ones_mask) |
382 	    (shadow & (cr4_zeros_mask | cr4_ones_mask)));
383 }
384 
385 static void
vpid_free(int vpid)386 vpid_free(int vpid)
387 {
388 	if (vpid < 0 || vpid > 0xffff)
389 		panic("vpid_free: invalid vpid %d", vpid);
390 
391 	/*
392 	 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
393 	 * the unit number allocator.
394 	 */
395 
396 	if (vpid > VM_MAXCPU)
397 		hma_vmx_vpid_free((uint16_t)vpid);
398 }
399 
400 static void
vpid_alloc(uint16_t * vpid,int num)401 vpid_alloc(uint16_t *vpid, int num)
402 {
403 	int i, x;
404 
405 	if (num <= 0 || num > VM_MAXCPU)
406 		panic("invalid number of vpids requested: %d", num);
407 
408 	/*
409 	 * If the "enable vpid" execution control is not enabled then the
410 	 * VPID is required to be 0 for all vcpus.
411 	 */
412 	if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
413 		for (i = 0; i < num; i++)
414 			vpid[i] = 0;
415 		return;
416 	}
417 
418 	/*
419 	 * Allocate a unique VPID for each vcpu from the unit number allocator.
420 	 */
421 	for (i = 0; i < num; i++) {
422 		uint16_t tmp;
423 
424 		tmp = hma_vmx_vpid_alloc();
425 		x = (tmp == 0) ? -1 : tmp;
426 
427 		if (x == -1)
428 			break;
429 		else
430 			vpid[i] = x;
431 	}
432 
433 	if (i < num) {
434 		atomic_add_int(&vpid_alloc_failed, 1);
435 
436 		/*
437 		 * If the unit number allocator does not have enough unique
438 		 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
439 		 *
440 		 * These VPIDs are not be unique across VMs but this does not
441 		 * affect correctness because the combined mappings are also
442 		 * tagged with the EP4TA which is unique for each VM.
443 		 *
444 		 * It is still sub-optimal because the invvpid will invalidate
445 		 * combined mappings for a particular VPID across all EP4TAs.
446 		 */
447 		while (i-- > 0)
448 			vpid_free(vpid[i]);
449 
450 		for (i = 0; i < num; i++)
451 			vpid[i] = i + 1;
452 	}
453 }
454 
455 static void
vmx_restore(void)456 vmx_restore(void)
457 {
458 	/* No-op on illumos */
459 }
460 
461 static int
vmx_init(void)462 vmx_init(void)
463 {
464 	int error;
465 	uint64_t fixed0, fixed1;
466 	uint32_t tmp;
467 	enum vmx_caps avail_caps = VMX_CAP_NONE;
468 
469 	/* Check support for primary processor-based VM-execution controls */
470 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
471 	    MSR_VMX_TRUE_PROCBASED_CTLS,
472 	    PROCBASED_CTLS_ONE_SETTING,
473 	    PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
474 	if (error) {
475 		printf("vmx_init: processor does not support desired primary "
476 		    "processor-based controls\n");
477 		return (error);
478 	}
479 
480 	/*
481 	 * Clear interrupt-window/NMI-window exiting from the default proc-based
482 	 * controls. They are set and cleared based on runtime vCPU events.
483 	 */
484 	procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
485 
486 	/* Check support for secondary processor-based VM-execution controls */
487 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
488 	    MSR_VMX_PROCBASED_CTLS2,
489 	    PROCBASED_CTLS2_ONE_SETTING,
490 	    PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
491 	if (error) {
492 		printf("vmx_init: processor does not support desired secondary "
493 		    "processor-based controls\n");
494 		return (error);
495 	}
496 
497 	/* Check support for VPID */
498 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
499 	    MSR_VMX_PROCBASED_CTLS2,
500 	    PROCBASED2_ENABLE_VPID,
501 	    0, &tmp);
502 	if (error == 0)
503 		procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
504 
505 	/* Check support for pin-based VM-execution controls */
506 	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
507 	    MSR_VMX_TRUE_PINBASED_CTLS,
508 	    PINBASED_CTLS_ONE_SETTING,
509 	    PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
510 	if (error) {
511 		printf("vmx_init: processor does not support desired "
512 		    "pin-based controls\n");
513 		return (error);
514 	}
515 
516 	/* Check support for VM-exit controls */
517 	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
518 	    VM_EXIT_CTLS_ONE_SETTING,
519 	    VM_EXIT_CTLS_ZERO_SETTING,
520 	    &exit_ctls);
521 	if (error) {
522 		printf("vmx_init: processor does not support desired "
523 		    "exit controls\n");
524 		return (error);
525 	}
526 
527 	/* Check support for VM-entry controls */
528 	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
529 	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
530 	    &entry_ctls);
531 	if (error) {
532 		printf("vmx_init: processor does not support desired "
533 		    "entry controls\n");
534 		return (error);
535 	}
536 
537 	/*
538 	 * Check support for optional features by testing them
539 	 * as individual bits
540 	 */
541 	cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
542 	    MSR_VMX_PROCBASED_CTLS,
543 	    PROCBASED_MTF, 0,
544 	    &tmp) == 0);
545 
546 	cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
547 	    MSR_VMX_TRUE_PROCBASED_CTLS,
548 	    PROCBASED_PAUSE_EXITING, 0,
549 	    &tmp) == 0);
550 
551 	cap_wbinvd_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
552 	    MSR_VMX_PROCBASED_CTLS2,
553 	    PROCBASED2_WBINVD_EXITING, 0,
554 	    &tmp) == 0);
555 
556 	cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
557 	    MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
558 	    &tmp) == 0);
559 
560 	/*
561 	 * Check for APIC virtualization capabilities:
562 	 * - TPR shadowing
563 	 * - Full APICv (with or without x2APIC support)
564 	 * - Posted interrupt handling
565 	 */
566 	if (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS, MSR_VMX_TRUE_PROCBASED_CTLS,
567 	    PROCBASED_USE_TPR_SHADOW, 0, &tmp) == 0) {
568 		avail_caps |= VMX_CAP_TPR_SHADOW;
569 
570 		const uint32_t apicv_bits =
571 		    PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
572 		    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
573 		    PROCBASED2_VIRTUALIZE_X2APIC_MODE |
574 		    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY;
575 		if (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
576 		    MSR_VMX_PROCBASED_CTLS2, apicv_bits, 0, &tmp) == 0) {
577 			avail_caps |= VMX_CAP_APICV;
578 
579 			/*
580 			 * It may make sense in the future to differentiate
581 			 * hardware (or software) configurations with APICv but
582 			 * no support for accelerating x2APIC mode.
583 			 */
584 			avail_caps |= VMX_CAP_APICV_X2APIC;
585 
586 			error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
587 			    MSR_VMX_TRUE_PINBASED_CTLS,
588 			    PINBASED_POSTED_INTERRUPT, 0, &tmp);
589 			if (error == 0) {
590 				/*
591 				 * If the PSM-provided interfaces for requesting
592 				 * and using a PIR IPI vector are present, use
593 				 * them for posted interrupts.
594 				 */
595 				if (psm_get_pir_ipivect != NULL &&
596 				    psm_send_pir_ipi != NULL) {
597 					pirvec = psm_get_pir_ipivect();
598 					avail_caps |= VMX_CAP_APICV_PIR;
599 				}
600 			}
601 		}
602 	}
603 
604 	/*
605 	 * Check for necessary EPT capabilities
606 	 *
607 	 * TODO: Properly handle when IA32_VMX_EPT_VPID_HW_AD is missing and the
608 	 * hypervisor intends to utilize dirty page tracking.
609 	 */
610 	uint64_t ept_caps = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
611 	if ((ept_caps & EPT_CAPS_REQUIRED) != EPT_CAPS_REQUIRED) {
612 		cmn_err(CE_WARN, "!Inadequate EPT capabilities: %lx", ept_caps);
613 		return (EINVAL);
614 	}
615 
616 #ifdef __FreeBSD__
617 	guest_l1d_flush = (cpu_ia32_arch_caps &
618 	    IA32_ARCH_CAP_SKIP_L1DFL_VMENTRY) == 0;
619 	TUNABLE_INT_FETCH("hw.vmm.l1d_flush", &guest_l1d_flush);
620 
621 	/*
622 	 * L1D cache flush is enabled.  Use IA32_FLUSH_CMD MSR when
623 	 * available.  Otherwise fall back to the software flush
624 	 * method which loads enough data from the kernel text to
625 	 * flush existing L1D content, both on VMX entry and on NMI
626 	 * return.
627 	 */
628 	if (guest_l1d_flush) {
629 		if ((cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) == 0) {
630 			guest_l1d_flush_sw = 1;
631 			TUNABLE_INT_FETCH("hw.vmm.l1d_flush_sw",
632 			    &guest_l1d_flush_sw);
633 		}
634 		if (guest_l1d_flush_sw) {
635 			if (nmi_flush_l1d_sw <= 1)
636 				nmi_flush_l1d_sw = 1;
637 		} else {
638 			msr_load_list[0].index = MSR_IA32_FLUSH_CMD;
639 			msr_load_list[0].val = IA32_FLUSH_CMD_L1D;
640 		}
641 	}
642 #else
643 	/* L1D flushing is taken care of by smt_acquire() and friends */
644 	guest_l1d_flush = 0;
645 #endif /* __FreeBSD__ */
646 
647 	/*
648 	 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
649 	 */
650 	fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
651 	fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
652 	cr0_ones_mask = fixed0 & fixed1;
653 	cr0_zeros_mask = ~fixed0 & ~fixed1;
654 
655 	/*
656 	 * Since Unrestricted Guest was already verified present, CR0_PE and
657 	 * CR0_PG are allowed to be set to zero in VMX non-root operation
658 	 */
659 	cr0_ones_mask &= ~(CR0_PG | CR0_PE);
660 
661 	/*
662 	 * Do not allow the guest to set CR0_NW or CR0_CD.
663 	 */
664 	cr0_zeros_mask |= (CR0_NW | CR0_CD);
665 
666 	fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
667 	fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
668 	cr4_ones_mask = fixed0 & fixed1;
669 	cr4_zeros_mask = ~fixed0 & ~fixed1;
670 
671 	vmx_msr_init();
672 
673 	vmx_capabilities = avail_caps;
674 
675 	return (0);
676 }
677 
678 static void
vmx_trigger_hostintr(int vector)679 vmx_trigger_hostintr(int vector)
680 {
681 	VERIFY(vector >= 32 && vector <= 255);
682 	vmx_call_isr(vector - 32);
683 }
684 
685 static void *
vmx_vminit(struct vm * vm)686 vmx_vminit(struct vm *vm)
687 {
688 	uint16_t vpid[VM_MAXCPU];
689 	int i, error, datasel;
690 	struct vmx *vmx;
691 	uint32_t exc_bitmap;
692 	uint16_t maxcpus;
693 	uint32_t proc_ctls, proc2_ctls, pin_ctls;
694 	uint64_t apic_access_pa = UINT64_MAX;
695 
696 	vmx = kmem_zalloc(sizeof (struct vmx), KM_SLEEP);
697 	VERIFY3U((uintptr_t)vmx & PAGE_MASK, ==, 0);
698 
699 	vmx->vm = vm;
700 	vmx->eptp = vmspace_table_root(vm_get_vmspace(vm));
701 
702 	/*
703 	 * Clean up EP4TA-tagged guest-physical and combined mappings
704 	 *
705 	 * VMX transitions are not required to invalidate any guest physical
706 	 * mappings. So, it may be possible for stale guest physical mappings
707 	 * to be present in the processor TLBs.
708 	 *
709 	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
710 	 */
711 	hma_vmx_invept_allcpus((uintptr_t)vmx->eptp);
712 
713 	vmx_msr_bitmap_initialize(vmx);
714 
715 	vpid_alloc(vpid, VM_MAXCPU);
716 
717 	/* Grab the established defaults */
718 	proc_ctls = procbased_ctls;
719 	proc2_ctls = procbased_ctls2;
720 	pin_ctls = pinbased_ctls;
721 	/* For now, default to the available capabilities */
722 	vmx->vmx_caps = vmx_capabilities;
723 
724 	if (vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW)) {
725 		proc_ctls |= PROCBASED_USE_TPR_SHADOW;
726 		proc_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
727 		proc_ctls &= ~PROCBASED_CR8_STORE_EXITING;
728 	}
729 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
730 		ASSERT(vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW));
731 
732 		proc2_ctls |= (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
733 		    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
734 		    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
735 
736 		/*
737 		 * Allocate a page of memory to back the APIC access address for
738 		 * when APICv features are in use.  Guest MMIO accesses should
739 		 * never actually reach this page, but rather be intercepted.
740 		 */
741 		vmx->apic_access_page = kmem_zalloc(PAGESIZE, KM_SLEEP);
742 		VERIFY3U((uintptr_t)vmx->apic_access_page & PAGEOFFSET, ==, 0);
743 		apic_access_pa = vtophys(vmx->apic_access_page);
744 
745 		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
746 		    apic_access_pa);
747 		/* XXX this should really return an error to the caller */
748 		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
749 	}
750 	if (vmx_cap_en(vmx, VMX_CAP_APICV_PIR)) {
751 		ASSERT(vmx_cap_en(vmx, VMX_CAP_APICV));
752 
753 		pin_ctls |= PINBASED_POSTED_INTERRUPT;
754 	}
755 
756 	/* Reflect any enabled defaults in the cap set */
757 	int cap_defaults = 0;
758 	if ((proc_ctls & PROCBASED_HLT_EXITING) != 0) {
759 		cap_defaults |= (1 << VM_CAP_HALT_EXIT);
760 	}
761 	if ((proc_ctls & PROCBASED_PAUSE_EXITING) != 0) {
762 		cap_defaults |= (1 << VM_CAP_PAUSE_EXIT);
763 	}
764 	if ((proc_ctls & PROCBASED_MTF) != 0) {
765 		cap_defaults |= (1 << VM_CAP_MTRAP_EXIT);
766 	}
767 	if ((proc2_ctls & PROCBASED2_ENABLE_INVPCID) != 0) {
768 		cap_defaults |= (1 << VM_CAP_ENABLE_INVPCID);
769 	}
770 
771 	maxcpus = vm_get_maxcpus(vm);
772 	datasel = vmm_get_host_datasel();
773 	for (i = 0; i < maxcpus; i++) {
774 		/*
775 		 * Cache physical address lookups for various components which
776 		 * may be required inside the critical_enter() section implied
777 		 * by VMPTRLD() below.
778 		 */
779 		vm_paddr_t msr_bitmap_pa = vtophys(vmx->msr_bitmap[i]);
780 		vm_paddr_t apic_page_pa = vtophys(&vmx->apic_page[i]);
781 		vm_paddr_t pir_desc_pa = vtophys(&vmx->pir_desc[i]);
782 
783 		vmx->vmcs_pa[i] = (uintptr_t)vtophys(&vmx->vmcs[i]);
784 		vmcs_initialize(&vmx->vmcs[i], vmx->vmcs_pa[i]);
785 
786 		vmx_msr_guest_init(vmx, i);
787 
788 		vmcs_load(vmx->vmcs_pa[i]);
789 
790 		vmcs_write(VMCS_HOST_IA32_PAT, vmm_get_host_pat());
791 		vmcs_write(VMCS_HOST_IA32_EFER, vmm_get_host_efer());
792 
793 		/* Load the control registers */
794 		vmcs_write(VMCS_HOST_CR0, vmm_get_host_cr0());
795 		vmcs_write(VMCS_HOST_CR4, vmm_get_host_cr4() | CR4_VMXE);
796 
797 		/* Load the segment selectors */
798 		vmcs_write(VMCS_HOST_CS_SELECTOR, vmm_get_host_codesel());
799 
800 		vmcs_write(VMCS_HOST_ES_SELECTOR, datasel);
801 		vmcs_write(VMCS_HOST_SS_SELECTOR, datasel);
802 		vmcs_write(VMCS_HOST_DS_SELECTOR, datasel);
803 
804 		vmcs_write(VMCS_HOST_FS_SELECTOR, vmm_get_host_fssel());
805 		vmcs_write(VMCS_HOST_GS_SELECTOR, vmm_get_host_gssel());
806 		vmcs_write(VMCS_HOST_TR_SELECTOR, vmm_get_host_tsssel());
807 
808 		/*
809 		 * Configure host sysenter MSRs to be restored on VM exit.
810 		 * The thread-specific MSR_INTC_SEP_ESP value is loaded in
811 		 * vmx_run.
812 		 */
813 		vmcs_write(VMCS_HOST_IA32_SYSENTER_CS, KCS_SEL);
814 		vmcs_write(VMCS_HOST_IA32_SYSENTER_EIP,
815 		    rdmsr(MSR_SYSENTER_EIP_MSR));
816 
817 		/* instruction pointer */
818 		vmcs_write(VMCS_HOST_RIP, (uint64_t)vmx_exit_guest);
819 
820 		/* link pointer */
821 		vmcs_write(VMCS_LINK_POINTER, ~0);
822 
823 		vmcs_write(VMCS_EPTP, vmx->eptp);
824 		vmcs_write(VMCS_PIN_BASED_CTLS, pin_ctls);
825 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
826 
827 		uint32_t use_proc2_ctls = proc2_ctls;
828 		if (cap_wbinvd_exit && vcpu_trap_wbinvd(vm, i) != 0)
829 			use_proc2_ctls |= PROCBASED2_WBINVD_EXITING;
830 		vmcs_write(VMCS_SEC_PROC_BASED_CTLS, use_proc2_ctls);
831 
832 		vmcs_write(VMCS_EXIT_CTLS, exit_ctls);
833 		vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
834 		vmcs_write(VMCS_MSR_BITMAP, msr_bitmap_pa);
835 		vmcs_write(VMCS_VPID, vpid[i]);
836 
837 		if (guest_l1d_flush && !guest_l1d_flush_sw) {
838 			vmcs_write(VMCS_ENTRY_MSR_LOAD,
839 			    vtophys(&msr_load_list[0]));
840 			vmcs_write(VMCS_ENTRY_MSR_LOAD_COUNT,
841 			    nitems(msr_load_list));
842 			vmcs_write(VMCS_EXIT_MSR_STORE, 0);
843 			vmcs_write(VMCS_EXIT_MSR_STORE_COUNT, 0);
844 		}
845 
846 		/* exception bitmap */
847 		if (vcpu_trace_exceptions(vm, i))
848 			exc_bitmap = 0xffffffff;
849 		else
850 			exc_bitmap = 1 << IDT_MC;
851 		vmcs_write(VMCS_EXCEPTION_BITMAP, exc_bitmap);
852 
853 		vmx->ctx[i].guest_dr6 = DBREG_DR6_RESERVED1;
854 		vmcs_write(VMCS_GUEST_DR7, DBREG_DR7_RESERVED1);
855 
856 		if (vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW)) {
857 			vmcs_write(VMCS_VIRTUAL_APIC, apic_page_pa);
858 		}
859 
860 		if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
861 			vmcs_write(VMCS_APIC_ACCESS, apic_access_pa);
862 			vmcs_write(VMCS_EOI_EXIT0, 0);
863 			vmcs_write(VMCS_EOI_EXIT1, 0);
864 			vmcs_write(VMCS_EOI_EXIT2, 0);
865 			vmcs_write(VMCS_EOI_EXIT3, 0);
866 		}
867 		if (vmx_cap_en(vmx, VMX_CAP_APICV_PIR)) {
868 			vmcs_write(VMCS_PIR_VECTOR, pirvec);
869 			vmcs_write(VMCS_PIR_DESC, pir_desc_pa);
870 		}
871 
872 		/*
873 		 * Set up the CR0/4 masks and configure the read shadow state
874 		 * to the power-on register value from the Intel Sys Arch.
875 		 *  CR0 - 0x60000010
876 		 *  CR4 - 0
877 		 */
878 		vmcs_write(VMCS_CR0_MASK, cr0_ones_mask | cr0_zeros_mask);
879 		vmcs_write(VMCS_CR0_SHADOW, 0x60000010);
880 		vmcs_write(VMCS_CR4_MASK, cr4_ones_mask | cr4_zeros_mask);
881 		vmcs_write(VMCS_CR4_SHADOW, 0);
882 
883 		vmcs_clear(vmx->vmcs_pa[i]);
884 
885 		vmx->cap[i].set = cap_defaults;
886 		vmx->cap[i].proc_ctls = proc_ctls;
887 		vmx->cap[i].proc_ctls2 = proc2_ctls;
888 		vmx->cap[i].exc_bitmap = exc_bitmap;
889 
890 		vmx->state[i].nextrip = ~0;
891 		vmx->state[i].lastcpu = NOCPU;
892 		vmx->state[i].vpid = vpid[i];
893 	}
894 
895 	return (vmx);
896 }
897 
898 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
899 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
900 
901 #define	INVVPID_TYPE_ADDRESS		0UL
902 #define	INVVPID_TYPE_SINGLE_CONTEXT	1UL
903 #define	INVVPID_TYPE_ALL_CONTEXTS	2UL
904 
905 struct invvpid_desc {
906 	uint16_t	vpid;
907 	uint16_t	_res1;
908 	uint32_t	_res2;
909 	uint64_t	linear_addr;
910 };
911 CTASSERT(sizeof (struct invvpid_desc) == 16);
912 
913 static __inline void
invvpid(uint64_t type,struct invvpid_desc desc)914 invvpid(uint64_t type, struct invvpid_desc desc)
915 {
916 	int error;
917 
918 	DTRACE_PROBE3(vmx__invvpid, uint64_t, type, uint16_t, desc.vpid,
919 	    uint64_t, desc.linear_addr);
920 
921 	__asm __volatile("invvpid %[desc], %[type];"
922 	    VMX_SET_ERROR_CODE_ASM
923 	    : [error] "=r" (error)
924 	    : [desc] "m" (desc), [type] "r" (type)
925 	    : "memory");
926 
927 	if (error) {
928 		panic("invvpid error %d", error);
929 	}
930 }
931 
932 /*
933  * Invalidate guest mappings identified by its VPID from the TLB.
934  *
935  * This is effectively a flush of the guest TLB, removing only "combined
936  * mappings" (to use the VMX parlance).  Actions which modify the EPT structures
937  * for the instance (such as unmapping GPAs) would require an 'invept' flush.
938  */
939 static void
vmx_invvpid(struct vmx * vmx,int vcpu,int running)940 vmx_invvpid(struct vmx *vmx, int vcpu, int running)
941 {
942 	struct vmxstate *vmxstate;
943 	struct vmspace *vms;
944 
945 	vmxstate = &vmx->state[vcpu];
946 	if (vmxstate->vpid == 0) {
947 		return;
948 	}
949 
950 	if (!running) {
951 		/*
952 		 * Set the 'lastcpu' to an invalid host cpu.
953 		 *
954 		 * This will invalidate TLB entries tagged with the vcpu's
955 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
956 		 */
957 		vmxstate->lastcpu = NOCPU;
958 		return;
959 	}
960 
961 	/*
962 	 * Invalidate all mappings tagged with 'vpid'
963 	 *
964 	 * This is done when a vCPU moves between host CPUs, where there may be
965 	 * stale TLB entries for this VPID on the target, or if emulated actions
966 	 * in the guest CPU have incurred an explicit TLB flush.
967 	 */
968 	vms = vm_get_vmspace(vmx->vm);
969 	if (vmspace_table_gen(vms) == vmx->eptgen[curcpu]) {
970 		struct invvpid_desc invvpid_desc = {
971 			.vpid = vmxstate->vpid,
972 			.linear_addr = 0,
973 			._res1 = 0,
974 			._res2 = 0,
975 		};
976 
977 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
978 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
979 	} else {
980 		/*
981 		 * The INVVPID can be skipped if an INVEPT is going to be
982 		 * performed before entering the guest.  The INVEPT will
983 		 * invalidate combined mappings for the EP4TA associated with
984 		 * this guest, in all VPIDs.
985 		 */
986 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
987 	}
988 }
989 
990 static __inline void
invept(uint64_t type,uint64_t eptp)991 invept(uint64_t type, uint64_t eptp)
992 {
993 	int error;
994 	struct invept_desc {
995 		uint64_t eptp;
996 		uint64_t _resv;
997 	} desc = { eptp, 0 };
998 
999 	DTRACE_PROBE2(vmx__invept, uint64_t, type, uint64_t, eptp);
1000 
1001 	__asm __volatile("invept %[desc], %[type];"
1002 	    VMX_SET_ERROR_CODE_ASM
1003 	    : [error] "=r" (error)
1004 	    : [desc] "m" (desc), [type] "r" (type)
1005 	    : "memory");
1006 
1007 	if (error != 0) {
1008 		panic("invvpid error %d", error);
1009 	}
1010 }
1011 
1012 static void
vmx_set_pcpu_defaults(struct vmx * vmx,int vcpu)1013 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu)
1014 {
1015 	struct vmxstate *vmxstate;
1016 
1017 	/*
1018 	 * Regardless of whether the VM appears to have migrated between CPUs,
1019 	 * save the host sysenter stack pointer.  As it points to the kernel
1020 	 * stack of each thread, the correct value must be maintained for every
1021 	 * trip into the critical section.
1022 	 */
1023 	vmcs_write(VMCS_HOST_IA32_SYSENTER_ESP, rdmsr(MSR_SYSENTER_ESP_MSR));
1024 
1025 	/*
1026 	 * Perform any needed TSC_OFFSET adjustment based on TSC_MSR writes or
1027 	 * migration between host CPUs with differing TSC values.
1028 	 */
1029 	vmx_apply_tsc_adjust(vmx, vcpu);
1030 
1031 	vmxstate = &vmx->state[vcpu];
1032 	if (vmxstate->lastcpu == curcpu)
1033 		return;
1034 
1035 	vmxstate->lastcpu = curcpu;
1036 
1037 	vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1038 
1039 	/* Load the per-CPU IDT address */
1040 	vmcs_write(VMCS_HOST_IDTR_BASE, vmm_get_host_idtrbase());
1041 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1042 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1043 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1044 	vmx_invvpid(vmx, vcpu, 1);
1045 }
1046 
1047 static __inline bool
vmx_int_window_exiting(struct vmx * vmx,int vcpu)1048 vmx_int_window_exiting(struct vmx *vmx, int vcpu)
1049 {
1050 	return ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0);
1051 }
1052 
1053 static __inline void
vmx_set_int_window_exiting(struct vmx * vmx,int vcpu)1054 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1055 {
1056 	if (!vmx_int_window_exiting(vmx, vcpu)) {
1057 		/* Enable interrupt window exiting */
1058 		vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1059 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1060 	}
1061 }
1062 
1063 static __inline void
vmx_clear_int_window_exiting(struct vmx * vmx,int vcpu)1064 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1065 {
1066 	/* Disable interrupt window exiting */
1067 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1068 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1069 }
1070 
1071 static __inline bool
vmx_nmi_window_exiting(struct vmx * vmx,int vcpu)1072 vmx_nmi_window_exiting(struct vmx *vmx, int vcpu)
1073 {
1074 	return ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0);
1075 }
1076 
1077 static __inline void
vmx_set_nmi_window_exiting(struct vmx * vmx,int vcpu)1078 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1079 {
1080 	if (!vmx_nmi_window_exiting(vmx, vcpu)) {
1081 		vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1082 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1083 	}
1084 }
1085 
1086 static __inline void
vmx_clear_nmi_window_exiting(struct vmx * vmx,int vcpu)1087 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1088 {
1089 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1090 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1091 }
1092 
1093 /*
1094  * Set the TSC adjustment, taking into account the offsets measured between
1095  * host physical CPUs.  This is required even if the guest has not set a TSC
1096  * offset since vCPUs inherit the TSC offset of whatever physical CPU it has
1097  * migrated onto.  Without this mitigation, un-synched host TSCs will convey
1098  * the appearance of TSC time-travel to the guest as its vCPUs migrate.
1099  */
1100 static void
vmx_apply_tsc_adjust(struct vmx * vmx,int vcpu)1101 vmx_apply_tsc_adjust(struct vmx *vmx, int vcpu)
1102 {
1103 	const uint64_t offset = vcpu_tsc_offset(vmx->vm, vcpu, true);
1104 
1105 	ASSERT(vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET);
1106 
1107 	if (vmx->tsc_offset_active[vcpu] != offset) {
1108 		vmcs_write(VMCS_TSC_OFFSET, offset);
1109 		vmx->tsc_offset_active[vcpu] = offset;
1110 	}
1111 }
1112 
1113 CTASSERT(VMCS_INTR_T_HWINTR		== VM_INTINFO_HWINTR);
1114 CTASSERT(VMCS_INTR_T_NMI		== VM_INTINFO_NMI);
1115 CTASSERT(VMCS_INTR_T_HWEXCEPTION	== VM_INTINFO_HWEXCP);
1116 CTASSERT(VMCS_INTR_T_SWINTR		== VM_INTINFO_SWINTR);
1117 CTASSERT(VMCS_INTR_T_PRIV_SWEXCEPTION	== VM_INTINFO_RESV5);
1118 CTASSERT(VMCS_INTR_T_SWEXCEPTION	== VM_INTINFO_RESV6);
1119 CTASSERT(VMCS_IDT_VEC_ERRCODE_VALID	== VM_INTINFO_DEL_ERRCODE);
1120 CTASSERT(VMCS_INTR_T_MASK		== VM_INTINFO_MASK_TYPE);
1121 
1122 static uint64_t
vmx_idtvec_to_intinfo(uint32_t info,uint32_t errcode)1123 vmx_idtvec_to_intinfo(uint32_t info, uint32_t errcode)
1124 {
1125 	ASSERT(info & VMCS_IDT_VEC_VALID);
1126 
1127 	const uint32_t type = info & VMCS_INTR_T_MASK;
1128 	const uint8_t vec = info & 0xff;
1129 
1130 	switch (type) {
1131 	case VMCS_INTR_T_HWINTR:
1132 	case VMCS_INTR_T_NMI:
1133 	case VMCS_INTR_T_HWEXCEPTION:
1134 	case VMCS_INTR_T_SWINTR:
1135 	case VMCS_INTR_T_PRIV_SWEXCEPTION:
1136 	case VMCS_INTR_T_SWEXCEPTION:
1137 		break;
1138 	default:
1139 		panic("unexpected event type 0x%03x", type);
1140 	}
1141 
1142 	uint64_t intinfo = VM_INTINFO_VALID | type | vec;
1143 	if (info & VMCS_IDT_VEC_ERRCODE_VALID) {
1144 		intinfo |= (uint64_t)errcode << 32;
1145 	}
1146 
1147 	return (intinfo);
1148 }
1149 
1150 CTASSERT(VMCS_INTR_DEL_ERRCODE		== VMCS_IDT_VEC_ERRCODE_VALID);
1151 CTASSERT(VMCS_INTR_VALID		== VMCS_IDT_VEC_VALID);
1152 
1153 /*
1154  * Store VMX-specific event injection info for later handling.  This depends on
1155  * the bhyve-internal event definitions matching those in the VMCS, as ensured
1156  * by the vmx_idtvec_to_intinfo() and the related CTASSERTs.
1157  */
1158 static void
vmx_stash_intinfo(struct vmx * vmx,int vcpu)1159 vmx_stash_intinfo(struct vmx *vmx, int vcpu)
1160 {
1161 	uint64_t info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1162 	if ((info & VMCS_INTR_VALID) != 0) {
1163 		uint32_t errcode = 0;
1164 
1165 		if ((info & VMCS_INTR_DEL_ERRCODE) != 0) {
1166 			errcode = vmcs_read(VMCS_ENTRY_EXCEPTION_ERROR);
1167 		}
1168 
1169 		VERIFY0(vm_exit_intinfo(vmx->vm, vcpu,
1170 		    vmx_idtvec_to_intinfo(info, errcode)));
1171 
1172 		vmcs_write(VMCS_ENTRY_INTR_INFO, 0);
1173 		vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, 0);
1174 	}
1175 }
1176 
1177 static void
vmx_inject_intinfo(uint64_t info)1178 vmx_inject_intinfo(uint64_t info)
1179 {
1180 	ASSERT(VM_INTINFO_PENDING(info));
1181 	ASSERT0(info & VM_INTINFO_MASK_RSVD);
1182 
1183 	/*
1184 	 * The bhyve format matches that of the VMCS, which is ensured by the
1185 	 * CTASSERTs above.
1186 	 */
1187 	uint32_t inject = info;
1188 	switch (VM_INTINFO_VECTOR(info)) {
1189 	case IDT_BP:
1190 	case IDT_OF:
1191 		/*
1192 		 * VT-x requires #BP and #OF to be injected as software
1193 		 * exceptions.
1194 		 */
1195 		inject &= ~VMCS_INTR_T_MASK;
1196 		inject |= VMCS_INTR_T_SWEXCEPTION;
1197 		break;
1198 	default:
1199 		break;
1200 	}
1201 
1202 	if (VM_INTINFO_HAS_ERRCODE(info)) {
1203 		vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR,
1204 		    VM_INTINFO_ERRCODE(info));
1205 	}
1206 	vmcs_write(VMCS_ENTRY_INTR_INFO, inject);
1207 }
1208 
1209 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1210 			VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1211 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1212 			VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1213 
1214 static void
vmx_inject_nmi(struct vmx * vmx,int vcpu)1215 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1216 {
1217 	ASSERT0(vmcs_read(VMCS_GUEST_INTERRUPTIBILITY) & NMI_BLOCKING);
1218 	ASSERT0(vmcs_read(VMCS_ENTRY_INTR_INFO) & VMCS_INTR_VALID);
1219 
1220 	/*
1221 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1222 	 * or the VMCS entry check will fail.
1223 	 */
1224 	vmcs_write(VMCS_ENTRY_INTR_INFO,
1225 	    IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID);
1226 
1227 	/* Clear the request */
1228 	vm_nmi_clear(vmx->vm, vcpu);
1229 }
1230 
1231 /*
1232  * Inject exceptions, NMIs, and ExtINTs.
1233  *
1234  * The logic behind these are complicated and may involve mutex contention, so
1235  * the injection is performed without the protection of host CPU interrupts
1236  * being disabled.  This means a racing notification could be "lost",
1237  * necessitating a later call to vmx_inject_recheck() to close that window
1238  * of opportunity.
1239  */
1240 static enum event_inject_state
vmx_inject_events(struct vmx * vmx,int vcpu,uint64_t rip)1241 vmx_inject_events(struct vmx *vmx, int vcpu, uint64_t rip)
1242 {
1243 	uint64_t entryinfo;
1244 	uint32_t gi, info;
1245 	int vector;
1246 	enum event_inject_state state;
1247 
1248 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1249 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1250 	state = EIS_CAN_INJECT;
1251 
1252 	/* Clear any interrupt blocking if the guest %rip has changed */
1253 	if (vmx->state[vcpu].nextrip != rip && (gi & HWINTR_BLOCKING) != 0) {
1254 		gi &= ~HWINTR_BLOCKING;
1255 		vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1256 	}
1257 
1258 	/*
1259 	 * It could be that an interrupt is already pending for injection from
1260 	 * the VMCS.  This would be the case if the vCPU exited for conditions
1261 	 * such as an AST before a vm-entry delivered the injection.
1262 	 */
1263 	if ((info & VMCS_INTR_VALID) != 0) {
1264 		return (EIS_EV_EXISTING | EIS_REQ_EXIT);
1265 	}
1266 
1267 	if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1268 		vmx_inject_intinfo(entryinfo);
1269 		state = EIS_EV_INJECTED;
1270 	}
1271 
1272 	if (vm_nmi_pending(vmx->vm, vcpu)) {
1273 		/*
1274 		 * If there are no conditions blocking NMI injection then inject
1275 		 * it directly here otherwise enable "NMI window exiting" to
1276 		 * inject it as soon as we can.
1277 		 *
1278 		 * According to the Intel manual, some CPUs do not allow NMI
1279 		 * injection when STI_BLOCKING is active.  That check is
1280 		 * enforced here, regardless of CPU capability.  If running on a
1281 		 * CPU without such a restriction it will immediately exit and
1282 		 * the NMI will be injected in the "NMI window exiting" handler.
1283 		 */
1284 		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1285 			if (state == EIS_CAN_INJECT) {
1286 				vmx_inject_nmi(vmx, vcpu);
1287 				state = EIS_EV_INJECTED;
1288 			} else {
1289 				return (state | EIS_REQ_EXIT);
1290 			}
1291 		} else {
1292 			vmx_set_nmi_window_exiting(vmx, vcpu);
1293 		}
1294 	}
1295 
1296 	if (vm_extint_pending(vmx->vm, vcpu)) {
1297 		if (state != EIS_CAN_INJECT) {
1298 			return (state | EIS_REQ_EXIT);
1299 		}
1300 		if ((gi & HWINTR_BLOCKING) != 0 ||
1301 		    (vmcs_read(VMCS_GUEST_RFLAGS) & PSL_I) == 0) {
1302 			return (EIS_GI_BLOCK);
1303 		}
1304 
1305 		/* Ask the legacy pic for a vector to inject */
1306 		vatpic_pending_intr(vmx->vm, &vector);
1307 
1308 		/*
1309 		 * From the Intel SDM, Volume 3, Section "Maskable
1310 		 * Hardware Interrupts":
1311 		 * - maskable interrupt vectors [0,255] can be delivered
1312 		 *   through the INTR pin.
1313 		 */
1314 		KASSERT(vector >= 0 && vector <= 255,
1315 		    ("invalid vector %d from INTR", vector));
1316 
1317 		/* Inject the interrupt */
1318 		vmcs_write(VMCS_ENTRY_INTR_INFO,
1319 		    VMCS_INTR_T_HWINTR | VMCS_INTR_VALID | vector);
1320 
1321 		vm_extint_clear(vmx->vm, vcpu);
1322 		vatpic_intr_accepted(vmx->vm, vector);
1323 		state = EIS_EV_INJECTED;
1324 	}
1325 
1326 	return (state);
1327 }
1328 
1329 /*
1330  * Inject any interrupts pending on the vLAPIC.
1331  *
1332  * This is done with host CPU interrupts disabled so notification IPIs, either
1333  * from the standard vCPU notification or APICv posted interrupts, will be
1334  * queued on the host APIC and recognized when entering VMX context.
1335  */
1336 static enum event_inject_state
vmx_inject_vlapic(struct vmx * vmx,int vcpu,struct vlapic * vlapic)1337 vmx_inject_vlapic(struct vmx *vmx, int vcpu, struct vlapic *vlapic)
1338 {
1339 	int vector;
1340 
1341 	if (!vlapic_pending_intr(vlapic, &vector)) {
1342 		return (EIS_CAN_INJECT);
1343 	}
1344 
1345 	/*
1346 	 * From the Intel SDM, Volume 3, Section "Maskable
1347 	 * Hardware Interrupts":
1348 	 * - maskable interrupt vectors [16,255] can be delivered
1349 	 *   through the local APIC.
1350 	 */
1351 	KASSERT(vector >= 16 && vector <= 255,
1352 	    ("invalid vector %d from local APIC", vector));
1353 
1354 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
1355 		uint16_t status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
1356 		uint16_t status_new = (status_old & 0xff00) | vector;
1357 
1358 		/*
1359 		 * The APICv state will have been synced into the vLAPIC
1360 		 * as part of vlapic_pending_intr().  Prepare the VMCS
1361 		 * for the to-be-injected pending interrupt.
1362 		 */
1363 		if (status_new > status_old) {
1364 			vmcs_write(VMCS_GUEST_INTR_STATUS, status_new);
1365 		}
1366 
1367 		/*
1368 		 * Ensure VMCS state regarding EOI traps is kept in sync
1369 		 * with the TMRs in the vlapic.
1370 		 */
1371 		vmx_apicv_sync_tmr(vlapic);
1372 
1373 		/*
1374 		 * The rest of the injection process for injecting the
1375 		 * interrupt(s) is handled by APICv. It does not preclude other
1376 		 * event injection from occurring.
1377 		 */
1378 		return (EIS_CAN_INJECT);
1379 	}
1380 
1381 	ASSERT0(vmcs_read(VMCS_ENTRY_INTR_INFO) & VMCS_INTR_VALID);
1382 
1383 	/* Does guest interruptability block injection? */
1384 	if ((vmcs_read(VMCS_GUEST_INTERRUPTIBILITY) & HWINTR_BLOCKING) != 0 ||
1385 	    (vmcs_read(VMCS_GUEST_RFLAGS) & PSL_I) == 0) {
1386 		return (EIS_GI_BLOCK);
1387 	}
1388 
1389 	/* Inject the interrupt */
1390 	vmcs_write(VMCS_ENTRY_INTR_INFO,
1391 	    VMCS_INTR_T_HWINTR | VMCS_INTR_VALID | vector);
1392 
1393 	/* Update the Local APIC ISR */
1394 	vlapic_intr_accepted(vlapic, vector);
1395 
1396 	return (EIS_EV_INJECTED);
1397 }
1398 
1399 /*
1400  * Re-check for events to be injected.
1401  *
1402  * Once host CPU interrupts are disabled, check for the presence of any events
1403  * which require injection processing.  If an exit is required upon injection,
1404  * or once the guest becomes interruptable, that will be configured too.
1405  */
1406 static bool
vmx_inject_recheck(struct vmx * vmx,int vcpu,enum event_inject_state state)1407 vmx_inject_recheck(struct vmx *vmx, int vcpu, enum event_inject_state state)
1408 {
1409 	if (state == EIS_CAN_INJECT) {
1410 		if (vm_nmi_pending(vmx->vm, vcpu) &&
1411 		    !vmx_nmi_window_exiting(vmx, vcpu)) {
1412 			/* queued NMI not blocked by NMI-window-exiting */
1413 			return (true);
1414 		}
1415 		if (vm_extint_pending(vmx->vm, vcpu)) {
1416 			/* queued ExtINT not blocked by existing injection */
1417 			return (true);
1418 		}
1419 	} else {
1420 		if ((state & EIS_REQ_EXIT) != 0) {
1421 			/*
1422 			 * Use a self-IPI to force an immediate exit after
1423 			 * event injection has occurred.
1424 			 */
1425 			poke_cpu(CPU->cpu_id);
1426 		} else {
1427 			/*
1428 			 * If any event is being injected, an exit immediately
1429 			 * upon becoming interruptable again will allow pending
1430 			 * or newly queued events to be injected in a timely
1431 			 * manner.
1432 			 */
1433 			vmx_set_int_window_exiting(vmx, vcpu);
1434 		}
1435 	}
1436 	return (false);
1437 }
1438 
1439 /*
1440  * If the Virtual NMIs execution control is '1' then the logical processor
1441  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1442  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1443  * virtual-NMI blocking.
1444  *
1445  * This unblocking occurs even if the IRET causes a fault. In this case the
1446  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1447  */
1448 static void
vmx_restore_nmi_blocking(struct vmx * vmx,int vcpuid)1449 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1450 {
1451 	uint32_t gi;
1452 
1453 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1454 	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1455 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1456 }
1457 
1458 static void
vmx_clear_nmi_blocking(struct vmx * vmx,int vcpuid)1459 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1460 {
1461 	uint32_t gi;
1462 
1463 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1464 	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1465 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1466 }
1467 
1468 static void
vmx_assert_nmi_blocking(struct vmx * vmx,int vcpuid)1469 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1470 {
1471 	uint32_t gi;
1472 
1473 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1474 	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1475 	    ("NMI blocking is not in effect %x", gi));
1476 }
1477 
1478 static int
vmx_emulate_xsetbv(struct vmx * vmx,int vcpu,struct vm_exit * vmexit)1479 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1480 {
1481 	struct vmxctx *vmxctx;
1482 	uint64_t xcrval;
1483 	const struct xsave_limits *limits;
1484 
1485 	vmxctx = &vmx->ctx[vcpu];
1486 	limits = vmm_get_xsave_limits();
1487 
1488 	/*
1489 	 * Note that the processor raises a GP# fault on its own if
1490 	 * xsetbv is executed for CPL != 0, so we do not have to
1491 	 * emulate that fault here.
1492 	 */
1493 
1494 	/* Only xcr0 is supported. */
1495 	if (vmxctx->guest_rcx != 0) {
1496 		vm_inject_gp(vmx->vm, vcpu);
1497 		return (HANDLED);
1498 	}
1499 
1500 	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1501 	if (!limits->xsave_enabled ||
1502 	    !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1503 		vm_inject_ud(vmx->vm, vcpu);
1504 		return (HANDLED);
1505 	}
1506 
1507 	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1508 	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1509 		vm_inject_gp(vmx->vm, vcpu);
1510 		return (HANDLED);
1511 	}
1512 
1513 	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1514 		vm_inject_gp(vmx->vm, vcpu);
1515 		return (HANDLED);
1516 	}
1517 
1518 	/* AVX (YMM_Hi128) requires SSE. */
1519 	if (xcrval & XFEATURE_ENABLED_AVX &&
1520 	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1521 		vm_inject_gp(vmx->vm, vcpu);
1522 		return (HANDLED);
1523 	}
1524 
1525 	/*
1526 	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1527 	 * ZMM_Hi256, and Hi16_ZMM.
1528 	 */
1529 	if (xcrval & XFEATURE_AVX512 &&
1530 	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1531 	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1532 		vm_inject_gp(vmx->vm, vcpu);
1533 		return (HANDLED);
1534 	}
1535 
1536 	/*
1537 	 * Intel MPX requires both bound register state flags to be
1538 	 * set.
1539 	 */
1540 	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1541 	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1542 		vm_inject_gp(vmx->vm, vcpu);
1543 		return (HANDLED);
1544 	}
1545 
1546 	/*
1547 	 * This runs "inside" vmrun() with the guest's FPU state, so
1548 	 * modifying xcr0 directly modifies the guest's xcr0, not the
1549 	 * host's.
1550 	 */
1551 	load_xcr(0, xcrval);
1552 	return (HANDLED);
1553 }
1554 
1555 static uint64_t
vmx_get_guest_reg(struct vmx * vmx,int vcpu,int ident)1556 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1557 {
1558 	const struct vmxctx *vmxctx;
1559 
1560 	vmxctx = &vmx->ctx[vcpu];
1561 
1562 	switch (ident) {
1563 	case 0:
1564 		return (vmxctx->guest_rax);
1565 	case 1:
1566 		return (vmxctx->guest_rcx);
1567 	case 2:
1568 		return (vmxctx->guest_rdx);
1569 	case 3:
1570 		return (vmxctx->guest_rbx);
1571 	case 4:
1572 		return (vmcs_read(VMCS_GUEST_RSP));
1573 	case 5:
1574 		return (vmxctx->guest_rbp);
1575 	case 6:
1576 		return (vmxctx->guest_rsi);
1577 	case 7:
1578 		return (vmxctx->guest_rdi);
1579 	case 8:
1580 		return (vmxctx->guest_r8);
1581 	case 9:
1582 		return (vmxctx->guest_r9);
1583 	case 10:
1584 		return (vmxctx->guest_r10);
1585 	case 11:
1586 		return (vmxctx->guest_r11);
1587 	case 12:
1588 		return (vmxctx->guest_r12);
1589 	case 13:
1590 		return (vmxctx->guest_r13);
1591 	case 14:
1592 		return (vmxctx->guest_r14);
1593 	case 15:
1594 		return (vmxctx->guest_r15);
1595 	default:
1596 		panic("invalid vmx register %d", ident);
1597 	}
1598 }
1599 
1600 static void
vmx_set_guest_reg(struct vmx * vmx,int vcpu,int ident,uint64_t regval)1601 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1602 {
1603 	struct vmxctx *vmxctx;
1604 
1605 	vmxctx = &vmx->ctx[vcpu];
1606 
1607 	switch (ident) {
1608 	case 0:
1609 		vmxctx->guest_rax = regval;
1610 		break;
1611 	case 1:
1612 		vmxctx->guest_rcx = regval;
1613 		break;
1614 	case 2:
1615 		vmxctx->guest_rdx = regval;
1616 		break;
1617 	case 3:
1618 		vmxctx->guest_rbx = regval;
1619 		break;
1620 	case 4:
1621 		vmcs_write(VMCS_GUEST_RSP, regval);
1622 		break;
1623 	case 5:
1624 		vmxctx->guest_rbp = regval;
1625 		break;
1626 	case 6:
1627 		vmxctx->guest_rsi = regval;
1628 		break;
1629 	case 7:
1630 		vmxctx->guest_rdi = regval;
1631 		break;
1632 	case 8:
1633 		vmxctx->guest_r8 = regval;
1634 		break;
1635 	case 9:
1636 		vmxctx->guest_r9 = regval;
1637 		break;
1638 	case 10:
1639 		vmxctx->guest_r10 = regval;
1640 		break;
1641 	case 11:
1642 		vmxctx->guest_r11 = regval;
1643 		break;
1644 	case 12:
1645 		vmxctx->guest_r12 = regval;
1646 		break;
1647 	case 13:
1648 		vmxctx->guest_r13 = regval;
1649 		break;
1650 	case 14:
1651 		vmxctx->guest_r14 = regval;
1652 		break;
1653 	case 15:
1654 		vmxctx->guest_r15 = regval;
1655 		break;
1656 	default:
1657 		panic("invalid vmx register %d", ident);
1658 	}
1659 }
1660 
1661 static void
vmx_sync_efer_state(struct vmx * vmx,int vcpu,uint64_t efer)1662 vmx_sync_efer_state(struct vmx *vmx, int vcpu, uint64_t efer)
1663 {
1664 	uint64_t ctrl;
1665 
1666 	/*
1667 	 * If the "load EFER" VM-entry control is 1 (which we require) then the
1668 	 * value of EFER.LMA must be identical to "IA-32e mode guest" bit in the
1669 	 * VM-entry control.
1670 	 */
1671 	ctrl = vmcs_read(VMCS_ENTRY_CTLS);
1672 	if ((efer & EFER_LMA) != 0) {
1673 		ctrl |= VM_ENTRY_GUEST_LMA;
1674 	} else {
1675 		ctrl &= ~VM_ENTRY_GUEST_LMA;
1676 	}
1677 	vmcs_write(VMCS_ENTRY_CTLS, ctrl);
1678 }
1679 
1680 static int
vmx_emulate_cr0_access(struct vmx * vmx,int vcpu,uint64_t exitqual)1681 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1682 {
1683 	uint64_t crval, regval;
1684 
1685 	/* We only handle mov to %cr0 at this time */
1686 	if ((exitqual & 0xf0) != 0x00)
1687 		return (UNHANDLED);
1688 
1689 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1690 
1691 	vmcs_write(VMCS_CR0_SHADOW, regval);
1692 
1693 	crval = regval | cr0_ones_mask;
1694 	crval &= ~cr0_zeros_mask;
1695 
1696 	const uint64_t old = vmcs_read(VMCS_GUEST_CR0);
1697 	const uint64_t diff = crval ^ old;
1698 	/* Flush the TLB if the paging or write-protect bits are changing */
1699 	if ((diff & CR0_PG) != 0 || (diff & CR0_WP) != 0) {
1700 		vmx_invvpid(vmx, vcpu, 1);
1701 	}
1702 
1703 	vmcs_write(VMCS_GUEST_CR0, crval);
1704 
1705 	if (regval & CR0_PG) {
1706 		uint64_t efer;
1707 
1708 		/* Keep EFER.LMA properly updated if paging is enabled */
1709 		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1710 		if (efer & EFER_LME) {
1711 			efer |= EFER_LMA;
1712 			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1713 			vmx_sync_efer_state(vmx, vcpu, efer);
1714 		}
1715 	}
1716 
1717 	return (HANDLED);
1718 }
1719 
1720 static int
vmx_emulate_cr4_access(struct vmx * vmx,int vcpu,uint64_t exitqual)1721 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1722 {
1723 	uint64_t crval, regval;
1724 
1725 	/* We only handle mov to %cr4 at this time */
1726 	if ((exitqual & 0xf0) != 0x00)
1727 		return (UNHANDLED);
1728 
1729 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1730 
1731 	vmcs_write(VMCS_CR4_SHADOW, regval);
1732 
1733 	crval = regval | cr4_ones_mask;
1734 	crval &= ~cr4_zeros_mask;
1735 	vmcs_write(VMCS_GUEST_CR4, crval);
1736 
1737 	return (HANDLED);
1738 }
1739 
1740 static int
vmx_emulate_cr8_access(struct vmx * vmx,int vcpu,uint64_t exitqual)1741 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1742 {
1743 	struct vlapic *vlapic;
1744 	uint64_t cr8;
1745 	int regnum;
1746 
1747 	/* We only handle mov %cr8 to/from a register at this time. */
1748 	if ((exitqual & 0xe0) != 0x00) {
1749 		return (UNHANDLED);
1750 	}
1751 
1752 	vlapic = vm_lapic(vmx->vm, vcpu);
1753 	regnum = (exitqual >> 8) & 0xf;
1754 	if (exitqual & 0x10) {
1755 		cr8 = vlapic_get_cr8(vlapic);
1756 		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1757 	} else {
1758 		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1759 		vlapic_set_cr8(vlapic, cr8);
1760 	}
1761 
1762 	return (HANDLED);
1763 }
1764 
1765 /*
1766  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1767  */
1768 static int
vmx_cpl(void)1769 vmx_cpl(void)
1770 {
1771 	uint32_t ssar;
1772 
1773 	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1774 	return ((ssar >> 5) & 0x3);
1775 }
1776 
1777 static enum vm_cpu_mode
vmx_cpu_mode(void)1778 vmx_cpu_mode(void)
1779 {
1780 	uint32_t csar;
1781 
1782 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1783 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1784 		if (csar & 0x2000)
1785 			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1786 		else
1787 			return (CPU_MODE_COMPATIBILITY);
1788 	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1789 		return (CPU_MODE_PROTECTED);
1790 	} else {
1791 		return (CPU_MODE_REAL);
1792 	}
1793 }
1794 
1795 static enum vm_paging_mode
vmx_paging_mode(void)1796 vmx_paging_mode(void)
1797 {
1798 
1799 	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1800 		return (PAGING_MODE_FLAT);
1801 	if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1802 		return (PAGING_MODE_32);
1803 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1804 		return (PAGING_MODE_64);
1805 	else
1806 		return (PAGING_MODE_PAE);
1807 }
1808 
1809 static void
vmx_paging_info(struct vm_guest_paging * paging)1810 vmx_paging_info(struct vm_guest_paging *paging)
1811 {
1812 	paging->cr3 = vmcs_read(VMCS_GUEST_CR3);
1813 	paging->cpl = vmx_cpl();
1814 	paging->cpu_mode = vmx_cpu_mode();
1815 	paging->paging_mode = vmx_paging_mode();
1816 }
1817 
1818 static void
vmexit_mmio_emul(struct vm_exit * vmexit,struct vie * vie,uint64_t gpa,uint64_t gla)1819 vmexit_mmio_emul(struct vm_exit *vmexit, struct vie *vie, uint64_t gpa,
1820     uint64_t gla)
1821 {
1822 	struct vm_guest_paging paging;
1823 	uint32_t csar;
1824 
1825 	vmexit->exitcode = VM_EXITCODE_MMIO_EMUL;
1826 	vmexit->inst_length = 0;
1827 	vmexit->u.mmio_emul.gpa = gpa;
1828 	vmexit->u.mmio_emul.gla = gla;
1829 	vmx_paging_info(&paging);
1830 
1831 	switch (paging.cpu_mode) {
1832 	case CPU_MODE_REAL:
1833 		vmexit->u.mmio_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1834 		vmexit->u.mmio_emul.cs_d = 0;
1835 		break;
1836 	case CPU_MODE_PROTECTED:
1837 	case CPU_MODE_COMPATIBILITY:
1838 		vmexit->u.mmio_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1839 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1840 		vmexit->u.mmio_emul.cs_d = SEG_DESC_DEF32(csar);
1841 		break;
1842 	default:
1843 		vmexit->u.mmio_emul.cs_base = 0;
1844 		vmexit->u.mmio_emul.cs_d = 0;
1845 		break;
1846 	}
1847 
1848 	vie_init_mmio(vie, NULL, 0, &paging, gpa);
1849 }
1850 
1851 static void
vmexit_inout(struct vm_exit * vmexit,struct vie * vie,uint64_t qual,uint32_t eax)1852 vmexit_inout(struct vm_exit *vmexit, struct vie *vie, uint64_t qual,
1853     uint32_t eax)
1854 {
1855 	struct vm_guest_paging paging;
1856 	struct vm_inout *inout;
1857 
1858 	inout = &vmexit->u.inout;
1859 
1860 	inout->bytes = (qual & 0x7) + 1;
1861 	inout->flags = 0;
1862 	inout->flags |= (qual & 0x8) ? INOUT_IN : 0;
1863 	inout->flags |= (qual & 0x10) ? INOUT_STR : 0;
1864 	inout->flags |= (qual & 0x20) ? INOUT_REP : 0;
1865 	inout->port = (uint16_t)(qual >> 16);
1866 	inout->eax = eax;
1867 	if (inout->flags & INOUT_STR) {
1868 		uint64_t inst_info;
1869 
1870 		inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
1871 
1872 		/*
1873 		 * According to the SDM, bits 9:7 encode the address size of the
1874 		 * ins/outs operation, but only values 0/1/2 are expected,
1875 		 * corresponding to 16/32/64 bit sizes.
1876 		 */
1877 		inout->addrsize = 2 << BITX(inst_info, 9, 7);
1878 		VERIFY(inout->addrsize == 2 || inout->addrsize == 4 ||
1879 		    inout->addrsize == 8);
1880 
1881 		if (inout->flags & INOUT_IN) {
1882 			/*
1883 			 * The bits describing the segment in INSTRUCTION_INFO
1884 			 * are not defined for ins, leaving it to system
1885 			 * software to assume %es (encoded as 0)
1886 			 */
1887 			inout->segment = 0;
1888 		} else {
1889 			/*
1890 			 * Bits 15-17 encode the segment for OUTS.
1891 			 * This value follows the standard x86 segment order.
1892 			 */
1893 			inout->segment = (inst_info >> 15) & 0x7;
1894 		}
1895 	}
1896 
1897 	vmexit->exitcode = VM_EXITCODE_INOUT;
1898 	vmx_paging_info(&paging);
1899 	vie_init_inout(vie, inout, vmexit->inst_length, &paging);
1900 
1901 	/* The in/out emulation will handle advancing %rip */
1902 	vmexit->inst_length = 0;
1903 }
1904 
1905 static int
ept_fault_type(uint64_t ept_qual)1906 ept_fault_type(uint64_t ept_qual)
1907 {
1908 	int fault_type;
1909 
1910 	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1911 		fault_type = PROT_WRITE;
1912 	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1913 		fault_type = PROT_EXEC;
1914 	else
1915 		fault_type = PROT_READ;
1916 
1917 	return (fault_type);
1918 }
1919 
1920 static bool
ept_emulation_fault(uint64_t ept_qual)1921 ept_emulation_fault(uint64_t ept_qual)
1922 {
1923 	int read, write;
1924 
1925 	/* EPT fault on an instruction fetch doesn't make sense here */
1926 	if (ept_qual & EPT_VIOLATION_INST_FETCH)
1927 		return (false);
1928 
1929 	/* EPT fault must be a read fault or a write fault */
1930 	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1931 	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1932 	if ((read | write) == 0)
1933 		return (false);
1934 
1935 	/*
1936 	 * The EPT violation must have been caused by accessing a
1937 	 * guest-physical address that is a translation of a guest-linear
1938 	 * address.
1939 	 */
1940 	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1941 	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1942 		return (false);
1943 	}
1944 
1945 	return (true);
1946 }
1947 
1948 static __inline int
apic_access_virtualization(struct vmx * vmx,int vcpuid)1949 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1950 {
1951 	uint32_t proc_ctls2;
1952 
1953 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1954 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1955 }
1956 
1957 static __inline int
x2apic_virtualization(struct vmx * vmx,int vcpuid)1958 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1959 {
1960 	uint32_t proc_ctls2;
1961 
1962 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1963 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1964 }
1965 
1966 static int
vmx_handle_apic_write(struct vmx * vmx,int vcpuid,struct vlapic * vlapic,uint64_t qual)1967 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1968     uint64_t qual)
1969 {
1970 	const uint_t offset = APIC_WRITE_OFFSET(qual);
1971 
1972 	if (!apic_access_virtualization(vmx, vcpuid)) {
1973 		/*
1974 		 * In general there should not be any APIC write VM-exits
1975 		 * unless APIC-access virtualization is enabled.
1976 		 *
1977 		 * However self-IPI virtualization can legitimately trigger
1978 		 * an APIC-write VM-exit so treat it specially.
1979 		 */
1980 		if (x2apic_virtualization(vmx, vcpuid) &&
1981 		    offset == APIC_OFFSET_SELF_IPI) {
1982 			const uint32_t *apic_regs =
1983 			    (uint32_t *)(vlapic->apic_page);
1984 			const uint32_t vector =
1985 			    apic_regs[APIC_OFFSET_SELF_IPI / 4];
1986 
1987 			vlapic_self_ipi_handler(vlapic, vector);
1988 			return (HANDLED);
1989 		} else
1990 			return (UNHANDLED);
1991 	}
1992 
1993 	switch (offset) {
1994 	case APIC_OFFSET_ID:
1995 		vlapic_id_write_handler(vlapic);
1996 		break;
1997 	case APIC_OFFSET_LDR:
1998 		vlapic_ldr_write_handler(vlapic);
1999 		break;
2000 	case APIC_OFFSET_DFR:
2001 		vlapic_dfr_write_handler(vlapic);
2002 		break;
2003 	case APIC_OFFSET_SVR:
2004 		vlapic_svr_write_handler(vlapic);
2005 		break;
2006 	case APIC_OFFSET_ESR:
2007 		vlapic_esr_write_handler(vlapic);
2008 		break;
2009 	case APIC_OFFSET_ICR_LOW:
2010 		vlapic_icrlo_write_handler(vlapic);
2011 		break;
2012 	case APIC_OFFSET_CMCI_LVT:
2013 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
2014 		vlapic_lvt_write_handler(vlapic, offset);
2015 		break;
2016 	case APIC_OFFSET_TIMER_ICR:
2017 		vlapic_icrtmr_write_handler(vlapic);
2018 		break;
2019 	case APIC_OFFSET_TIMER_DCR:
2020 		vlapic_dcr_write_handler(vlapic);
2021 		break;
2022 	default:
2023 		return (UNHANDLED);
2024 	}
2025 	return (HANDLED);
2026 }
2027 
2028 static bool
apic_access_fault(struct vmx * vmx,int vcpuid,uint64_t gpa)2029 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
2030 {
2031 
2032 	if (apic_access_virtualization(vmx, vcpuid) &&
2033 	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
2034 		return (true);
2035 	else
2036 		return (false);
2037 }
2038 
2039 static int
vmx_handle_apic_access(struct vmx * vmx,int vcpuid,struct vm_exit * vmexit)2040 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2041 {
2042 	uint64_t qual;
2043 	int access_type, offset, allowed;
2044 	struct vie *vie;
2045 
2046 	if (!apic_access_virtualization(vmx, vcpuid))
2047 		return (UNHANDLED);
2048 
2049 	qual = vmexit->u.vmx.exit_qualification;
2050 	access_type = APIC_ACCESS_TYPE(qual);
2051 	offset = APIC_ACCESS_OFFSET(qual);
2052 
2053 	allowed = 0;
2054 	if (access_type == 0) {
2055 		/*
2056 		 * Read data access to the following registers is expected.
2057 		 */
2058 		switch (offset) {
2059 		case APIC_OFFSET_APR:
2060 		case APIC_OFFSET_PPR:
2061 		case APIC_OFFSET_RRR:
2062 		case APIC_OFFSET_CMCI_LVT:
2063 		case APIC_OFFSET_TIMER_CCR:
2064 			allowed = 1;
2065 			break;
2066 		default:
2067 			break;
2068 		}
2069 	} else if (access_type == 1) {
2070 		/*
2071 		 * Write data access to the following registers is expected.
2072 		 */
2073 		switch (offset) {
2074 		case APIC_OFFSET_VER:
2075 		case APIC_OFFSET_APR:
2076 		case APIC_OFFSET_PPR:
2077 		case APIC_OFFSET_RRR:
2078 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2079 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2080 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2081 		case APIC_OFFSET_CMCI_LVT:
2082 		case APIC_OFFSET_TIMER_CCR:
2083 			allowed = 1;
2084 			break;
2085 		default:
2086 			break;
2087 		}
2088 	}
2089 
2090 	if (allowed) {
2091 		vie = vm_vie_ctx(vmx->vm, vcpuid);
2092 		vmexit_mmio_emul(vmexit, vie, DEFAULT_APIC_BASE + offset,
2093 		    VIE_INVALID_GLA);
2094 	}
2095 
2096 	/*
2097 	 * Regardless of whether the APIC-access is allowed this handler
2098 	 * always returns UNHANDLED:
2099 	 * - if the access is allowed then it is handled by emulating the
2100 	 *   instruction that caused the VM-exit (outside the critical section)
2101 	 * - if the access is not allowed then it will be converted to an
2102 	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2103 	 */
2104 	return (UNHANDLED);
2105 }
2106 
2107 static enum task_switch_reason
vmx_task_switch_reason(uint64_t qual)2108 vmx_task_switch_reason(uint64_t qual)
2109 {
2110 	int reason;
2111 
2112 	reason = (qual >> 30) & 0x3;
2113 	switch (reason) {
2114 	case 0:
2115 		return (TSR_CALL);
2116 	case 1:
2117 		return (TSR_IRET);
2118 	case 2:
2119 		return (TSR_JMP);
2120 	case 3:
2121 		return (TSR_IDT_GATE);
2122 	default:
2123 		panic("%s: invalid reason %d", __func__, reason);
2124 	}
2125 }
2126 
2127 static int
vmx_handle_msr(struct vmx * vmx,int vcpuid,struct vm_exit * vmexit,bool is_wrmsr)2128 vmx_handle_msr(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit,
2129     bool is_wrmsr)
2130 {
2131 	struct vmxctx *vmxctx = &vmx->ctx[vcpuid];
2132 	const uint32_t ecx = vmxctx->guest_rcx;
2133 	vm_msr_result_t res;
2134 	uint64_t val = 0;
2135 
2136 	if (is_wrmsr) {
2137 		vmm_stat_incr(vmx->vm, vcpuid, VMEXIT_WRMSR, 1);
2138 		val = vmxctx->guest_rdx << 32 | (uint32_t)vmxctx->guest_rax;
2139 
2140 		if (vlapic_owned_msr(ecx)) {
2141 			struct vlapic *vlapic = vm_lapic(vmx->vm, vcpuid);
2142 
2143 			res = vlapic_wrmsr(vlapic, ecx, val);
2144 		} else {
2145 			res = vmx_wrmsr(vmx, vcpuid, ecx, val);
2146 		}
2147 	} else {
2148 		vmm_stat_incr(vmx->vm, vcpuid, VMEXIT_RDMSR, 1);
2149 
2150 		if (vlapic_owned_msr(ecx)) {
2151 			struct vlapic *vlapic = vm_lapic(vmx->vm, vcpuid);
2152 
2153 			res = vlapic_rdmsr(vlapic, ecx, &val);
2154 		} else {
2155 			res = vmx_rdmsr(vmx, vcpuid, ecx, &val);
2156 		}
2157 	}
2158 
2159 	switch (res) {
2160 	case VMR_OK:
2161 		/* Store rdmsr result in the appropriate registers */
2162 		if (!is_wrmsr) {
2163 			vmxctx->guest_rax = (uint32_t)val;
2164 			vmxctx->guest_rdx = val >> 32;
2165 		}
2166 		return (HANDLED);
2167 	case VMR_GP:
2168 		vm_inject_gp(vmx->vm, vcpuid);
2169 		return (HANDLED);
2170 	case VMR_UNHANLDED:
2171 		vmexit->exitcode = is_wrmsr ?
2172 		    VM_EXITCODE_WRMSR : VM_EXITCODE_RDMSR;
2173 		vmexit->u.msr.code = ecx;
2174 		vmexit->u.msr.wval = val;
2175 		return (UNHANDLED);
2176 	default:
2177 		panic("unexpected msr result %u\n", res);
2178 	}
2179 }
2180 
2181 static int
vmx_exit_process(struct vmx * vmx,int vcpu,struct vm_exit * vmexit)2182 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2183 {
2184 	int error, errcode, errcode_valid, handled;
2185 	struct vmxctx *vmxctx;
2186 	struct vie *vie;
2187 	struct vlapic *vlapic;
2188 	struct vm_task_switch *ts;
2189 	uint32_t idtvec_info, intr_info;
2190 	uint32_t intr_type, intr_vec, reason;
2191 	uint64_t qual, gpa;
2192 
2193 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2194 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2195 
2196 	handled = UNHANDLED;
2197 	vmxctx = &vmx->ctx[vcpu];
2198 
2199 	qual = vmexit->u.vmx.exit_qualification;
2200 	reason = vmexit->u.vmx.exit_reason;
2201 	vmexit->exitcode = VM_EXITCODE_BOGUS;
2202 
2203 	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2204 	SDT_PROBE3(vmm, vmx, exit, entry, vmx, vcpu, vmexit);
2205 
2206 	/*
2207 	 * VM-entry failures during or after loading guest state.
2208 	 *
2209 	 * These VM-exits are uncommon but must be handled specially
2210 	 * as most VM-exit fields are not populated as usual.
2211 	 */
2212 	if (reason == EXIT_REASON_MCE_DURING_ENTRY) {
2213 		vmm_call_trap(T_MCE);
2214 		return (1);
2215 	}
2216 
2217 	/*
2218 	 * VM exits that can be triggered during event delivery need to
2219 	 * be handled specially by re-injecting the event if the IDT
2220 	 * vectoring information field's valid bit is set.
2221 	 *
2222 	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2223 	 * for details.
2224 	 */
2225 	idtvec_info = vmcs_read(VMCS_IDT_VECTORING_INFO);
2226 	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2227 		uint32_t errcode = 0;
2228 		if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2229 			errcode = vmcs_read(VMCS_IDT_VECTORING_ERROR);
2230 		}
2231 
2232 		/* Record exit intinfo */
2233 		VERIFY0(vm_exit_intinfo(vmx->vm, vcpu,
2234 		    vmx_idtvec_to_intinfo(idtvec_info, errcode)));
2235 
2236 		/*
2237 		 * If 'virtual NMIs' are being used and the VM-exit
2238 		 * happened while injecting an NMI during the previous
2239 		 * VM-entry, then clear "blocking by NMI" in the
2240 		 * Guest Interruptibility-State so the NMI can be
2241 		 * reinjected on the subsequent VM-entry.
2242 		 *
2243 		 * However, if the NMI was being delivered through a task
2244 		 * gate, then the new task must start execution with NMIs
2245 		 * blocked so don't clear NMI blocking in this case.
2246 		 */
2247 		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2248 		if (intr_type == VMCS_INTR_T_NMI) {
2249 			if (reason != EXIT_REASON_TASK_SWITCH)
2250 				vmx_clear_nmi_blocking(vmx, vcpu);
2251 			else
2252 				vmx_assert_nmi_blocking(vmx, vcpu);
2253 		}
2254 
2255 		/*
2256 		 * Update VM-entry instruction length if the event being
2257 		 * delivered was a software interrupt or software exception.
2258 		 */
2259 		if (intr_type == VMCS_INTR_T_SWINTR ||
2260 		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2261 		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2262 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2263 		}
2264 	}
2265 
2266 	switch (reason) {
2267 	case EXIT_REASON_TRIPLE_FAULT:
2268 		(void) vm_suspend(vmx->vm, VM_SUSPEND_TRIPLEFAULT, vcpu);
2269 		handled = HANDLED;
2270 		break;
2271 	case EXIT_REASON_TASK_SWITCH:
2272 		ts = &vmexit->u.task_switch;
2273 		ts->tsssel = qual & 0xffff;
2274 		ts->reason = vmx_task_switch_reason(qual);
2275 		ts->ext = 0;
2276 		ts->errcode_valid = 0;
2277 		vmx_paging_info(&ts->paging);
2278 		/*
2279 		 * If the task switch was due to a CALL, JMP, IRET, software
2280 		 * interrupt (INT n) or software exception (INT3, INTO),
2281 		 * then the saved %rip references the instruction that caused
2282 		 * the task switch. The instruction length field in the VMCS
2283 		 * is valid in this case.
2284 		 *
2285 		 * In all other cases (e.g., NMI, hardware exception) the
2286 		 * saved %rip is one that would have been saved in the old TSS
2287 		 * had the task switch completed normally so the instruction
2288 		 * length field is not needed in this case and is explicitly
2289 		 * set to 0.
2290 		 */
2291 		if (ts->reason == TSR_IDT_GATE) {
2292 			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2293 			    ("invalid idtvec_info %x for IDT task switch",
2294 			    idtvec_info));
2295 			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2296 			if (intr_type != VMCS_INTR_T_SWINTR &&
2297 			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2298 			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2299 				/* Task switch triggered by external event */
2300 				ts->ext = 1;
2301 				vmexit->inst_length = 0;
2302 				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2303 					ts->errcode_valid = 1;
2304 					ts->errcode =
2305 					    vmcs_read(VMCS_IDT_VECTORING_ERROR);
2306 				}
2307 			}
2308 		}
2309 		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2310 		SDT_PROBE4(vmm, vmx, exit, taskswitch, vmx, vcpu, vmexit, ts);
2311 		break;
2312 	case EXIT_REASON_CR_ACCESS:
2313 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2314 		SDT_PROBE4(vmm, vmx, exit, craccess, vmx, vcpu, vmexit, qual);
2315 		switch (qual & 0xf) {
2316 		case 0:
2317 			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2318 			break;
2319 		case 4:
2320 			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2321 			break;
2322 		case 8:
2323 			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2324 			break;
2325 		}
2326 		break;
2327 	case EXIT_REASON_RDMSR:
2328 	case EXIT_REASON_WRMSR:
2329 		handled = vmx_handle_msr(vmx, vcpu, vmexit,
2330 		    reason == EXIT_REASON_WRMSR);
2331 		break;
2332 	case EXIT_REASON_HLT:
2333 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2334 		SDT_PROBE3(vmm, vmx, exit, halt, vmx, vcpu, vmexit);
2335 		vmexit->exitcode = VM_EXITCODE_HLT;
2336 		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2337 		break;
2338 	case EXIT_REASON_MTF:
2339 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2340 		SDT_PROBE3(vmm, vmx, exit, mtrap, vmx, vcpu, vmexit);
2341 		vmexit->exitcode = VM_EXITCODE_MTRAP;
2342 		vmexit->inst_length = 0;
2343 		break;
2344 	case EXIT_REASON_PAUSE:
2345 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2346 		SDT_PROBE3(vmm, vmx, exit, pause, vmx, vcpu, vmexit);
2347 		vmexit->exitcode = VM_EXITCODE_PAUSE;
2348 		break;
2349 	case EXIT_REASON_INTR_WINDOW:
2350 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2351 		SDT_PROBE3(vmm, vmx, exit, intrwindow, vmx, vcpu, vmexit);
2352 		ASSERT(vmx_int_window_exiting(vmx, vcpu));
2353 		vmx_clear_int_window_exiting(vmx, vcpu);
2354 		return (1);
2355 	case EXIT_REASON_EXT_INTR:
2356 		/*
2357 		 * External interrupts serve only to cause VM exits and allow
2358 		 * the host interrupt handler to run.
2359 		 *
2360 		 * If this external interrupt triggers a virtual interrupt
2361 		 * to a VM, then that state will be recorded by the
2362 		 * host interrupt handler in the VM's softc. We will inject
2363 		 * this virtual interrupt during the subsequent VM enter.
2364 		 */
2365 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2366 		SDT_PROBE4(vmm, vmx, exit, interrupt,
2367 		    vmx, vcpu, vmexit, intr_info);
2368 
2369 		/*
2370 		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2371 		 * This appears to be a bug in VMware Fusion?
2372 		 */
2373 		if (!(intr_info & VMCS_INTR_VALID))
2374 			return (1);
2375 		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2376 		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2377 		    ("VM exit interruption info invalid: %x", intr_info));
2378 		vmx_trigger_hostintr(intr_info & 0xff);
2379 
2380 		/*
2381 		 * This is special. We want to treat this as an 'handled'
2382 		 * VM-exit but not increment the instruction pointer.
2383 		 */
2384 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2385 		return (1);
2386 	case EXIT_REASON_NMI_WINDOW:
2387 		SDT_PROBE3(vmm, vmx, exit, nmiwindow, vmx, vcpu, vmexit);
2388 		/* Exit to allow the pending virtual NMI to be injected */
2389 		if (vm_nmi_pending(vmx->vm, vcpu))
2390 			vmx_inject_nmi(vmx, vcpu);
2391 		ASSERT(vmx_nmi_window_exiting(vmx, vcpu));
2392 		vmx_clear_nmi_window_exiting(vmx, vcpu);
2393 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2394 		return (1);
2395 	case EXIT_REASON_INOUT:
2396 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2397 		vie = vm_vie_ctx(vmx->vm, vcpu);
2398 		vmexit_inout(vmexit, vie, qual, (uint32_t)vmxctx->guest_rax);
2399 		SDT_PROBE3(vmm, vmx, exit, inout, vmx, vcpu, vmexit);
2400 		break;
2401 	case EXIT_REASON_CPUID:
2402 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2403 		SDT_PROBE3(vmm, vmx, exit, cpuid, vmx, vcpu, vmexit);
2404 		vcpu_emulate_cpuid(vmx->vm, vcpu,
2405 		    (uint64_t *)&vmxctx->guest_rax,
2406 		    (uint64_t *)&vmxctx->guest_rbx,
2407 		    (uint64_t *)&vmxctx->guest_rcx,
2408 		    (uint64_t *)&vmxctx->guest_rdx);
2409 		handled = HANDLED;
2410 		break;
2411 	case EXIT_REASON_EXCEPTION:
2412 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2413 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2414 		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2415 		    ("VM exit interruption info invalid: %x", intr_info));
2416 
2417 		intr_vec = intr_info & 0xff;
2418 		intr_type = intr_info & VMCS_INTR_T_MASK;
2419 
2420 		/*
2421 		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2422 		 * fault encountered during the execution of IRET then we must
2423 		 * restore the state of "virtual-NMI blocking" before resuming
2424 		 * the guest.
2425 		 *
2426 		 * See "Resuming Guest Software after Handling an Exception".
2427 		 * See "Information for VM Exits Due to Vectored Events".
2428 		 */
2429 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2430 		    (intr_vec != IDT_DF) &&
2431 		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2432 			vmx_restore_nmi_blocking(vmx, vcpu);
2433 
2434 		/*
2435 		 * The NMI has already been handled in vmx_exit_handle_nmi().
2436 		 */
2437 		if (intr_type == VMCS_INTR_T_NMI)
2438 			return (1);
2439 
2440 		/*
2441 		 * Call the machine check handler by hand. Also don't reflect
2442 		 * the machine check back into the guest.
2443 		 */
2444 		if (intr_vec == IDT_MC) {
2445 			vmm_call_trap(T_MCE);
2446 			return (1);
2447 		}
2448 
2449 		/*
2450 		 * If the hypervisor has requested user exits for
2451 		 * debug exceptions, bounce them out to userland.
2452 		 */
2453 		if (intr_type == VMCS_INTR_T_SWEXCEPTION &&
2454 		    intr_vec == IDT_BP &&
2455 		    (vmx->cap[vcpu].set & (1 << VM_CAP_BPT_EXIT))) {
2456 			vmexit->exitcode = VM_EXITCODE_BPT;
2457 			vmexit->u.bpt.inst_length = vmexit->inst_length;
2458 			vmexit->inst_length = 0;
2459 			break;
2460 		}
2461 
2462 		if (intr_vec == IDT_PF) {
2463 			vmxctx->guest_cr2 = qual;
2464 		}
2465 
2466 		/*
2467 		 * Software exceptions exhibit trap-like behavior. This in
2468 		 * turn requires populating the VM-entry instruction length
2469 		 * so that the %rip in the trap frame is past the INT3/INTO
2470 		 * instruction.
2471 		 */
2472 		if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2473 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2474 
2475 		/* Reflect all other exceptions back into the guest */
2476 		errcode_valid = errcode = 0;
2477 		if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2478 			errcode_valid = 1;
2479 			errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2480 		}
2481 		SDT_PROBE5(vmm, vmx, exit, exception,
2482 		    vmx, vcpu, vmexit, intr_vec, errcode);
2483 		error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2484 		    errcode_valid, errcode, 0);
2485 		KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2486 		    __func__, error));
2487 		return (1);
2488 
2489 	case EXIT_REASON_EPT_FAULT:
2490 		/*
2491 		 * If 'gpa' lies within the address space allocated to
2492 		 * memory then this must be a nested page fault otherwise
2493 		 * this must be an instruction that accesses MMIO space.
2494 		 */
2495 		gpa = vmcs_read(VMCS_GUEST_PHYSICAL_ADDRESS);
2496 		if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2497 		    apic_access_fault(vmx, vcpu, gpa)) {
2498 			vmexit->exitcode = VM_EXITCODE_PAGING;
2499 			vmexit->inst_length = 0;
2500 			vmexit->u.paging.gpa = gpa;
2501 			vmexit->u.paging.fault_type = ept_fault_type(qual);
2502 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2503 			SDT_PROBE5(vmm, vmx, exit, nestedfault,
2504 			    vmx, vcpu, vmexit, gpa, qual);
2505 		} else if (ept_emulation_fault(qual)) {
2506 			vie = vm_vie_ctx(vmx->vm, vcpu);
2507 			vmexit_mmio_emul(vmexit, vie, gpa,
2508 			    vmcs_read(VMCS_GUEST_LINEAR_ADDRESS));
2509 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MMIO_EMUL, 1);
2510 			SDT_PROBE4(vmm, vmx, exit, mmiofault,
2511 			    vmx, vcpu, vmexit, gpa);
2512 		}
2513 		/*
2514 		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2515 		 * EPT fault during the execution of IRET then we must restore
2516 		 * the state of "virtual-NMI blocking" before resuming.
2517 		 *
2518 		 * See description of "NMI unblocking due to IRET" in
2519 		 * "Exit Qualification for EPT Violations".
2520 		 */
2521 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2522 		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2523 			vmx_restore_nmi_blocking(vmx, vcpu);
2524 		break;
2525 	case EXIT_REASON_VIRTUALIZED_EOI:
2526 		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2527 		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2528 		SDT_PROBE3(vmm, vmx, exit, eoi, vmx, vcpu, vmexit);
2529 		vmexit->inst_length = 0;	/* trap-like */
2530 		break;
2531 	case EXIT_REASON_APIC_ACCESS:
2532 		SDT_PROBE3(vmm, vmx, exit, apicaccess, vmx, vcpu, vmexit);
2533 		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2534 		break;
2535 	case EXIT_REASON_APIC_WRITE:
2536 		/*
2537 		 * APIC-write VM exit is trap-like so the %rip is already
2538 		 * pointing to the next instruction.
2539 		 */
2540 		vmexit->inst_length = 0;
2541 		vlapic = vm_lapic(vmx->vm, vcpu);
2542 		SDT_PROBE4(vmm, vmx, exit, apicwrite,
2543 		    vmx, vcpu, vmexit, vlapic);
2544 		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2545 		break;
2546 	case EXIT_REASON_XSETBV:
2547 		SDT_PROBE3(vmm, vmx, exit, xsetbv, vmx, vcpu, vmexit);
2548 		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2549 		break;
2550 	case EXIT_REASON_MONITOR:
2551 		SDT_PROBE3(vmm, vmx, exit, monitor, vmx, vcpu, vmexit);
2552 		vmexit->exitcode = VM_EXITCODE_MONITOR;
2553 		break;
2554 	case EXIT_REASON_MWAIT:
2555 		SDT_PROBE3(vmm, vmx, exit, mwait, vmx, vcpu, vmexit);
2556 		vmexit->exitcode = VM_EXITCODE_MWAIT;
2557 		break;
2558 	case EXIT_REASON_TPR:
2559 		vlapic = vm_lapic(vmx->vm, vcpu);
2560 		vlapic_sync_tpr(vlapic);
2561 		vmexit->inst_length = 0;
2562 		handled = HANDLED;
2563 		break;
2564 	case EXIT_REASON_VMCALL:
2565 	case EXIT_REASON_VMCLEAR:
2566 	case EXIT_REASON_VMLAUNCH:
2567 	case EXIT_REASON_VMPTRLD:
2568 	case EXIT_REASON_VMPTRST:
2569 	case EXIT_REASON_VMREAD:
2570 	case EXIT_REASON_VMRESUME:
2571 	case EXIT_REASON_VMWRITE:
2572 	case EXIT_REASON_VMXOFF:
2573 	case EXIT_REASON_VMXON:
2574 		SDT_PROBE3(vmm, vmx, exit, vminsn, vmx, vcpu, vmexit);
2575 		vmexit->exitcode = VM_EXITCODE_VMINSN;
2576 		break;
2577 	case EXIT_REASON_INVD:
2578 	case EXIT_REASON_WBINVD:
2579 		/* ignore exit */
2580 		handled = HANDLED;
2581 		break;
2582 	default:
2583 		SDT_PROBE4(vmm, vmx, exit, unknown,
2584 		    vmx, vcpu, vmexit, reason);
2585 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2586 		break;
2587 	}
2588 
2589 	if (handled) {
2590 		/*
2591 		 * It is possible that control is returned to userland
2592 		 * even though we were able to handle the VM exit in the
2593 		 * kernel.
2594 		 *
2595 		 * In such a case we want to make sure that the userland
2596 		 * restarts guest execution at the instruction *after*
2597 		 * the one we just processed. Therefore we update the
2598 		 * guest rip in the VMCS and in 'vmexit'.
2599 		 */
2600 		vmexit->rip += vmexit->inst_length;
2601 		vmexit->inst_length = 0;
2602 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2603 	} else {
2604 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2605 			/*
2606 			 * If this VM exit was not claimed by anybody then
2607 			 * treat it as a generic VMX exit.
2608 			 */
2609 			vmexit->exitcode = VM_EXITCODE_VMX;
2610 			vmexit->u.vmx.status = VM_SUCCESS;
2611 			vmexit->u.vmx.inst_type = 0;
2612 			vmexit->u.vmx.inst_error = 0;
2613 		} else {
2614 			/*
2615 			 * The exitcode and collateral have been populated.
2616 			 * The VM exit will be processed further in userland.
2617 			 */
2618 		}
2619 	}
2620 
2621 	SDT_PROBE4(vmm, vmx, exit, return,
2622 	    vmx, vcpu, vmexit, handled);
2623 	return (handled);
2624 }
2625 
2626 static void
vmx_exit_inst_error(struct vmxctx * vmxctx,int rc,struct vm_exit * vmexit)2627 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2628 {
2629 
2630 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2631 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2632 	    vmxctx->inst_fail_status));
2633 
2634 	vmexit->inst_length = 0;
2635 	vmexit->exitcode = VM_EXITCODE_VMX;
2636 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2637 	vmexit->u.vmx.inst_error = vmcs_read(VMCS_INSTRUCTION_ERROR);
2638 	vmexit->u.vmx.exit_reason = ~0;
2639 	vmexit->u.vmx.exit_qualification = ~0;
2640 
2641 	switch (rc) {
2642 	case VMX_VMRESUME_ERROR:
2643 	case VMX_VMLAUNCH_ERROR:
2644 	case VMX_INVEPT_ERROR:
2645 	case VMX_VMWRITE_ERROR:
2646 		vmexit->u.vmx.inst_type = rc;
2647 		break;
2648 	default:
2649 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2650 	}
2651 }
2652 
2653 /*
2654  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2655  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2656  * sufficient to simply vector to the NMI handler via a software interrupt.
2657  * However, this must be done before maskable interrupts are enabled
2658  * otherwise the "iret" issued by an interrupt handler will incorrectly
2659  * clear NMI blocking.
2660  */
2661 static __inline void
vmx_exit_handle_possible_nmi(struct vm_exit * vmexit)2662 vmx_exit_handle_possible_nmi(struct vm_exit *vmexit)
2663 {
2664 	ASSERT(!interrupts_enabled());
2665 
2666 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EXCEPTION) {
2667 		uint32_t intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2668 		ASSERT(intr_info & VMCS_INTR_VALID);
2669 
2670 		if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2671 			ASSERT3U(intr_info & 0xff, ==, IDT_NMI);
2672 			vmm_call_trap(T_NMIFLT);
2673 		}
2674 	}
2675 }
2676 
2677 static __inline void
vmx_dr_enter_guest(struct vmxctx * vmxctx)2678 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2679 {
2680 	uint64_t rflags;
2681 
2682 	/* Save host control debug registers. */
2683 	vmxctx->host_dr7 = rdr7();
2684 	vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2685 
2686 	/*
2687 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2688 	 * exceptions in the host based on the guest DRx values.  The
2689 	 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2690 	 */
2691 	load_dr7(0);
2692 	wrmsr(MSR_DEBUGCTLMSR, 0);
2693 
2694 	/*
2695 	 * Disable single stepping the kernel to avoid corrupting the
2696 	 * guest DR6.  A debugger might still be able to corrupt the
2697 	 * guest DR6 by setting a breakpoint after this point and then
2698 	 * single stepping.
2699 	 */
2700 	rflags = read_rflags();
2701 	vmxctx->host_tf = rflags & PSL_T;
2702 	write_rflags(rflags & ~PSL_T);
2703 
2704 	/* Save host debug registers. */
2705 	vmxctx->host_dr0 = rdr0();
2706 	vmxctx->host_dr1 = rdr1();
2707 	vmxctx->host_dr2 = rdr2();
2708 	vmxctx->host_dr3 = rdr3();
2709 	vmxctx->host_dr6 = rdr6();
2710 
2711 	/* Restore guest debug registers. */
2712 	load_dr0(vmxctx->guest_dr0);
2713 	load_dr1(vmxctx->guest_dr1);
2714 	load_dr2(vmxctx->guest_dr2);
2715 	load_dr3(vmxctx->guest_dr3);
2716 	load_dr6(vmxctx->guest_dr6);
2717 }
2718 
2719 static __inline void
vmx_dr_leave_guest(struct vmxctx * vmxctx)2720 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2721 {
2722 
2723 	/* Save guest debug registers. */
2724 	vmxctx->guest_dr0 = rdr0();
2725 	vmxctx->guest_dr1 = rdr1();
2726 	vmxctx->guest_dr2 = rdr2();
2727 	vmxctx->guest_dr3 = rdr3();
2728 	vmxctx->guest_dr6 = rdr6();
2729 
2730 	/*
2731 	 * Restore host debug registers.  Restore DR7, DEBUGCTL, and
2732 	 * PSL_T last.
2733 	 */
2734 	load_dr0(vmxctx->host_dr0);
2735 	load_dr1(vmxctx->host_dr1);
2736 	load_dr2(vmxctx->host_dr2);
2737 	load_dr3(vmxctx->host_dr3);
2738 	load_dr6(vmxctx->host_dr6);
2739 	wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2740 	load_dr7(vmxctx->host_dr7);
2741 	write_rflags(read_rflags() | vmxctx->host_tf);
2742 }
2743 
2744 static int
vmx_run(void * arg,int vcpu,uint64_t rip)2745 vmx_run(void *arg, int vcpu, uint64_t rip)
2746 {
2747 	int rc, handled, launched;
2748 	struct vmx *vmx;
2749 	struct vm *vm;
2750 	struct vmxctx *vmxctx;
2751 	uintptr_t vmcs_pa;
2752 	struct vm_exit *vmexit;
2753 	struct vlapic *vlapic;
2754 	uint32_t exit_reason;
2755 	bool tpr_shadow_active;
2756 	vm_client_t *vmc;
2757 
2758 	vmx = arg;
2759 	vm = vmx->vm;
2760 	vmcs_pa = vmx->vmcs_pa[vcpu];
2761 	vmxctx = &vmx->ctx[vcpu];
2762 	vlapic = vm_lapic(vm, vcpu);
2763 	vmexit = vm_exitinfo(vm, vcpu);
2764 	vmc = vm_get_vmclient(vm, vcpu);
2765 	launched = 0;
2766 	tpr_shadow_active = vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW) &&
2767 	    !vmx_cap_en(vmx, VMX_CAP_APICV) &&
2768 	    (vmx->cap[vcpu].proc_ctls & PROCBASED_USE_TPR_SHADOW) != 0;
2769 
2770 	vmx_msr_guest_enter(vmx, vcpu);
2771 
2772 	vmcs_load(vmcs_pa);
2773 
2774 	VERIFY(vmx->vmcs_state[vcpu] == VS_NONE && curthread->t_preempt != 0);
2775 	vmx->vmcs_state[vcpu] = VS_LOADED;
2776 
2777 	/*
2778 	 * XXX
2779 	 * We do this every time because we may setup the virtual machine
2780 	 * from a different process than the one that actually runs it.
2781 	 *
2782 	 * If the life of a virtual machine was spent entirely in the context
2783 	 * of a single process we could do this once in vmx_vminit().
2784 	 */
2785 	vmcs_write(VMCS_HOST_CR3, rcr3());
2786 
2787 	vmcs_write(VMCS_GUEST_RIP, rip);
2788 	vmx_set_pcpu_defaults(vmx, vcpu);
2789 	do {
2790 		enum event_inject_state inject_state;
2791 		uint64_t eptgen;
2792 
2793 		ASSERT3U(vmcs_read(VMCS_GUEST_RIP), ==, rip);
2794 
2795 		handled = UNHANDLED;
2796 
2797 		/*
2798 		 * Perform initial event/exception/interrupt injection before
2799 		 * host CPU interrupts are disabled.
2800 		 */
2801 		inject_state = vmx_inject_events(vmx, vcpu, rip);
2802 
2803 		/*
2804 		 * Interrupts are disabled from this point on until the
2805 		 * guest starts executing. This is done for the following
2806 		 * reasons:
2807 		 *
2808 		 * If an AST is asserted on this thread after the check below,
2809 		 * then the IPI_AST notification will not be lost, because it
2810 		 * will cause a VM exit due to external interrupt as soon as
2811 		 * the guest state is loaded.
2812 		 *
2813 		 * A posted interrupt after vmx_inject_vlapic() will not be
2814 		 * "lost" because it will be held pending in the host APIC
2815 		 * because interrupts are disabled. The pending interrupt will
2816 		 * be recognized as soon as the guest state is loaded.
2817 		 *
2818 		 * The same reasoning applies to the IPI generated by vmspace
2819 		 * invalidation.
2820 		 */
2821 		disable_intr();
2822 
2823 		/*
2824 		 * If not precluded by existing events, inject any interrupt
2825 		 * pending on the vLAPIC.  As a lock-less operation, it is safe
2826 		 * (and prudent) to perform with host CPU interrupts disabled.
2827 		 */
2828 		if (inject_state == EIS_CAN_INJECT) {
2829 			inject_state = vmx_inject_vlapic(vmx, vcpu, vlapic);
2830 		}
2831 
2832 		/*
2833 		 * Check for vCPU bail-out conditions.  This must be done after
2834 		 * vmx_inject_events() to detect a triple-fault condition.
2835 		 */
2836 		if (vcpu_entry_bailout_checks(vmx->vm, vcpu, rip)) {
2837 			enable_intr();
2838 			break;
2839 		}
2840 
2841 		if (vcpu_run_state_pending(vm, vcpu)) {
2842 			enable_intr();
2843 			vm_exit_run_state(vmx->vm, vcpu, rip);
2844 			break;
2845 		}
2846 
2847 		/*
2848 		 * If subsequent activity queued events which require injection
2849 		 * handling, take another lap to handle them.
2850 		 */
2851 		if (vmx_inject_recheck(vmx, vcpu, inject_state)) {
2852 			enable_intr();
2853 			handled = HANDLED;
2854 			continue;
2855 		}
2856 
2857 		if ((rc = smt_acquire()) != 1) {
2858 			enable_intr();
2859 			vmexit->rip = rip;
2860 			vmexit->inst_length = 0;
2861 			if (rc == -1) {
2862 				vmexit->exitcode = VM_EXITCODE_HT;
2863 			} else {
2864 				vmexit->exitcode = VM_EXITCODE_BOGUS;
2865 				handled = HANDLED;
2866 			}
2867 			break;
2868 		}
2869 
2870 		/*
2871 		 * If this thread has gone off-cpu due to mutex operations
2872 		 * during vmx_run, the VMCS will have been unloaded, forcing a
2873 		 * re-VMLAUNCH as opposed to VMRESUME.
2874 		 */
2875 		launched = (vmx->vmcs_state[vcpu] & VS_LAUNCHED) != 0;
2876 		/*
2877 		 * Restoration of the GDT limit is taken care of by
2878 		 * vmx_savectx().  Since the maximum practical index for the
2879 		 * IDT is 255, restoring its limits from the post-VMX-exit
2880 		 * default of 0xffff is not a concern.
2881 		 *
2882 		 * Only 64-bit hypervisor callers are allowed, which forgoes
2883 		 * the need to restore any LDT descriptor.  Toss an error to
2884 		 * anyone attempting to break that rule.
2885 		 */
2886 		if (curproc->p_model != DATAMODEL_LP64) {
2887 			smt_release();
2888 			enable_intr();
2889 			bzero(vmexit, sizeof (*vmexit));
2890 			vmexit->rip = rip;
2891 			vmexit->exitcode = VM_EXITCODE_VMX;
2892 			vmexit->u.vmx.status = VM_FAIL_INVALID;
2893 			handled = UNHANDLED;
2894 			break;
2895 		}
2896 
2897 		if (tpr_shadow_active) {
2898 			vmx_tpr_shadow_enter(vlapic);
2899 		}
2900 
2901 		/*
2902 		 * Indicate activation of vmspace (EPT) table just prior to VMX
2903 		 * entry, checking for the necessity of an invept invalidation.
2904 		 */
2905 		eptgen = vmc_table_enter(vmc);
2906 		if (vmx->eptgen[curcpu] != eptgen) {
2907 			/*
2908 			 * VMspace generation does not match what was previously
2909 			 * used on this host CPU, so all mappings associated
2910 			 * with this EP4TA must be invalidated.
2911 			 */
2912 			invept(1, vmx->eptp);
2913 			vmx->eptgen[curcpu] = eptgen;
2914 		}
2915 
2916 		vcpu_ustate_change(vm, vcpu, VU_RUN);
2917 		vmx_dr_enter_guest(vmxctx);
2918 
2919 		/* Perform VMX entry */
2920 		rc = vmx_enter_guest(vmxctx, vmx, launched);
2921 
2922 		vmx_dr_leave_guest(vmxctx);
2923 		vcpu_ustate_change(vm, vcpu, VU_EMU_KERN);
2924 
2925 		vmx->vmcs_state[vcpu] |= VS_LAUNCHED;
2926 		smt_release();
2927 
2928 		if (tpr_shadow_active) {
2929 			vmx_tpr_shadow_exit(vlapic);
2930 		}
2931 
2932 		/* Collect some information for VM exit processing */
2933 		vmexit->rip = rip = vmcs_read(VMCS_GUEST_RIP);
2934 		vmexit->inst_length = vmcs_read(VMCS_EXIT_INSTRUCTION_LENGTH);
2935 		vmexit->u.vmx.exit_reason = exit_reason =
2936 		    (vmcs_read(VMCS_EXIT_REASON) & BASIC_EXIT_REASON_MASK);
2937 		vmexit->u.vmx.exit_qualification =
2938 		    vmcs_read(VMCS_EXIT_QUALIFICATION);
2939 		/* Update 'nextrip' */
2940 		vmx->state[vcpu].nextrip = rip;
2941 
2942 		if (rc == VMX_GUEST_VMEXIT) {
2943 			vmx_exit_handle_possible_nmi(vmexit);
2944 		}
2945 		enable_intr();
2946 		vmc_table_exit(vmc);
2947 
2948 		if (rc == VMX_GUEST_VMEXIT) {
2949 			handled = vmx_exit_process(vmx, vcpu, vmexit);
2950 		} else {
2951 			vmx_exit_inst_error(vmxctx, rc, vmexit);
2952 		}
2953 		DTRACE_PROBE3(vmm__vexit, int, vcpu, uint64_t, rip,
2954 		    uint32_t, exit_reason);
2955 		rip = vmexit->rip;
2956 	} while (handled);
2957 
2958 	/* If a VM exit has been handled then the exitcode must be BOGUS */
2959 	if (handled && vmexit->exitcode != VM_EXITCODE_BOGUS) {
2960 		panic("Non-BOGUS exitcode (%d) unexpected for handled VM exit",
2961 		    vmexit->exitcode);
2962 	}
2963 
2964 	vmcs_clear(vmcs_pa);
2965 	vmx_msr_guest_exit(vmx, vcpu);
2966 
2967 	VERIFY(vmx->vmcs_state[vcpu] != VS_NONE && curthread->t_preempt != 0);
2968 	vmx->vmcs_state[vcpu] = VS_NONE;
2969 
2970 	return (0);
2971 }
2972 
2973 static void
vmx_vmcleanup(void * arg)2974 vmx_vmcleanup(void *arg)
2975 {
2976 	int i;
2977 	struct vmx *vmx = arg;
2978 	uint16_t maxcpus;
2979 
2980 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
2981 		(void) vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2982 		kmem_free(vmx->apic_access_page, PAGESIZE);
2983 	} else {
2984 		VERIFY3P(vmx->apic_access_page, ==, NULL);
2985 	}
2986 
2987 	vmx_msr_bitmap_destroy(vmx);
2988 
2989 	maxcpus = vm_get_maxcpus(vmx->vm);
2990 	for (i = 0; i < maxcpus; i++)
2991 		vpid_free(vmx->state[i].vpid);
2992 
2993 	kmem_free(vmx, sizeof (*vmx));
2994 }
2995 
2996 /*
2997  * Ensure that the VMCS for this vcpu is loaded.
2998  * Returns true if a VMCS load was required.
2999  */
3000 static bool
vmx_vmcs_access_ensure(struct vmx * vmx,int vcpu)3001 vmx_vmcs_access_ensure(struct vmx *vmx, int vcpu)
3002 {
3003 	int hostcpu;
3004 
3005 	if (vcpu_is_running(vmx->vm, vcpu, &hostcpu)) {
3006 		if (hostcpu != curcpu) {
3007 			panic("unexpected vcpu migration %d != %d",
3008 			    hostcpu, curcpu);
3009 		}
3010 		/* Earlier logic already took care of the load */
3011 		return (false);
3012 	} else {
3013 		vmcs_load(vmx->vmcs_pa[vcpu]);
3014 		return (true);
3015 	}
3016 }
3017 
3018 static void
vmx_vmcs_access_done(struct vmx * vmx,int vcpu)3019 vmx_vmcs_access_done(struct vmx *vmx, int vcpu)
3020 {
3021 	int hostcpu;
3022 
3023 	if (vcpu_is_running(vmx->vm, vcpu, &hostcpu)) {
3024 		if (hostcpu != curcpu) {
3025 			panic("unexpected vcpu migration %d != %d",
3026 			    hostcpu, curcpu);
3027 		}
3028 		/* Later logic will take care of the unload */
3029 	} else {
3030 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3031 	}
3032 }
3033 
3034 static uint64_t *
vmxctx_regptr(struct vmxctx * vmxctx,int reg)3035 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
3036 {
3037 	switch (reg) {
3038 	case VM_REG_GUEST_RAX:
3039 		return (&vmxctx->guest_rax);
3040 	case VM_REG_GUEST_RBX:
3041 		return (&vmxctx->guest_rbx);
3042 	case VM_REG_GUEST_RCX:
3043 		return (&vmxctx->guest_rcx);
3044 	case VM_REG_GUEST_RDX:
3045 		return (&vmxctx->guest_rdx);
3046 	case VM_REG_GUEST_RSI:
3047 		return (&vmxctx->guest_rsi);
3048 	case VM_REG_GUEST_RDI:
3049 		return (&vmxctx->guest_rdi);
3050 	case VM_REG_GUEST_RBP:
3051 		return (&vmxctx->guest_rbp);
3052 	case VM_REG_GUEST_R8:
3053 		return (&vmxctx->guest_r8);
3054 	case VM_REG_GUEST_R9:
3055 		return (&vmxctx->guest_r9);
3056 	case VM_REG_GUEST_R10:
3057 		return (&vmxctx->guest_r10);
3058 	case VM_REG_GUEST_R11:
3059 		return (&vmxctx->guest_r11);
3060 	case VM_REG_GUEST_R12:
3061 		return (&vmxctx->guest_r12);
3062 	case VM_REG_GUEST_R13:
3063 		return (&vmxctx->guest_r13);
3064 	case VM_REG_GUEST_R14:
3065 		return (&vmxctx->guest_r14);
3066 	case VM_REG_GUEST_R15:
3067 		return (&vmxctx->guest_r15);
3068 	case VM_REG_GUEST_CR2:
3069 		return (&vmxctx->guest_cr2);
3070 	case VM_REG_GUEST_DR0:
3071 		return (&vmxctx->guest_dr0);
3072 	case VM_REG_GUEST_DR1:
3073 		return (&vmxctx->guest_dr1);
3074 	case VM_REG_GUEST_DR2:
3075 		return (&vmxctx->guest_dr2);
3076 	case VM_REG_GUEST_DR3:
3077 		return (&vmxctx->guest_dr3);
3078 	case VM_REG_GUEST_DR6:
3079 		return (&vmxctx->guest_dr6);
3080 	default:
3081 		break;
3082 	}
3083 	return (NULL);
3084 }
3085 
3086 static int
vmx_getreg(void * arg,int vcpu,int reg,uint64_t * retval)3087 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
3088 {
3089 	struct vmx *vmx = arg;
3090 	uint64_t *regp;
3091 
3092 	/* VMCS access not required for ctx reads */
3093 	if ((regp = vmxctx_regptr(&vmx->ctx[vcpu], reg)) != NULL) {
3094 		*retval = *regp;
3095 		return (0);
3096 	}
3097 
3098 	bool vmcs_loaded = vmx_vmcs_access_ensure(vmx, vcpu);
3099 	int err = 0;
3100 
3101 	if (reg == VM_REG_GUEST_INTR_SHADOW) {
3102 		uint64_t gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
3103 		*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
3104 	} else {
3105 		uint32_t encoding;
3106 
3107 		encoding = vmcs_field_encoding(reg);
3108 		switch (encoding) {
3109 		case VMCS_GUEST_CR0:
3110 			/* Take the shadow bits into account */
3111 			*retval = vmx_unshadow_cr0(vmcs_read(encoding),
3112 			    vmcs_read(VMCS_CR0_SHADOW));
3113 			break;
3114 		case VMCS_GUEST_CR4:
3115 			/* Take the shadow bits into account */
3116 			*retval = vmx_unshadow_cr4(vmcs_read(encoding),
3117 			    vmcs_read(VMCS_CR4_SHADOW));
3118 			break;
3119 		case VMCS_INVALID_ENCODING:
3120 			err = EINVAL;
3121 			break;
3122 		default:
3123 			*retval = vmcs_read(encoding);
3124 			break;
3125 		}
3126 	}
3127 
3128 	if (vmcs_loaded) {
3129 		vmx_vmcs_access_done(vmx, vcpu);
3130 	}
3131 	return (err);
3132 }
3133 
3134 static int
vmx_setreg(void * arg,int vcpu,int reg,uint64_t val)3135 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
3136 {
3137 	struct vmx *vmx = arg;
3138 	uint64_t *regp;
3139 
3140 	/* VMCS access not required for ctx writes */
3141 	if ((regp = vmxctx_regptr(&vmx->ctx[vcpu], reg)) != NULL) {
3142 		*regp = val;
3143 		return (0);
3144 	}
3145 
3146 	bool vmcs_loaded = vmx_vmcs_access_ensure(vmx, vcpu);
3147 	int err = 0;
3148 
3149 	if (reg == VM_REG_GUEST_INTR_SHADOW) {
3150 		if (val != 0) {
3151 			/*
3152 			 * Forcing the vcpu into an interrupt shadow is not
3153 			 * presently supported.
3154 			 */
3155 			err = EINVAL;
3156 		} else {
3157 			uint64_t gi;
3158 
3159 			gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
3160 			gi &= ~HWINTR_BLOCKING;
3161 			vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
3162 			err = 0;
3163 		}
3164 	} else {
3165 		uint32_t encoding;
3166 
3167 		err = 0;
3168 		encoding = vmcs_field_encoding(reg);
3169 		switch (encoding) {
3170 		case VMCS_GUEST_IA32_EFER:
3171 			vmcs_write(encoding, val);
3172 			vmx_sync_efer_state(vmx, vcpu, val);
3173 			break;
3174 		case VMCS_GUEST_CR0:
3175 			/*
3176 			 * The guest is not allowed to modify certain bits in
3177 			 * %cr0 and %cr4.  To maintain the illusion of full
3178 			 * control, they have shadow versions which contain the
3179 			 * guest-perceived (via reads from the register) values
3180 			 * as opposed to the guest-effective values.
3181 			 *
3182 			 * This is detailed in the SDM: Vol. 3 Ch. 24.6.6.
3183 			 */
3184 			vmcs_write(VMCS_CR0_SHADOW, val);
3185 			vmcs_write(encoding, vmx_fix_cr0(val));
3186 			break;
3187 		case VMCS_GUEST_CR4:
3188 			/* See above for detail on %cr4 shadowing */
3189 			vmcs_write(VMCS_CR4_SHADOW, val);
3190 			vmcs_write(encoding, vmx_fix_cr4(val));
3191 			break;
3192 		case VMCS_GUEST_CR3:
3193 			vmcs_write(encoding, val);
3194 			/*
3195 			 * Invalidate the guest vcpu's TLB mappings to emulate
3196 			 * the behavior of updating %cr3.
3197 			 *
3198 			 * XXX the processor retains global mappings when %cr3
3199 			 * is updated but vmx_invvpid() does not.
3200 			 */
3201 			vmx_invvpid(vmx, vcpu,
3202 			    vcpu_is_running(vmx->vm, vcpu, NULL));
3203 			break;
3204 		case VMCS_INVALID_ENCODING:
3205 			err = EINVAL;
3206 			break;
3207 		default:
3208 			vmcs_write(encoding, val);
3209 			break;
3210 		}
3211 	}
3212 
3213 	if (vmcs_loaded) {
3214 		vmx_vmcs_access_done(vmx, vcpu);
3215 	}
3216 	return (err);
3217 }
3218 
3219 static int
vmx_getdesc(void * arg,int vcpu,int seg,struct seg_desc * desc)3220 vmx_getdesc(void *arg, int vcpu, int seg, struct seg_desc *desc)
3221 {
3222 	struct vmx *vmx = arg;
3223 	uint32_t base, limit, access;
3224 
3225 	bool vmcs_loaded = vmx_vmcs_access_ensure(vmx, vcpu);
3226 
3227 	vmcs_seg_desc_encoding(seg, &base, &limit, &access);
3228 	desc->base = vmcs_read(base);
3229 	desc->limit = vmcs_read(limit);
3230 	if (access != VMCS_INVALID_ENCODING) {
3231 		desc->access = vmcs_read(access);
3232 	} else {
3233 		desc->access = 0;
3234 	}
3235 
3236 	if (vmcs_loaded) {
3237 		vmx_vmcs_access_done(vmx, vcpu);
3238 	}
3239 	return (0);
3240 }
3241 
3242 static int
vmx_setdesc(void * arg,int vcpu,int seg,const struct seg_desc * desc)3243 vmx_setdesc(void *arg, int vcpu, int seg, const struct seg_desc *desc)
3244 {
3245 	struct vmx *vmx = arg;
3246 	uint32_t base, limit, access;
3247 
3248 	bool vmcs_loaded = vmx_vmcs_access_ensure(vmx, vcpu);
3249 
3250 	vmcs_seg_desc_encoding(seg, &base, &limit, &access);
3251 	vmcs_write(base, desc->base);
3252 	vmcs_write(limit, desc->limit);
3253 	if (access != VMCS_INVALID_ENCODING) {
3254 		vmcs_write(access, desc->access);
3255 	}
3256 
3257 	if (vmcs_loaded) {
3258 		vmx_vmcs_access_done(vmx, vcpu);
3259 	}
3260 	return (0);
3261 }
3262 
3263 static uint64_t *
vmx_msr_ptr(struct vmx * vmx,int vcpu,uint32_t msr)3264 vmx_msr_ptr(struct vmx *vmx, int vcpu, uint32_t msr)
3265 {
3266 	uint64_t *guest_msrs = vmx->guest_msrs[vcpu];
3267 
3268 	switch (msr) {
3269 	case MSR_LSTAR:
3270 		return (&guest_msrs[IDX_MSR_LSTAR]);
3271 	case MSR_CSTAR:
3272 		return (&guest_msrs[IDX_MSR_CSTAR]);
3273 	case MSR_STAR:
3274 		return (&guest_msrs[IDX_MSR_STAR]);
3275 	case MSR_SF_MASK:
3276 		return (&guest_msrs[IDX_MSR_SF_MASK]);
3277 	case MSR_KGSBASE:
3278 		return (&guest_msrs[IDX_MSR_KGSBASE]);
3279 	case MSR_PAT:
3280 		return (&guest_msrs[IDX_MSR_PAT]);
3281 	default:
3282 		return (NULL);
3283 	}
3284 }
3285 
3286 static int
vmx_msr_get(void * arg,int vcpu,uint32_t msr,uint64_t * valp)3287 vmx_msr_get(void *arg, int vcpu, uint32_t msr, uint64_t *valp)
3288 {
3289 	struct vmx *vmx = arg;
3290 
3291 	ASSERT(valp != NULL);
3292 
3293 	const uint64_t *msrp = vmx_msr_ptr(vmx, vcpu, msr);
3294 	if (msrp != NULL) {
3295 		*valp = *msrp;
3296 		return (0);
3297 	}
3298 
3299 	const uint32_t vmcs_enc = vmcs_msr_encoding(msr);
3300 	if (vmcs_enc != VMCS_INVALID_ENCODING) {
3301 		bool vmcs_loaded = vmx_vmcs_access_ensure(vmx, vcpu);
3302 
3303 		*valp = vmcs_read(vmcs_enc);
3304 
3305 		if (vmcs_loaded) {
3306 			vmx_vmcs_access_done(vmx, vcpu);
3307 		}
3308 		return (0);
3309 	}
3310 
3311 	return (EINVAL);
3312 }
3313 
3314 static int
vmx_msr_set(void * arg,int vcpu,uint32_t msr,uint64_t val)3315 vmx_msr_set(void *arg, int vcpu, uint32_t msr, uint64_t val)
3316 {
3317 	struct vmx *vmx = arg;
3318 
3319 	/* TODO: mask value */
3320 
3321 	uint64_t *msrp = vmx_msr_ptr(vmx, vcpu, msr);
3322 	if (msrp != NULL) {
3323 		*msrp = val;
3324 		return (0);
3325 	}
3326 
3327 	const uint32_t vmcs_enc = vmcs_msr_encoding(msr);
3328 	if (vmcs_enc != VMCS_INVALID_ENCODING) {
3329 		bool vmcs_loaded = vmx_vmcs_access_ensure(vmx, vcpu);
3330 
3331 		vmcs_write(vmcs_enc, val);
3332 
3333 		if (msr == MSR_EFER) {
3334 			vmx_sync_efer_state(vmx, vcpu, val);
3335 		}
3336 
3337 		if (vmcs_loaded) {
3338 			vmx_vmcs_access_done(vmx, vcpu);
3339 		}
3340 		return (0);
3341 	}
3342 	return (EINVAL);
3343 }
3344 
3345 static int
vmx_getcap(void * arg,int vcpu,int type,int * retval)3346 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3347 {
3348 	struct vmx *vmx = arg;
3349 	int vcap;
3350 	int ret;
3351 
3352 	ret = ENOENT;
3353 
3354 	vcap = vmx->cap[vcpu].set;
3355 
3356 	switch (type) {
3357 	case VM_CAP_HALT_EXIT:
3358 		ret = 0;
3359 		break;
3360 	case VM_CAP_PAUSE_EXIT:
3361 		if (cap_pause_exit)
3362 			ret = 0;
3363 		break;
3364 	case VM_CAP_MTRAP_EXIT:
3365 		if (cap_monitor_trap)
3366 			ret = 0;
3367 		break;
3368 	case VM_CAP_ENABLE_INVPCID:
3369 		if (cap_invpcid)
3370 			ret = 0;
3371 		break;
3372 	case VM_CAP_BPT_EXIT:
3373 		ret = 0;
3374 		break;
3375 	default:
3376 		break;
3377 	}
3378 
3379 	if (ret == 0)
3380 		*retval = (vcap & (1 << type)) ? 1 : 0;
3381 
3382 	return (ret);
3383 }
3384 
3385 static int
vmx_setcap(void * arg,int vcpu,int type,int val)3386 vmx_setcap(void *arg, int vcpu, int type, int val)
3387 {
3388 	struct vmx *vmx = arg;
3389 	uint32_t baseval, reg, flag;
3390 	uint32_t *pptr;
3391 	int error;
3392 
3393 	error = ENOENT;
3394 	pptr = NULL;
3395 
3396 	switch (type) {
3397 	case VM_CAP_HALT_EXIT:
3398 		error = 0;
3399 		pptr = &vmx->cap[vcpu].proc_ctls;
3400 		baseval = *pptr;
3401 		flag = PROCBASED_HLT_EXITING;
3402 		reg = VMCS_PRI_PROC_BASED_CTLS;
3403 		break;
3404 	case VM_CAP_MTRAP_EXIT:
3405 		if (cap_monitor_trap) {
3406 			error = 0;
3407 			pptr = &vmx->cap[vcpu].proc_ctls;
3408 			baseval = *pptr;
3409 			flag = PROCBASED_MTF;
3410 			reg = VMCS_PRI_PROC_BASED_CTLS;
3411 		}
3412 		break;
3413 	case VM_CAP_PAUSE_EXIT:
3414 		if (cap_pause_exit) {
3415 			error = 0;
3416 			pptr = &vmx->cap[vcpu].proc_ctls;
3417 			baseval = *pptr;
3418 			flag = PROCBASED_PAUSE_EXITING;
3419 			reg = VMCS_PRI_PROC_BASED_CTLS;
3420 		}
3421 		break;
3422 	case VM_CAP_ENABLE_INVPCID:
3423 		if (cap_invpcid) {
3424 			error = 0;
3425 			pptr = &vmx->cap[vcpu].proc_ctls2;
3426 			baseval = *pptr;
3427 			flag = PROCBASED2_ENABLE_INVPCID;
3428 			reg = VMCS_SEC_PROC_BASED_CTLS;
3429 		}
3430 		break;
3431 	case VM_CAP_BPT_EXIT:
3432 		error = 0;
3433 
3434 		/* Don't change the bitmap if we are tracing all exceptions. */
3435 		if (vmx->cap[vcpu].exc_bitmap != 0xffffffff) {
3436 			pptr = &vmx->cap[vcpu].exc_bitmap;
3437 			baseval = *pptr;
3438 			flag = (1 << IDT_BP);
3439 			reg = VMCS_EXCEPTION_BITMAP;
3440 		}
3441 		break;
3442 	default:
3443 		break;
3444 	}
3445 
3446 	if (error != 0) {
3447 		return (error);
3448 	}
3449 
3450 	if (pptr != NULL) {
3451 		if (val) {
3452 			baseval |= flag;
3453 		} else {
3454 			baseval &= ~flag;
3455 		}
3456 		vmcs_load(vmx->vmcs_pa[vcpu]);
3457 		vmcs_write(reg, baseval);
3458 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3459 
3460 		/*
3461 		 * Update optional stored flags, and record
3462 		 * setting
3463 		 */
3464 		*pptr = baseval;
3465 	}
3466 
3467 	if (val) {
3468 		vmx->cap[vcpu].set |= (1 << type);
3469 	} else {
3470 		vmx->cap[vcpu].set &= ~(1 << type);
3471 	}
3472 
3473 	return (0);
3474 }
3475 
3476 struct vlapic_vtx {
3477 	struct vlapic	vlapic;
3478 
3479 	/* Align to the nearest cacheline */
3480 	uint8_t		_pad[64 - (sizeof (struct vlapic) % 64)];
3481 
3482 	/* TMR handling state for posted interrupts */
3483 	uint32_t	tmr_active[8];
3484 	uint32_t	pending_level[8];
3485 	uint32_t	pending_edge[8];
3486 
3487 	struct pir_desc	*pir_desc;
3488 	struct vmx	*vmx;
3489 	uint_t	pending_prio;
3490 	boolean_t	tmr_sync;
3491 };
3492 
3493 CTASSERT((offsetof(struct vlapic_vtx, tmr_active) & 63) == 0);
3494 
3495 #define	VPR_PRIO_BIT(vpr)	(1 << ((vpr) >> 4))
3496 
3497 static vcpu_notify_t
vmx_apicv_set_ready(struct vlapic * vlapic,int vector,bool level)3498 vmx_apicv_set_ready(struct vlapic *vlapic, int vector, bool level)
3499 {
3500 	struct vlapic_vtx *vlapic_vtx;
3501 	struct pir_desc *pir_desc;
3502 	uint32_t mask, tmrval;
3503 	int idx;
3504 	vcpu_notify_t notify = VCPU_NOTIFY_NONE;
3505 
3506 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3507 	pir_desc = vlapic_vtx->pir_desc;
3508 	idx = vector / 32;
3509 	mask = 1UL << (vector % 32);
3510 
3511 	/*
3512 	 * If the currently asserted TMRs do not match the state requested by
3513 	 * the incoming interrupt, an exit will be required to reconcile those
3514 	 * bits in the APIC page.  This will keep the vLAPIC behavior in line
3515 	 * with the architecturally defined expectations.
3516 	 *
3517 	 * If actors of mixed types (edge and level) are racing against the same
3518 	 * vector (toggling its TMR bit back and forth), the results could
3519 	 * inconsistent.  Such circumstances are considered a rare edge case and
3520 	 * are never expected to be found in the wild.
3521 	 */
3522 	tmrval = atomic_load_acq_int(&vlapic_vtx->tmr_active[idx]);
3523 	if (!level) {
3524 		if ((tmrval & mask) != 0) {
3525 			/* Edge-triggered interrupt needs TMR de-asserted */
3526 			atomic_set_int(&vlapic_vtx->pending_edge[idx], mask);
3527 			atomic_store_rel_long(&pir_desc->pending, 1);
3528 			return (VCPU_NOTIFY_EXIT);
3529 		}
3530 	} else {
3531 		if ((tmrval & mask) == 0) {
3532 			/* Level-triggered interrupt needs TMR asserted */
3533 			atomic_set_int(&vlapic_vtx->pending_level[idx], mask);
3534 			atomic_store_rel_long(&pir_desc->pending, 1);
3535 			return (VCPU_NOTIFY_EXIT);
3536 		}
3537 	}
3538 
3539 	/*
3540 	 * If the interrupt request does not require manipulation of the TMRs
3541 	 * for delivery, set it in PIR descriptor.  It cannot be inserted into
3542 	 * the APIC page while the vCPU might be running.
3543 	 */
3544 	atomic_set_int(&pir_desc->pir[idx], mask);
3545 
3546 	/*
3547 	 * A notification is required whenever the 'pending' bit makes a
3548 	 * transition from 0->1.
3549 	 *
3550 	 * Even if the 'pending' bit is already asserted, notification about
3551 	 * the incoming interrupt may still be necessary.  For example, if a
3552 	 * vCPU is HLTed with a high PPR, a low priority interrupt would cause
3553 	 * the 0->1 'pending' transition with a notification, but the vCPU
3554 	 * would ignore the interrupt for the time being.  The same vCPU would
3555 	 * need to then be notified if a high-priority interrupt arrived which
3556 	 * satisfied the PPR.
3557 	 *
3558 	 * The priorities of interrupts injected while 'pending' is asserted
3559 	 * are tracked in a custom bitfield 'pending_prio'.  Should the
3560 	 * to-be-injected interrupt exceed the priorities already present, the
3561 	 * notification is sent.  The priorities recorded in 'pending_prio' are
3562 	 * cleared whenever the 'pending' bit makes another 0->1 transition.
3563 	 */
3564 	if (atomic_cmpset_long(&pir_desc->pending, 0, 1) != 0) {
3565 		notify = VCPU_NOTIFY_APIC;
3566 		vlapic_vtx->pending_prio = 0;
3567 	} else {
3568 		const uint_t old_prio = vlapic_vtx->pending_prio;
3569 		const uint_t prio_bit = VPR_PRIO_BIT(vector & APIC_TPR_INT);
3570 
3571 		if ((old_prio & prio_bit) == 0 && prio_bit > old_prio) {
3572 			atomic_set_int(&vlapic_vtx->pending_prio, prio_bit);
3573 			notify = VCPU_NOTIFY_APIC;
3574 		}
3575 	}
3576 
3577 	return (notify);
3578 }
3579 
3580 static void
vmx_apicv_accepted(struct vlapic * vlapic,int vector)3581 vmx_apicv_accepted(struct vlapic *vlapic, int vector)
3582 {
3583 	/*
3584 	 * When APICv is enabled for an instance, the traditional interrupt
3585 	 * injection method (populating ENTRY_INTR_INFO in the VMCS) is not
3586 	 * used and the CPU does the heavy lifting of virtual interrupt
3587 	 * delivery.  For that reason vmx_intr_accepted() should never be called
3588 	 * when APICv is enabled.
3589 	 */
3590 	panic("vmx_intr_accepted: not expected to be called");
3591 }
3592 
3593 static void
vmx_apicv_sync_tmr(struct vlapic * vlapic)3594 vmx_apicv_sync_tmr(struct vlapic *vlapic)
3595 {
3596 	struct vlapic_vtx *vlapic_vtx;
3597 	const uint32_t *tmrs;
3598 
3599 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3600 	tmrs = &vlapic_vtx->tmr_active[0];
3601 
3602 	if (!vlapic_vtx->tmr_sync) {
3603 		return;
3604 	}
3605 
3606 	vmcs_write(VMCS_EOI_EXIT0, ((uint64_t)tmrs[1] << 32) | tmrs[0]);
3607 	vmcs_write(VMCS_EOI_EXIT1, ((uint64_t)tmrs[3] << 32) | tmrs[2]);
3608 	vmcs_write(VMCS_EOI_EXIT2, ((uint64_t)tmrs[5] << 32) | tmrs[4]);
3609 	vmcs_write(VMCS_EOI_EXIT3, ((uint64_t)tmrs[7] << 32) | tmrs[6]);
3610 	vlapic_vtx->tmr_sync = B_FALSE;
3611 }
3612 
3613 static void
vmx_enable_x2apic_mode_ts(struct vlapic * vlapic)3614 vmx_enable_x2apic_mode_ts(struct vlapic *vlapic)
3615 {
3616 	struct vmx *vmx;
3617 	uint32_t proc_ctls;
3618 	int vcpuid;
3619 
3620 	vcpuid = vlapic->vcpuid;
3621 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3622 
3623 	proc_ctls = vmx->cap[vcpuid].proc_ctls;
3624 	proc_ctls &= ~PROCBASED_USE_TPR_SHADOW;
3625 	proc_ctls |= PROCBASED_CR8_LOAD_EXITING;
3626 	proc_ctls |= PROCBASED_CR8_STORE_EXITING;
3627 	vmx->cap[vcpuid].proc_ctls = proc_ctls;
3628 
3629 	vmcs_load(vmx->vmcs_pa[vcpuid]);
3630 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
3631 	vmcs_clear(vmx->vmcs_pa[vcpuid]);
3632 }
3633 
3634 static void
vmx_enable_x2apic_mode_vid(struct vlapic * vlapic)3635 vmx_enable_x2apic_mode_vid(struct vlapic *vlapic)
3636 {
3637 	struct vmx *vmx;
3638 	uint32_t proc_ctls2;
3639 	int vcpuid;
3640 
3641 	vcpuid = vlapic->vcpuid;
3642 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3643 
3644 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3645 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3646 	    ("%s: invalid proc_ctls2 %x", __func__, proc_ctls2));
3647 
3648 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3649 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3650 	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3651 
3652 	vmcs_load(vmx->vmcs_pa[vcpuid]);
3653 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3654 	vmcs_clear(vmx->vmcs_pa[vcpuid]);
3655 
3656 	vmx_allow_x2apic_msrs(vmx, vcpuid);
3657 }
3658 
3659 static void
vmx_apicv_notify(struct vlapic * vlapic,int hostcpu)3660 vmx_apicv_notify(struct vlapic *vlapic, int hostcpu)
3661 {
3662 	psm_send_pir_ipi(hostcpu);
3663 }
3664 
3665 static void
vmx_apicv_sync(struct vlapic * vlapic)3666 vmx_apicv_sync(struct vlapic *vlapic)
3667 {
3668 	struct vlapic_vtx *vlapic_vtx;
3669 	struct pir_desc *pir_desc;
3670 	struct LAPIC *lapic;
3671 	uint_t i;
3672 
3673 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3674 	pir_desc = vlapic_vtx->pir_desc;
3675 	lapic = vlapic->apic_page;
3676 
3677 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3678 		return;
3679 	}
3680 
3681 	vlapic_vtx->pending_prio = 0;
3682 
3683 	/* Make sure the invalid (0-15) vectors are not set */
3684 	ASSERT0(vlapic_vtx->pending_level[0] & 0xffff);
3685 	ASSERT0(vlapic_vtx->pending_edge[0] & 0xffff);
3686 	ASSERT0(pir_desc->pir[0] & 0xffff);
3687 
3688 	for (i = 0; i <= 7; i++) {
3689 		uint32_t *tmrp = &lapic->tmr0 + (i * 4);
3690 		uint32_t *irrp = &lapic->irr0 + (i * 4);
3691 
3692 		const uint32_t pending_level =
3693 		    atomic_readandclear_int(&vlapic_vtx->pending_level[i]);
3694 		const uint32_t pending_edge =
3695 		    atomic_readandclear_int(&vlapic_vtx->pending_edge[i]);
3696 		const uint32_t pending_inject =
3697 		    atomic_readandclear_int(&pir_desc->pir[i]);
3698 
3699 		if (pending_level != 0) {
3700 			/*
3701 			 * Level-triggered interrupts assert their corresponding
3702 			 * bit in the TMR when queued in IRR.
3703 			 */
3704 			*tmrp |= pending_level;
3705 			*irrp |= pending_level;
3706 		}
3707 		if (pending_edge != 0) {
3708 			/*
3709 			 * When queuing an edge-triggered interrupt in IRR, the
3710 			 * corresponding bit in the TMR is cleared.
3711 			 */
3712 			*tmrp &= ~pending_edge;
3713 			*irrp |= pending_edge;
3714 		}
3715 		if (pending_inject != 0) {
3716 			/*
3717 			 * Interrupts which do not require a change to the TMR
3718 			 * (because it already matches the necessary state) can
3719 			 * simply be queued in IRR.
3720 			 */
3721 			*irrp |= pending_inject;
3722 		}
3723 
3724 		if (*tmrp != vlapic_vtx->tmr_active[i]) {
3725 			/* Check if VMX EOI triggers require updating. */
3726 			vlapic_vtx->tmr_active[i] = *tmrp;
3727 			vlapic_vtx->tmr_sync = B_TRUE;
3728 		}
3729 	}
3730 }
3731 
3732 static void
vmx_tpr_shadow_enter(struct vlapic * vlapic)3733 vmx_tpr_shadow_enter(struct vlapic *vlapic)
3734 {
3735 	/*
3736 	 * When TPR shadowing is enabled, VMX will initiate a guest exit if its
3737 	 * TPR falls below a threshold priority.  That threshold is set to the
3738 	 * current TPR priority, since guest interrupt status should be
3739 	 * re-evaluated if its TPR is set lower.
3740 	 */
3741 	vmcs_write(VMCS_TPR_THRESHOLD, vlapic_get_cr8(vlapic));
3742 }
3743 
3744 static void
vmx_tpr_shadow_exit(struct vlapic * vlapic)3745 vmx_tpr_shadow_exit(struct vlapic *vlapic)
3746 {
3747 	/*
3748 	 * Unlike full APICv, where changes to the TPR are reflected in the PPR,
3749 	 * with TPR shadowing, that duty is relegated to the VMM.  Upon exit,
3750 	 * the PPR is updated to reflect any change in the TPR here.
3751 	 */
3752 	vlapic_sync_tpr(vlapic);
3753 }
3754 
3755 static struct vlapic *
vmx_vlapic_init(void * arg,int vcpuid)3756 vmx_vlapic_init(void *arg, int vcpuid)
3757 {
3758 	struct vmx *vmx = arg;
3759 	struct vlapic_vtx *vlapic_vtx;
3760 	struct vlapic *vlapic;
3761 
3762 	vlapic_vtx = kmem_zalloc(sizeof (struct vlapic_vtx), KM_SLEEP);
3763 	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3764 	vlapic_vtx->vmx = vmx;
3765 
3766 	vlapic = &vlapic_vtx->vlapic;
3767 	vlapic->vm = vmx->vm;
3768 	vlapic->vcpuid = vcpuid;
3769 	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3770 
3771 	if (vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW)) {
3772 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_ts;
3773 	}
3774 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
3775 		vlapic->ops.set_intr_ready = vmx_apicv_set_ready;
3776 		vlapic->ops.sync_state = vmx_apicv_sync;
3777 		vlapic->ops.intr_accepted = vmx_apicv_accepted;
3778 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_vid;
3779 
3780 		if (vmx_cap_en(vmx, VMX_CAP_APICV_PIR)) {
3781 			vlapic->ops.post_intr = vmx_apicv_notify;
3782 		}
3783 	}
3784 
3785 	vlapic_init(vlapic);
3786 
3787 	return (vlapic);
3788 }
3789 
3790 static void
vmx_vlapic_cleanup(void * arg,struct vlapic * vlapic)3791 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3792 {
3793 	vlapic_cleanup(vlapic);
3794 	kmem_free(vlapic, sizeof (struct vlapic_vtx));
3795 }
3796 
3797 static void
vmx_pause(void * arg,int vcpuid)3798 vmx_pause(void *arg, int vcpuid)
3799 {
3800 	struct vmx *vmx = arg;
3801 
3802 	VERIFY(vmx_vmcs_access_ensure(vmx, vcpuid));
3803 
3804 	/* Stash any interrupt/exception pending injection. */
3805 	vmx_stash_intinfo(vmx, vcpuid);
3806 
3807 	/*
3808 	 * Now that no event is pending injection, interrupt-window exiting and
3809 	 * NMI-window exiting can be disabled.  If/when this vCPU is made to run
3810 	 * again, those conditions will be reinstated when the now-queued events
3811 	 * are re-injected.
3812 	 */
3813 	vmx_clear_nmi_window_exiting(vmx, vcpuid);
3814 	vmx_clear_int_window_exiting(vmx, vcpuid);
3815 
3816 	vmx_vmcs_access_done(vmx, vcpuid);
3817 }
3818 
3819 static void
vmx_savectx(void * arg,int vcpu)3820 vmx_savectx(void *arg, int vcpu)
3821 {
3822 	struct vmx *vmx = arg;
3823 
3824 	if ((vmx->vmcs_state[vcpu] & VS_LOADED) != 0) {
3825 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3826 		vmx_msr_guest_exit(vmx, vcpu);
3827 		/*
3828 		 * Having VMCLEARed the VMCS, it can no longer be re-entered
3829 		 * with VMRESUME, but must be VMLAUNCHed again.
3830 		 */
3831 		vmx->vmcs_state[vcpu] &= ~VS_LAUNCHED;
3832 	}
3833 
3834 	reset_gdtr_limit();
3835 }
3836 
3837 static void
vmx_restorectx(void * arg,int vcpu)3838 vmx_restorectx(void *arg, int vcpu)
3839 {
3840 	struct vmx *vmx = arg;
3841 
3842 	ASSERT0(vmx->vmcs_state[vcpu] & VS_LAUNCHED);
3843 
3844 	if ((vmx->vmcs_state[vcpu] & VS_LOADED) != 0) {
3845 		vmx_msr_guest_enter(vmx, vcpu);
3846 		vmcs_load(vmx->vmcs_pa[vcpu]);
3847 	}
3848 }
3849 
3850 static freqratio_res_t
vmx_freq_ratio(uint64_t guest_hz,uint64_t host_hz,uint64_t * mult)3851 vmx_freq_ratio(uint64_t guest_hz, uint64_t host_hz, uint64_t *mult)
3852 {
3853 	if (guest_hz == host_hz) {
3854 		*mult = VM_TSCM_NOSCALE;
3855 		return (FR_SCALING_NOT_NEEDED);
3856 	}
3857 
3858 	/* VMX support not implemented at this time */
3859 	return (FR_SCALING_NOT_SUPPORTED);
3860 }
3861 
3862 struct vmm_ops vmm_ops_intel = {
3863 	.init		= vmx_init,
3864 	.resume		= vmx_restore,
3865 
3866 	.vminit		= vmx_vminit,
3867 	.vmrun		= vmx_run,
3868 	.vmcleanup	= vmx_vmcleanup,
3869 	.vmgetreg	= vmx_getreg,
3870 	.vmsetreg	= vmx_setreg,
3871 	.vmgetdesc	= vmx_getdesc,
3872 	.vmsetdesc	= vmx_setdesc,
3873 	.vmgetcap	= vmx_getcap,
3874 	.vmsetcap	= vmx_setcap,
3875 	.vlapic_init	= vmx_vlapic_init,
3876 	.vlapic_cleanup	= vmx_vlapic_cleanup,
3877 	.vmpause	= vmx_pause,
3878 
3879 	.vmsavectx	= vmx_savectx,
3880 	.vmrestorectx	= vmx_restorectx,
3881 
3882 	.vmgetmsr	= vmx_msr_get,
3883 	.vmsetmsr	= vmx_msr_set,
3884 
3885 	.vmfreqratio	= vmx_freq_ratio,
3886 	.fr_intsize	= INTEL_TSCM_INT_SIZE,
3887 	.fr_fracsize	= INTEL_TSCM_FRAC_SIZE,
3888 };
3889 
3890 /* Side-effect free HW validation derived from checks in vmx_init. */
3891 int
vmx_x86_supported(const char ** msg)3892 vmx_x86_supported(const char **msg)
3893 {
3894 	int error;
3895 	uint32_t tmp;
3896 
3897 	ASSERT(msg != NULL);
3898 
3899 	/* Check support for primary processor-based VM-execution controls */
3900 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
3901 	    MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_CTLS_ONE_SETTING,
3902 	    PROCBASED_CTLS_ZERO_SETTING, &tmp);
3903 	if (error) {
3904 		*msg = "processor does not support desired primary "
3905 		    "processor-based controls";
3906 		return (error);
3907 	}
3908 
3909 	/* Check support for secondary processor-based VM-execution controls */
3910 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
3911 	    MSR_VMX_PROCBASED_CTLS2, PROCBASED_CTLS2_ONE_SETTING,
3912 	    PROCBASED_CTLS2_ZERO_SETTING, &tmp);
3913 	if (error) {
3914 		*msg = "processor does not support desired secondary "
3915 		    "processor-based controls";
3916 		return (error);
3917 	}
3918 
3919 	/* Check support for pin-based VM-execution controls */
3920 	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
3921 	    MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_CTLS_ONE_SETTING,
3922 	    PINBASED_CTLS_ZERO_SETTING, &tmp);
3923 	if (error) {
3924 		*msg = "processor does not support desired pin-based controls";
3925 		return (error);
3926 	}
3927 
3928 	/* Check support for VM-exit controls */
3929 	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
3930 	    VM_EXIT_CTLS_ONE_SETTING, VM_EXIT_CTLS_ZERO_SETTING, &tmp);
3931 	if (error) {
3932 		*msg = "processor does not support desired exit controls";
3933 		return (error);
3934 	}
3935 
3936 	/* Check support for VM-entry controls */
3937 	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
3938 	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING, &tmp);
3939 	if (error) {
3940 		*msg = "processor does not support desired entry controls";
3941 		return (error);
3942 	}
3943 
3944 	/* Unrestricted guest is nominally optional, but not for us. */
3945 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
3946 	    PROCBASED2_UNRESTRICTED_GUEST, 0, &tmp);
3947 	if (error) {
3948 		*msg = "processor does not support desired unrestricted guest "
3949 		    "controls";
3950 		return (error);
3951 	}
3952 
3953 	return (0);
3954 }
3955