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