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