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