xref: /freebsd/sys/amd64/vmm/intel/vmx.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  * Copyright (c) 2018 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_bhyve_snapshot.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/smp.h>
40 #include <sys/kernel.h>
41 #include <sys/malloc.h>
42 #include <sys/pcpu.h>
43 #include <sys/proc.h>
44 #include <sys/reg.h>
45 #include <sys/smr.h>
46 #include <sys/sysctl.h>
47 
48 #include <vm/vm.h>
49 #include <vm/vm_extern.h>
50 #include <vm/pmap.h>
51 
52 #include <machine/psl.h>
53 #include <machine/cpufunc.h>
54 #include <machine/md_var.h>
55 #include <machine/segments.h>
56 #include <machine/smp.h>
57 #include <machine/specialreg.h>
58 #include <machine/vmparam.h>
59 
60 #include <machine/vmm.h>
61 #include <machine/vmm_dev.h>
62 #include <machine/vmm_instruction_emul.h>
63 #include <machine/vmm_snapshot.h>
64 
65 #include "vmm_lapic.h"
66 #include "vmm_host.h"
67 #include "vmm_ioport.h"
68 #include "vmm_ktr.h"
69 #include "vmm_stat.h"
70 #include "vatpic.h"
71 #include "vlapic.h"
72 #include "vlapic_priv.h"
73 
74 #include "ept.h"
75 #include "vmx_cpufunc.h"
76 #include "vmx.h"
77 #include "vmx_msr.h"
78 #include "x86.h"
79 #include "vmx_controls.h"
80 
81 #define	PINBASED_CTLS_ONE_SETTING					\
82 	(PINBASED_EXTINT_EXITING	|				\
83 	 PINBASED_NMI_EXITING		|				\
84 	 PINBASED_VIRTUAL_NMI)
85 #define	PINBASED_CTLS_ZERO_SETTING	0
86 
87 #define PROCBASED_CTLS_WINDOW_SETTING					\
88 	(PROCBASED_INT_WINDOW_EXITING	|				\
89 	 PROCBASED_NMI_WINDOW_EXITING)
90 
91 #define	PROCBASED_CTLS_ONE_SETTING					\
92 	(PROCBASED_SECONDARY_CONTROLS	|				\
93 	 PROCBASED_MWAIT_EXITING	|				\
94 	 PROCBASED_MONITOR_EXITING	|				\
95 	 PROCBASED_IO_EXITING		|				\
96 	 PROCBASED_MSR_BITMAPS		|				\
97 	 PROCBASED_CTLS_WINDOW_SETTING	|				\
98 	 PROCBASED_CR8_LOAD_EXITING	|				\
99 	 PROCBASED_CR8_STORE_EXITING)
100 #define	PROCBASED_CTLS_ZERO_SETTING	\
101 	(PROCBASED_CR3_LOAD_EXITING |	\
102 	PROCBASED_CR3_STORE_EXITING |	\
103 	PROCBASED_IO_BITMAPS)
104 
105 #define	PROCBASED_CTLS2_ONE_SETTING	PROCBASED2_ENABLE_EPT
106 #define	PROCBASED_CTLS2_ZERO_SETTING	0
107 
108 #define	VM_EXIT_CTLS_ONE_SETTING					\
109 	(VM_EXIT_SAVE_DEBUG_CONTROLS		|			\
110 	VM_EXIT_HOST_LMA			|			\
111 	VM_EXIT_SAVE_EFER			|			\
112 	VM_EXIT_LOAD_EFER			|			\
113 	VM_EXIT_ACKNOWLEDGE_INTERRUPT)
114 
115 #define	VM_EXIT_CTLS_ZERO_SETTING	0
116 
117 #define	VM_ENTRY_CTLS_ONE_SETTING					\
118 	(VM_ENTRY_LOAD_DEBUG_CONTROLS		|			\
119 	VM_ENTRY_LOAD_EFER)
120 
121 #define	VM_ENTRY_CTLS_ZERO_SETTING					\
122 	(VM_ENTRY_INTO_SMM			|			\
123 	VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
124 
125 #define	HANDLED		1
126 #define	UNHANDLED	0
127 
128 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
129 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
130 
131 bool vmx_have_msr_tsc_aux;
132 
133 SYSCTL_DECL(_hw_vmm);
134 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
135     NULL);
136 
137 int vmxon_enabled[MAXCPU];
138 static uint8_t *vmxon_region;
139 
140 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
141 static uint32_t exit_ctls, entry_ctls;
142 
143 static uint64_t cr0_ones_mask, cr0_zeros_mask;
144 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
145 	     &cr0_ones_mask, 0, NULL);
146 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
147 	     &cr0_zeros_mask, 0, NULL);
148 
149 static uint64_t cr4_ones_mask, cr4_zeros_mask;
150 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
151 	     &cr4_ones_mask, 0, NULL);
152 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
153 	     &cr4_zeros_mask, 0, NULL);
154 
155 static int vmx_initialized;
156 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
157 	   &vmx_initialized, 0, "Intel VMX initialized");
158 
159 /*
160  * Optional capabilities
161  */
162 static SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap,
163     CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
164     NULL);
165 
166 static int cap_halt_exit;
167 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
168     "HLT triggers a VM-exit");
169 
170 static int cap_pause_exit;
171 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
172     0, "PAUSE triggers a VM-exit");
173 
174 static int cap_wbinvd_exit;
175 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, wbinvd_exit, CTLFLAG_RD, &cap_wbinvd_exit,
176     0, "WBINVD triggers a VM-exit");
177 
178 static int cap_rdpid;
179 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, rdpid, CTLFLAG_RD, &cap_rdpid, 0,
180     "Guests are allowed to use RDPID");
181 
182 static int cap_rdtscp;
183 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, rdtscp, CTLFLAG_RD, &cap_rdtscp, 0,
184     "Guests are allowed to use RDTSCP");
185 
186 static int cap_unrestricted_guest;
187 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
188     &cap_unrestricted_guest, 0, "Unrestricted guests");
189 
190 static int cap_monitor_trap;
191 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
192     &cap_monitor_trap, 0, "Monitor trap flag");
193 
194 static int cap_invpcid;
195 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
196     0, "Guests are allowed to use INVPCID");
197 
198 static int tpr_shadowing;
199 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, tpr_shadowing, CTLFLAG_RD,
200     &tpr_shadowing, 0, "TPR shadowing support");
201 
202 static int virtual_interrupt_delivery;
203 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
204     &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
205 
206 static int posted_interrupts;
207 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
208     &posted_interrupts, 0, "APICv posted interrupt support");
209 
210 static int pirvec = -1;
211 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
212     &pirvec, 0, "APICv posted interrupt vector");
213 
214 static struct unrhdr *vpid_unr;
215 static u_int vpid_alloc_failed;
216 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
217 	    &vpid_alloc_failed, 0, NULL);
218 
219 int guest_l1d_flush;
220 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush, CTLFLAG_RD,
221     &guest_l1d_flush, 0, NULL);
222 int guest_l1d_flush_sw;
223 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush_sw, CTLFLAG_RD,
224     &guest_l1d_flush_sw, 0, NULL);
225 
226 static struct msr_entry msr_load_list[1] __aligned(16);
227 
228 /*
229  * The definitions of SDT probes for VMX.
230  */
231 
232 SDT_PROBE_DEFINE3(vmm, vmx, exit, entry,
233     "struct vmx *", "int", "struct vm_exit *");
234 
235 SDT_PROBE_DEFINE4(vmm, vmx, exit, taskswitch,
236     "struct vmx *", "int", "struct vm_exit *", "struct vm_task_switch *");
237 
238 SDT_PROBE_DEFINE4(vmm, vmx, exit, craccess,
239     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
240 
241 SDT_PROBE_DEFINE4(vmm, vmx, exit, rdmsr,
242     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
243 
244 SDT_PROBE_DEFINE5(vmm, vmx, exit, wrmsr,
245     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "uint64_t");
246 
247 SDT_PROBE_DEFINE3(vmm, vmx, exit, halt,
248     "struct vmx *", "int", "struct vm_exit *");
249 
250 SDT_PROBE_DEFINE3(vmm, vmx, exit, mtrap,
251     "struct vmx *", "int", "struct vm_exit *");
252 
253 SDT_PROBE_DEFINE3(vmm, vmx, exit, pause,
254     "struct vmx *", "int", "struct vm_exit *");
255 
256 SDT_PROBE_DEFINE3(vmm, vmx, exit, intrwindow,
257     "struct vmx *", "int", "struct vm_exit *");
258 
259 SDT_PROBE_DEFINE4(vmm, vmx, exit, interrupt,
260     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
261 
262 SDT_PROBE_DEFINE3(vmm, vmx, exit, nmiwindow,
263     "struct vmx *", "int", "struct vm_exit *");
264 
265 SDT_PROBE_DEFINE3(vmm, vmx, exit, inout,
266     "struct vmx *", "int", "struct vm_exit *");
267 
268 SDT_PROBE_DEFINE3(vmm, vmx, exit, cpuid,
269     "struct vmx *", "int", "struct vm_exit *");
270 
271 SDT_PROBE_DEFINE5(vmm, vmx, exit, exception,
272     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "int");
273 
274 SDT_PROBE_DEFINE5(vmm, vmx, exit, nestedfault,
275     "struct vmx *", "int", "struct vm_exit *", "uint64_t", "uint64_t");
276 
277 SDT_PROBE_DEFINE4(vmm, vmx, exit, mmiofault,
278     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
279 
280 SDT_PROBE_DEFINE3(vmm, vmx, exit, eoi,
281     "struct vmx *", "int", "struct vm_exit *");
282 
283 SDT_PROBE_DEFINE3(vmm, vmx, exit, apicaccess,
284     "struct vmx *", "int", "struct vm_exit *");
285 
286 SDT_PROBE_DEFINE4(vmm, vmx, exit, apicwrite,
287     "struct vmx *", "int", "struct vm_exit *", "struct vlapic *");
288 
289 SDT_PROBE_DEFINE3(vmm, vmx, exit, xsetbv,
290     "struct vmx *", "int", "struct vm_exit *");
291 
292 SDT_PROBE_DEFINE3(vmm, vmx, exit, monitor,
293     "struct vmx *", "int", "struct vm_exit *");
294 
295 SDT_PROBE_DEFINE3(vmm, vmx, exit, mwait,
296     "struct vmx *", "int", "struct vm_exit *");
297 
298 SDT_PROBE_DEFINE3(vmm, vmx, exit, vminsn,
299     "struct vmx *", "int", "struct vm_exit *");
300 
301 SDT_PROBE_DEFINE4(vmm, vmx, exit, unknown,
302     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
303 
304 SDT_PROBE_DEFINE4(vmm, vmx, exit, return,
305     "struct vmx *", "int", "struct vm_exit *", "int");
306 
307 /*
308  * Use the last page below 4GB as the APIC access address. This address is
309  * occupied by the boot firmware so it is guaranteed that it will not conflict
310  * with a page in system memory.
311  */
312 #define	APIC_ACCESS_ADDRESS	0xFFFFF000
313 
314 static int vmx_getdesc(void *vcpui, int reg, struct seg_desc *desc);
315 static int vmx_getreg(void *vcpui, int reg, uint64_t *retval);
316 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
317 static void vmx_inject_pir(struct vlapic *vlapic);
318 #ifdef BHYVE_SNAPSHOT
319 static int vmx_restore_tsc(void *vcpui, uint64_t now);
320 #endif
321 
322 static inline bool
323 host_has_rdpid(void)
324 {
325 	return ((cpu_stdext_feature2 & CPUID_STDEXT2_RDPID) != 0);
326 }
327 
328 static inline bool
329 host_has_rdtscp(void)
330 {
331 	return ((amd_feature & AMDID_RDTSCP) != 0);
332 }
333 
334 #ifdef KTR
335 static const char *
336 exit_reason_to_str(int reason)
337 {
338 	static char reasonbuf[32];
339 
340 	switch (reason) {
341 	case EXIT_REASON_EXCEPTION:
342 		return "exception";
343 	case EXIT_REASON_EXT_INTR:
344 		return "extint";
345 	case EXIT_REASON_TRIPLE_FAULT:
346 		return "triplefault";
347 	case EXIT_REASON_INIT:
348 		return "init";
349 	case EXIT_REASON_SIPI:
350 		return "sipi";
351 	case EXIT_REASON_IO_SMI:
352 		return "iosmi";
353 	case EXIT_REASON_SMI:
354 		return "smi";
355 	case EXIT_REASON_INTR_WINDOW:
356 		return "intrwindow";
357 	case EXIT_REASON_NMI_WINDOW:
358 		return "nmiwindow";
359 	case EXIT_REASON_TASK_SWITCH:
360 		return "taskswitch";
361 	case EXIT_REASON_CPUID:
362 		return "cpuid";
363 	case EXIT_REASON_GETSEC:
364 		return "getsec";
365 	case EXIT_REASON_HLT:
366 		return "hlt";
367 	case EXIT_REASON_INVD:
368 		return "invd";
369 	case EXIT_REASON_INVLPG:
370 		return "invlpg";
371 	case EXIT_REASON_RDPMC:
372 		return "rdpmc";
373 	case EXIT_REASON_RDTSC:
374 		return "rdtsc";
375 	case EXIT_REASON_RSM:
376 		return "rsm";
377 	case EXIT_REASON_VMCALL:
378 		return "vmcall";
379 	case EXIT_REASON_VMCLEAR:
380 		return "vmclear";
381 	case EXIT_REASON_VMLAUNCH:
382 		return "vmlaunch";
383 	case EXIT_REASON_VMPTRLD:
384 		return "vmptrld";
385 	case EXIT_REASON_VMPTRST:
386 		return "vmptrst";
387 	case EXIT_REASON_VMREAD:
388 		return "vmread";
389 	case EXIT_REASON_VMRESUME:
390 		return "vmresume";
391 	case EXIT_REASON_VMWRITE:
392 		return "vmwrite";
393 	case EXIT_REASON_VMXOFF:
394 		return "vmxoff";
395 	case EXIT_REASON_VMXON:
396 		return "vmxon";
397 	case EXIT_REASON_CR_ACCESS:
398 		return "craccess";
399 	case EXIT_REASON_DR_ACCESS:
400 		return "draccess";
401 	case EXIT_REASON_INOUT:
402 		return "inout";
403 	case EXIT_REASON_RDMSR:
404 		return "rdmsr";
405 	case EXIT_REASON_WRMSR:
406 		return "wrmsr";
407 	case EXIT_REASON_INVAL_VMCS:
408 		return "invalvmcs";
409 	case EXIT_REASON_INVAL_MSR:
410 		return "invalmsr";
411 	case EXIT_REASON_MWAIT:
412 		return "mwait";
413 	case EXIT_REASON_MTF:
414 		return "mtf";
415 	case EXIT_REASON_MONITOR:
416 		return "monitor";
417 	case EXIT_REASON_PAUSE:
418 		return "pause";
419 	case EXIT_REASON_MCE_DURING_ENTRY:
420 		return "mce-during-entry";
421 	case EXIT_REASON_TPR:
422 		return "tpr";
423 	case EXIT_REASON_APIC_ACCESS:
424 		return "apic-access";
425 	case EXIT_REASON_GDTR_IDTR:
426 		return "gdtridtr";
427 	case EXIT_REASON_LDTR_TR:
428 		return "ldtrtr";
429 	case EXIT_REASON_EPT_FAULT:
430 		return "eptfault";
431 	case EXIT_REASON_EPT_MISCONFIG:
432 		return "eptmisconfig";
433 	case EXIT_REASON_INVEPT:
434 		return "invept";
435 	case EXIT_REASON_RDTSCP:
436 		return "rdtscp";
437 	case EXIT_REASON_VMX_PREEMPT:
438 		return "vmxpreempt";
439 	case EXIT_REASON_INVVPID:
440 		return "invvpid";
441 	case EXIT_REASON_WBINVD:
442 		return "wbinvd";
443 	case EXIT_REASON_XSETBV:
444 		return "xsetbv";
445 	case EXIT_REASON_APIC_WRITE:
446 		return "apic-write";
447 	default:
448 		snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
449 		return (reasonbuf);
450 	}
451 }
452 #endif	/* KTR */
453 
454 static int
455 vmx_allow_x2apic_msrs(struct vmx *vmx)
456 {
457 	int i, error;
458 
459 	error = 0;
460 
461 	/*
462 	 * Allow readonly access to the following x2APIC MSRs from the guest.
463 	 */
464 	error += guest_msr_ro(vmx, MSR_APIC_ID);
465 	error += guest_msr_ro(vmx, MSR_APIC_VERSION);
466 	error += guest_msr_ro(vmx, MSR_APIC_LDR);
467 	error += guest_msr_ro(vmx, MSR_APIC_SVR);
468 
469 	for (i = 0; i < 8; i++)
470 		error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
471 
472 	for (i = 0; i < 8; i++)
473 		error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
474 
475 	for (i = 0; i < 8; i++)
476 		error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
477 
478 	error += guest_msr_ro(vmx, MSR_APIC_ESR);
479 	error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
480 	error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
481 	error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
482 	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
483 	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
484 	error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
485 	error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
486 	error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
487 	error += guest_msr_ro(vmx, MSR_APIC_ICR);
488 
489 	/*
490 	 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
491 	 *
492 	 * These registers get special treatment described in the section
493 	 * "Virtualizing MSR-Based APIC Accesses".
494 	 */
495 	error += guest_msr_rw(vmx, MSR_APIC_TPR);
496 	error += guest_msr_rw(vmx, MSR_APIC_EOI);
497 	error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
498 
499 	return (error);
500 }
501 
502 u_long
503 vmx_fix_cr0(u_long cr0)
504 {
505 
506 	return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
507 }
508 
509 u_long
510 vmx_fix_cr4(u_long cr4)
511 {
512 
513 	return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
514 }
515 
516 static void
517 vpid_free(int vpid)
518 {
519 	if (vpid < 0 || vpid > 0xffff)
520 		panic("vpid_free: invalid vpid %d", vpid);
521 
522 	/*
523 	 * VPIDs [0,vm_maxcpu] are special and are not allocated from
524 	 * the unit number allocator.
525 	 */
526 
527 	if (vpid > vm_maxcpu)
528 		free_unr(vpid_unr, vpid);
529 }
530 
531 static uint16_t
532 vpid_alloc(int vcpuid)
533 {
534 	int x;
535 
536 	/*
537 	 * If the "enable vpid" execution control is not enabled then the
538 	 * VPID is required to be 0 for all vcpus.
539 	 */
540 	if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0)
541 		return (0);
542 
543 	/*
544 	 * Try to allocate a unique VPID for each from the unit number
545 	 * allocator.
546 	 */
547 	x = alloc_unr(vpid_unr);
548 
549 	if (x == -1) {
550 		atomic_add_int(&vpid_alloc_failed, 1);
551 
552 		/*
553 		 * If the unit number allocator does not have enough unique
554 		 * VPIDs then we need to allocate from the [1,vm_maxcpu] range.
555 		 *
556 		 * These VPIDs are not be unique across VMs but this does not
557 		 * affect correctness because the combined mappings are also
558 		 * tagged with the EP4TA which is unique for each VM.
559 		 *
560 		 * It is still sub-optimal because the invvpid will invalidate
561 		 * combined mappings for a particular VPID across all EP4TAs.
562 		 */
563 		return (vcpuid + 1);
564 	}
565 
566 	return (x);
567 }
568 
569 static void
570 vpid_init(void)
571 {
572 	/*
573 	 * VPID 0 is required when the "enable VPID" execution control is
574 	 * disabled.
575 	 *
576 	 * VPIDs [1,vm_maxcpu] are used as the "overflow namespace" when the
577 	 * unit number allocator does not have sufficient unique VPIDs to
578 	 * satisfy the allocation.
579 	 *
580 	 * The remaining VPIDs are managed by the unit number allocator.
581 	 */
582 	vpid_unr = new_unrhdr(vm_maxcpu + 1, 0xffff, NULL);
583 }
584 
585 static void
586 vmx_disable(void *arg __unused)
587 {
588 	struct invvpid_desc invvpid_desc = { 0 };
589 	struct invept_desc invept_desc = { 0 };
590 
591 	if (vmxon_enabled[curcpu]) {
592 		/*
593 		 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
594 		 *
595 		 * VMXON or VMXOFF are not required to invalidate any TLB
596 		 * caching structures. This prevents potential retention of
597 		 * cached information in the TLB between distinct VMX episodes.
598 		 */
599 		invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
600 		invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
601 		vmxoff();
602 	}
603 	load_cr4(rcr4() & ~CR4_VMXE);
604 }
605 
606 static int
607 vmx_modcleanup(void)
608 {
609 
610 	if (pirvec >= 0)
611 		lapic_ipi_free(pirvec);
612 
613 	if (vpid_unr != NULL) {
614 		delete_unrhdr(vpid_unr);
615 		vpid_unr = NULL;
616 	}
617 
618 	if (nmi_flush_l1d_sw == 1)
619 		nmi_flush_l1d_sw = 0;
620 
621 	smp_rendezvous(NULL, vmx_disable, NULL, NULL);
622 
623 	if (vmxon_region != NULL)
624 		kmem_free(vmxon_region, (mp_maxid + 1) * PAGE_SIZE);
625 
626 	return (0);
627 }
628 
629 static void
630 vmx_enable(void *arg __unused)
631 {
632 	int error;
633 	uint64_t feature_control;
634 
635 	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
636 	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
637 	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
638 		wrmsr(MSR_IA32_FEATURE_CONTROL,
639 		    feature_control | IA32_FEATURE_CONTROL_VMX_EN |
640 		    IA32_FEATURE_CONTROL_LOCK);
641 	}
642 
643 	load_cr4(rcr4() | CR4_VMXE);
644 
645 	*(uint32_t *)&vmxon_region[curcpu * PAGE_SIZE] = vmx_revision();
646 	error = vmxon(&vmxon_region[curcpu * PAGE_SIZE]);
647 	if (error == 0)
648 		vmxon_enabled[curcpu] = 1;
649 }
650 
651 static void
652 vmx_modresume(void)
653 {
654 
655 	if (vmxon_enabled[curcpu])
656 		vmxon(&vmxon_region[curcpu * PAGE_SIZE]);
657 }
658 
659 static int
660 vmx_modinit(int ipinum)
661 {
662 	int error;
663 	uint64_t basic, fixed0, fixed1, feature_control;
664 	uint32_t tmp, procbased2_vid_bits;
665 
666 	/* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
667 	if (!(cpu_feature2 & CPUID2_VMX)) {
668 		printf("vmx_modinit: processor does not support VMX "
669 		    "operation\n");
670 		return (ENXIO);
671 	}
672 
673 	/*
674 	 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
675 	 * are set (bits 0 and 2 respectively).
676 	 */
677 	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
678 	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
679 	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
680 		printf("vmx_modinit: VMX operation disabled by BIOS\n");
681 		return (ENXIO);
682 	}
683 
684 	/*
685 	 * Verify capabilities MSR_VMX_BASIC:
686 	 * - bit 54 indicates support for INS/OUTS decoding
687 	 */
688 	basic = rdmsr(MSR_VMX_BASIC);
689 	if ((basic & (1UL << 54)) == 0) {
690 		printf("vmx_modinit: processor does not support desired basic "
691 		    "capabilities\n");
692 		return (EINVAL);
693 	}
694 
695 	/* Check support for primary processor-based VM-execution controls */
696 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
697 			       MSR_VMX_TRUE_PROCBASED_CTLS,
698 			       PROCBASED_CTLS_ONE_SETTING,
699 			       PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
700 	if (error) {
701 		printf("vmx_modinit: processor does not support desired "
702 		    "primary processor-based controls\n");
703 		return (error);
704 	}
705 
706 	/* Clear the processor-based ctl bits that are set on demand */
707 	procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
708 
709 	/* Check support for secondary processor-based VM-execution controls */
710 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
711 			       MSR_VMX_PROCBASED_CTLS2,
712 			       PROCBASED_CTLS2_ONE_SETTING,
713 			       PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
714 	if (error) {
715 		printf("vmx_modinit: processor does not support desired "
716 		    "secondary processor-based controls\n");
717 		return (error);
718 	}
719 
720 	/* Check support for VPID */
721 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
722 			       PROCBASED2_ENABLE_VPID, 0, &tmp);
723 	if (error == 0)
724 		procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
725 
726 	/* Check support for pin-based VM-execution controls */
727 	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
728 			       MSR_VMX_TRUE_PINBASED_CTLS,
729 			       PINBASED_CTLS_ONE_SETTING,
730 			       PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
731 	if (error) {
732 		printf("vmx_modinit: processor does not support desired "
733 		    "pin-based controls\n");
734 		return (error);
735 	}
736 
737 	/* Check support for VM-exit controls */
738 	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
739 			       VM_EXIT_CTLS_ONE_SETTING,
740 			       VM_EXIT_CTLS_ZERO_SETTING,
741 			       &exit_ctls);
742 	if (error) {
743 		printf("vmx_modinit: processor does not support desired "
744 		    "exit controls\n");
745 		return (error);
746 	}
747 
748 	/* Check support for VM-entry controls */
749 	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
750 	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
751 	    &entry_ctls);
752 	if (error) {
753 		printf("vmx_modinit: processor does not support desired "
754 		    "entry controls\n");
755 		return (error);
756 	}
757 
758 	/*
759 	 * Check support for optional features by testing them
760 	 * as individual bits
761 	 */
762 	cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
763 					MSR_VMX_TRUE_PROCBASED_CTLS,
764 					PROCBASED_HLT_EXITING, 0,
765 					&tmp) == 0);
766 
767 	cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
768 					MSR_VMX_PROCBASED_CTLS,
769 					PROCBASED_MTF, 0,
770 					&tmp) == 0);
771 
772 	cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
773 					 MSR_VMX_TRUE_PROCBASED_CTLS,
774 					 PROCBASED_PAUSE_EXITING, 0,
775 					 &tmp) == 0);
776 
777 	cap_wbinvd_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
778 					MSR_VMX_PROCBASED_CTLS2,
779 					PROCBASED2_WBINVD_EXITING,
780 					0,
781 					&tmp) == 0);
782 
783 	/*
784 	 * Check support for RDPID and/or RDTSCP.
785 	 *
786 	 * Support a pass-through-based implementation of these via the
787 	 * "enable RDTSCP" VM-execution control and the "RDTSC exiting"
788 	 * VM-execution control.
789 	 *
790 	 * The "enable RDTSCP" VM-execution control applies to both RDPID
791 	 * and RDTSCP (see SDM volume 3, section 25.3, "Changes to
792 	 * Instruction Behavior in VMX Non-root operation"); this is why
793 	 * only this VM-execution control needs to be enabled in order to
794 	 * enable passing through whichever of RDPID and/or RDTSCP are
795 	 * supported by the host.
796 	 *
797 	 * The "RDTSC exiting" VM-execution control applies to both RDTSC
798 	 * and RDTSCP (again, per SDM volume 3, section 25.3), and is
799 	 * already set up for RDTSC and RDTSCP pass-through by the current
800 	 * implementation of RDTSC.
801 	 *
802 	 * Although RDPID and RDTSCP are optional capabilities, since there
803 	 * does not currently seem to be a use case for enabling/disabling
804 	 * these via libvmmapi, choose not to support this and, instead,
805 	 * just statically always enable or always disable this support
806 	 * across all vCPUs on all VMs. (Note that there may be some
807 	 * complications to providing this functionality, e.g., the MSR
808 	 * bitmap is currently per-VM rather than per-vCPU while the
809 	 * capability API wants to be able to control capabilities on a
810 	 * per-vCPU basis).
811 	 */
812 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
813 			       MSR_VMX_PROCBASED_CTLS2,
814 			       PROCBASED2_ENABLE_RDTSCP, 0, &tmp);
815 	cap_rdpid = error == 0 && host_has_rdpid();
816 	cap_rdtscp = error == 0 && host_has_rdtscp();
817 	if (cap_rdpid || cap_rdtscp) {
818 		procbased_ctls2 |= PROCBASED2_ENABLE_RDTSCP;
819 		vmx_have_msr_tsc_aux = true;
820 	}
821 
822 	cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
823 					MSR_VMX_PROCBASED_CTLS2,
824 					PROCBASED2_UNRESTRICTED_GUEST, 0,
825 				        &tmp) == 0);
826 
827 	cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
828 	    MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
829 	    &tmp) == 0);
830 
831 	/*
832 	 * Check support for TPR shadow.
833 	 */
834 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
835 	    MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
836 	    &tmp);
837 	if (error == 0) {
838 		tpr_shadowing = 1;
839 		TUNABLE_INT_FETCH("hw.vmm.vmx.use_tpr_shadowing",
840 		    &tpr_shadowing);
841 	}
842 
843 	if (tpr_shadowing) {
844 		procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
845 		procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
846 		procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
847 	}
848 
849 	/*
850 	 * Check support for virtual interrupt delivery.
851 	 */
852 	procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
853 	    PROCBASED2_VIRTUALIZE_X2APIC_MODE |
854 	    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
855 	    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
856 
857 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
858 	    procbased2_vid_bits, 0, &tmp);
859 	if (error == 0 && tpr_shadowing) {
860 		virtual_interrupt_delivery = 1;
861 		TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
862 		    &virtual_interrupt_delivery);
863 	}
864 
865 	if (virtual_interrupt_delivery) {
866 		procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
867 		procbased_ctls2 |= procbased2_vid_bits;
868 		procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
869 
870 		/*
871 		 * Check for Posted Interrupts only if Virtual Interrupt
872 		 * Delivery is enabled.
873 		 */
874 		error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
875 		    MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
876 		    &tmp);
877 		if (error == 0) {
878 			pirvec = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
879 			    &IDTVEC(justreturn));
880 			if (pirvec < 0) {
881 				if (bootverbose) {
882 					printf("vmx_modinit: unable to "
883 					    "allocate posted interrupt "
884 					    "vector\n");
885 				}
886 			} else {
887 				posted_interrupts = 1;
888 				TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
889 				    &posted_interrupts);
890 			}
891 		}
892 	}
893 
894 	if (posted_interrupts)
895 		    pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
896 
897 	/* Initialize EPT */
898 	error = ept_init(ipinum);
899 	if (error) {
900 		printf("vmx_modinit: ept initialization failed (%d)\n", error);
901 		return (error);
902 	}
903 
904 	guest_l1d_flush = (cpu_ia32_arch_caps &
905 	    IA32_ARCH_CAP_SKIP_L1DFL_VMENTRY) == 0;
906 	TUNABLE_INT_FETCH("hw.vmm.l1d_flush", &guest_l1d_flush);
907 
908 	/*
909 	 * L1D cache flush is enabled.  Use IA32_FLUSH_CMD MSR when
910 	 * available.  Otherwise fall back to the software flush
911 	 * method which loads enough data from the kernel text to
912 	 * flush existing L1D content, both on VMX entry and on NMI
913 	 * return.
914 	 */
915 	if (guest_l1d_flush) {
916 		if ((cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) == 0) {
917 			guest_l1d_flush_sw = 1;
918 			TUNABLE_INT_FETCH("hw.vmm.l1d_flush_sw",
919 			    &guest_l1d_flush_sw);
920 		}
921 		if (guest_l1d_flush_sw) {
922 			if (nmi_flush_l1d_sw <= 1)
923 				nmi_flush_l1d_sw = 1;
924 		} else {
925 			msr_load_list[0].index = MSR_IA32_FLUSH_CMD;
926 			msr_load_list[0].val = IA32_FLUSH_CMD_L1D;
927 		}
928 	}
929 
930 	/*
931 	 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
932 	 */
933 	fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
934 	fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
935 	cr0_ones_mask = fixed0 & fixed1;
936 	cr0_zeros_mask = ~fixed0 & ~fixed1;
937 
938 	/*
939 	 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
940 	 * if unrestricted guest execution is allowed.
941 	 */
942 	if (cap_unrestricted_guest)
943 		cr0_ones_mask &= ~(CR0_PG | CR0_PE);
944 
945 	/*
946 	 * Do not allow the guest to set CR0_NW or CR0_CD.
947 	 */
948 	cr0_zeros_mask |= (CR0_NW | CR0_CD);
949 
950 	fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
951 	fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
952 	cr4_ones_mask = fixed0 & fixed1;
953 	cr4_zeros_mask = ~fixed0 & ~fixed1;
954 
955 	vpid_init();
956 
957 	vmx_msr_init();
958 
959 	/* enable VMX operation */
960 	vmxon_region = kmem_malloc((mp_maxid + 1) * PAGE_SIZE,
961 	    M_WAITOK | M_ZERO);
962 	smp_rendezvous(NULL, vmx_enable, NULL, NULL);
963 
964 	vmx_initialized = 1;
965 
966 	return (0);
967 }
968 
969 static void
970 vmx_trigger_hostintr(int vector)
971 {
972 	uintptr_t func;
973 	struct gate_descriptor *gd;
974 
975 	gd = &idt[vector];
976 
977 	KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
978 	    "invalid vector %d", vector));
979 	KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
980 	    vector));
981 	KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
982 	    "has invalid type %d", vector, gd->gd_type));
983 	KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
984 	    "has invalid dpl %d", vector, gd->gd_dpl));
985 	KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
986 	    "for vector %d has invalid selector %d", vector, gd->gd_selector));
987 	KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
988 	    "IST %d", vector, gd->gd_ist));
989 
990 	func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
991 	vmx_call_isr(func);
992 }
993 
994 static int
995 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
996 {
997 	int error, mask_ident, shadow_ident;
998 	uint64_t mask_value;
999 
1000 	if (which != 0 && which != 4)
1001 		panic("vmx_setup_cr_shadow: unknown cr%d", which);
1002 
1003 	if (which == 0) {
1004 		mask_ident = VMCS_CR0_MASK;
1005 		mask_value = cr0_ones_mask | cr0_zeros_mask;
1006 		shadow_ident = VMCS_CR0_SHADOW;
1007 	} else {
1008 		mask_ident = VMCS_CR4_MASK;
1009 		mask_value = cr4_ones_mask | cr4_zeros_mask;
1010 		shadow_ident = VMCS_CR4_SHADOW;
1011 	}
1012 
1013 	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
1014 	if (error)
1015 		return (error);
1016 
1017 	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
1018 	if (error)
1019 		return (error);
1020 
1021 	return (0);
1022 }
1023 #define	vmx_setup_cr0_shadow(vmcs,init)	vmx_setup_cr_shadow(0, (vmcs), (init))
1024 #define	vmx_setup_cr4_shadow(vmcs,init)	vmx_setup_cr_shadow(4, (vmcs), (init))
1025 
1026 static void *
1027 vmx_init(struct vm *vm, pmap_t pmap)
1028 {
1029 	int error __diagused;
1030 	struct vmx *vmx;
1031 
1032 	vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
1033 	vmx->vm = vm;
1034 
1035 	vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pmltop));
1036 
1037 	/*
1038 	 * Clean up EPTP-tagged guest physical and combined mappings
1039 	 *
1040 	 * VMX transitions are not required to invalidate any guest physical
1041 	 * mappings. So, it may be possible for stale guest physical mappings
1042 	 * to be present in the processor TLBs.
1043 	 *
1044 	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
1045 	 */
1046 	ept_invalidate_mappings(vmx->eptp);
1047 
1048 	vmx->msr_bitmap = malloc_aligned(PAGE_SIZE, PAGE_SIZE, M_VMX,
1049 	    M_WAITOK | M_ZERO);
1050 	msr_bitmap_initialize(vmx->msr_bitmap);
1051 
1052 	/*
1053 	 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
1054 	 * The guest FSBASE and GSBASE are saved and restored during
1055 	 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
1056 	 * always restored from the vmcs host state area on vm-exit.
1057 	 *
1058 	 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
1059 	 * how they are saved/restored so can be directly accessed by the
1060 	 * guest.
1061 	 *
1062 	 * MSR_EFER is saved and restored in the guest VMCS area on a
1063 	 * VM exit and entry respectively. It is also restored from the
1064 	 * host VMCS area on a VM exit.
1065 	 *
1066 	 * The TSC MSR is exposed read-only. Writes are disallowed as
1067 	 * that will impact the host TSC.  If the guest does a write
1068 	 * the "use TSC offsetting" execution control is enabled and the
1069 	 * difference between the host TSC and the guest TSC is written
1070 	 * into the TSC offset in the VMCS.
1071 	 *
1072 	 * Guest TSC_AUX support is enabled if any of guest RDPID and/or
1073 	 * guest RDTSCP support are enabled (since, as per Table 2-2 in SDM
1074 	 * volume 4, TSC_AUX is supported if any of RDPID and/or RDTSCP are
1075 	 * supported). If guest TSC_AUX support is enabled, TSC_AUX is
1076 	 * exposed read-only so that the VMM can do one fewer MSR read per
1077 	 * exit than if this register were exposed read-write; the guest
1078 	 * restore value can be updated during guest writes (expected to be
1079 	 * rare) instead of during all exits (common).
1080 	 */
1081 	if (guest_msr_rw(vmx, MSR_GSBASE) ||
1082 	    guest_msr_rw(vmx, MSR_FSBASE) ||
1083 	    guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
1084 	    guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
1085 	    guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
1086 	    guest_msr_rw(vmx, MSR_EFER) ||
1087 	    guest_msr_ro(vmx, MSR_TSC) ||
1088 	    ((cap_rdpid || cap_rdtscp) && guest_msr_ro(vmx, MSR_TSC_AUX)))
1089 		panic("vmx_init: error setting guest msr access");
1090 
1091 	if (virtual_interrupt_delivery) {
1092 		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
1093 		    APIC_ACCESS_ADDRESS);
1094 		/* XXX this should really return an error to the caller */
1095 		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
1096 	}
1097 
1098 	vmx->pmap = pmap;
1099 	return (vmx);
1100 }
1101 
1102 static void *
1103 vmx_vcpu_init(void *vmi, struct vcpu *vcpu1, int vcpuid)
1104 {
1105 	struct vmx *vmx = vmi;
1106 	struct vmcs *vmcs;
1107 	struct vmx_vcpu *vcpu;
1108 	uint32_t exc_bitmap;
1109 	uint16_t vpid;
1110 	int error;
1111 
1112 	vpid = vpid_alloc(vcpuid);
1113 
1114 	vcpu = malloc(sizeof(*vcpu), M_VMX, M_WAITOK | M_ZERO);
1115 	vcpu->vmx = vmx;
1116 	vcpu->vcpu = vcpu1;
1117 	vcpu->vcpuid = vcpuid;
1118 	vcpu->vmcs = malloc_aligned(sizeof(*vmcs), PAGE_SIZE, M_VMX,
1119 	    M_WAITOK | M_ZERO);
1120 	vcpu->apic_page = malloc_aligned(PAGE_SIZE, PAGE_SIZE, M_VMX,
1121 	    M_WAITOK | M_ZERO);
1122 	vcpu->pir_desc = malloc_aligned(sizeof(*vcpu->pir_desc), 64, M_VMX,
1123 	    M_WAITOK | M_ZERO);
1124 
1125 	vmcs = vcpu->vmcs;
1126 	vmcs->identifier = vmx_revision();
1127 	error = vmclear(vmcs);
1128 	if (error != 0) {
1129 		panic("vmx_init: vmclear error %d on vcpu %d\n",
1130 		    error, vcpuid);
1131 	}
1132 
1133 	vmx_msr_guest_init(vmx, vcpu);
1134 
1135 	error = vmcs_init(vmcs);
1136 	KASSERT(error == 0, ("vmcs_init error %d", error));
1137 
1138 	VMPTRLD(vmcs);
1139 	error = 0;
1140 	error += vmwrite(VMCS_HOST_RSP, (u_long)&vcpu->ctx);
1141 	error += vmwrite(VMCS_EPTP, vmx->eptp);
1142 	error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
1143 	error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
1144 	if (vcpu_trap_wbinvd(vcpu->vcpu)) {
1145 		KASSERT(cap_wbinvd_exit, ("WBINVD trap not available"));
1146 		procbased_ctls2 |= PROCBASED2_WBINVD_EXITING;
1147 	}
1148 	error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
1149 	error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
1150 	error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
1151 	error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
1152 	error += vmwrite(VMCS_VPID, vpid);
1153 
1154 	if (guest_l1d_flush && !guest_l1d_flush_sw) {
1155 		vmcs_write(VMCS_ENTRY_MSR_LOAD, pmap_kextract(
1156 			(vm_offset_t)&msr_load_list[0]));
1157 		vmcs_write(VMCS_ENTRY_MSR_LOAD_COUNT,
1158 		    nitems(msr_load_list));
1159 		vmcs_write(VMCS_EXIT_MSR_STORE, 0);
1160 		vmcs_write(VMCS_EXIT_MSR_STORE_COUNT, 0);
1161 	}
1162 
1163 	/* exception bitmap */
1164 	if (vcpu_trace_exceptions(vcpu->vcpu))
1165 		exc_bitmap = 0xffffffff;
1166 	else
1167 		exc_bitmap = 1 << IDT_MC;
1168 	error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
1169 
1170 	vcpu->ctx.guest_dr6 = DBREG_DR6_RESERVED1;
1171 	error += vmwrite(VMCS_GUEST_DR7, DBREG_DR7_RESERVED1);
1172 
1173 	if (tpr_shadowing) {
1174 		error += vmwrite(VMCS_VIRTUAL_APIC, vtophys(vcpu->apic_page));
1175 	}
1176 
1177 	if (virtual_interrupt_delivery) {
1178 		error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
1179 		error += vmwrite(VMCS_EOI_EXIT0, 0);
1180 		error += vmwrite(VMCS_EOI_EXIT1, 0);
1181 		error += vmwrite(VMCS_EOI_EXIT2, 0);
1182 		error += vmwrite(VMCS_EOI_EXIT3, 0);
1183 	}
1184 	if (posted_interrupts) {
1185 		error += vmwrite(VMCS_PIR_VECTOR, pirvec);
1186 		error += vmwrite(VMCS_PIR_DESC, vtophys(vcpu->pir_desc));
1187 	}
1188 	VMCLEAR(vmcs);
1189 	KASSERT(error == 0, ("vmx_init: error customizing the vmcs"));
1190 
1191 	vcpu->cap.set = 0;
1192 	vcpu->cap.set |= cap_rdpid != 0 ? 1 << VM_CAP_RDPID : 0;
1193 	vcpu->cap.set |= cap_rdtscp != 0 ? 1 << VM_CAP_RDTSCP : 0;
1194 	vcpu->cap.proc_ctls = procbased_ctls;
1195 	vcpu->cap.proc_ctls2 = procbased_ctls2;
1196 	vcpu->cap.exc_bitmap = exc_bitmap;
1197 
1198 	vcpu->state.nextrip = ~0;
1199 	vcpu->state.lastcpu = NOCPU;
1200 	vcpu->state.vpid = vpid;
1201 
1202 	/*
1203 	 * Set up the CR0/4 shadows, and init the read shadow
1204 	 * to the power-on register value from the Intel Sys Arch.
1205 	 *  CR0 - 0x60000010
1206 	 *  CR4 - 0
1207 	 */
1208 	error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
1209 	if (error != 0)
1210 		panic("vmx_setup_cr0_shadow %d", error);
1211 
1212 	error = vmx_setup_cr4_shadow(vmcs, 0);
1213 	if (error != 0)
1214 		panic("vmx_setup_cr4_shadow %d", error);
1215 
1216 	vcpu->ctx.pmap = vmx->pmap;
1217 
1218 	return (vcpu);
1219 }
1220 
1221 static int
1222 vmx_handle_cpuid(struct vmx_vcpu *vcpu, struct vmxctx *vmxctx)
1223 {
1224 	int handled;
1225 
1226 	handled = x86_emulate_cpuid(vcpu->vcpu, (uint64_t *)&vmxctx->guest_rax,
1227 	    (uint64_t *)&vmxctx->guest_rbx, (uint64_t *)&vmxctx->guest_rcx,
1228 	    (uint64_t *)&vmxctx->guest_rdx);
1229 	return (handled);
1230 }
1231 
1232 static __inline void
1233 vmx_run_trace(struct vmx_vcpu *vcpu)
1234 {
1235 	VMX_CTR1(vcpu, "Resume execution at %#lx", vmcs_guest_rip());
1236 }
1237 
1238 static __inline void
1239 vmx_exit_trace(struct vmx_vcpu *vcpu, uint64_t rip, uint32_t exit_reason,
1240     int handled)
1241 {
1242 	VMX_CTR3(vcpu, "%s %s vmexit at 0x%0lx",
1243 		 handled ? "handled" : "unhandled",
1244 		 exit_reason_to_str(exit_reason), rip);
1245 }
1246 
1247 static __inline void
1248 vmx_astpending_trace(struct vmx_vcpu *vcpu, uint64_t rip)
1249 {
1250 	VMX_CTR1(vcpu, "astpending vmexit at 0x%0lx", rip);
1251 }
1252 
1253 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1254 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1255 
1256 /*
1257  * Invalidate guest mappings identified by its vpid from the TLB.
1258  */
1259 static __inline void
1260 vmx_invvpid(struct vmx *vmx, struct vmx_vcpu *vcpu, pmap_t pmap, int running)
1261 {
1262 	struct vmxstate *vmxstate;
1263 	struct invvpid_desc invvpid_desc;
1264 
1265 	vmxstate = &vcpu->state;
1266 	if (vmxstate->vpid == 0)
1267 		return;
1268 
1269 	if (!running) {
1270 		/*
1271 		 * Set the 'lastcpu' to an invalid host cpu.
1272 		 *
1273 		 * This will invalidate TLB entries tagged with the vcpu's
1274 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
1275 		 */
1276 		vmxstate->lastcpu = NOCPU;
1277 		return;
1278 	}
1279 
1280 	KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1281 	    "critical section", __func__, vcpu->vcpuid));
1282 
1283 	/*
1284 	 * Invalidate all mappings tagged with 'vpid'
1285 	 *
1286 	 * We do this because this vcpu was executing on a different host
1287 	 * cpu when it last ran. We do not track whether it invalidated
1288 	 * mappings associated with its 'vpid' during that run. So we must
1289 	 * assume that the mappings associated with 'vpid' on 'curcpu' are
1290 	 * stale and invalidate them.
1291 	 *
1292 	 * Note that we incur this penalty only when the scheduler chooses to
1293 	 * move the thread associated with this vcpu between host cpus.
1294 	 *
1295 	 * Note also that this will invalidate mappings tagged with 'vpid'
1296 	 * for "all" EP4TAs.
1297 	 */
1298 	if (atomic_load_long(&pmap->pm_eptgen) == vmx->eptgen[curcpu]) {
1299 		invvpid_desc._res1 = 0;
1300 		invvpid_desc._res2 = 0;
1301 		invvpid_desc.vpid = vmxstate->vpid;
1302 		invvpid_desc.linear_addr = 0;
1303 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1304 		vmm_stat_incr(vcpu->vcpu, VCPU_INVVPID_DONE, 1);
1305 	} else {
1306 		/*
1307 		 * The invvpid can be skipped if an invept is going to
1308 		 * be performed before entering the guest. The invept
1309 		 * will invalidate combined mappings tagged with
1310 		 * 'vmx->eptp' for all vpids.
1311 		 */
1312 		vmm_stat_incr(vcpu->vcpu, VCPU_INVVPID_SAVED, 1);
1313 	}
1314 }
1315 
1316 static void
1317 vmx_set_pcpu_defaults(struct vmx *vmx, struct vmx_vcpu *vcpu, pmap_t pmap)
1318 {
1319 	struct vmxstate *vmxstate;
1320 
1321 	vmxstate = &vcpu->state;
1322 	if (vmxstate->lastcpu == curcpu)
1323 		return;
1324 
1325 	vmxstate->lastcpu = curcpu;
1326 
1327 	vmm_stat_incr(vcpu->vcpu, VCPU_MIGRATIONS, 1);
1328 
1329 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1330 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1331 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1332 	vmx_invvpid(vmx, vcpu, pmap, 1);
1333 }
1334 
1335 /*
1336  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1337  */
1338 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1339 
1340 static void __inline
1341 vmx_set_int_window_exiting(struct vmx_vcpu *vcpu)
1342 {
1343 
1344 	if ((vcpu->cap.proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1345 		vcpu->cap.proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1346 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1347 		VMX_CTR0(vcpu, "Enabling interrupt window exiting");
1348 	}
1349 }
1350 
1351 static void __inline
1352 vmx_clear_int_window_exiting(struct vmx_vcpu *vcpu)
1353 {
1354 
1355 	KASSERT((vcpu->cap.proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1356 	    ("intr_window_exiting not set: %#x", vcpu->cap.proc_ctls));
1357 	vcpu->cap.proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1358 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1359 	VMX_CTR0(vcpu, "Disabling interrupt window exiting");
1360 }
1361 
1362 static void __inline
1363 vmx_set_nmi_window_exiting(struct vmx_vcpu *vcpu)
1364 {
1365 
1366 	if ((vcpu->cap.proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1367 		vcpu->cap.proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1368 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1369 		VMX_CTR0(vcpu, "Enabling NMI window exiting");
1370 	}
1371 }
1372 
1373 static void __inline
1374 vmx_clear_nmi_window_exiting(struct vmx_vcpu *vcpu)
1375 {
1376 
1377 	KASSERT((vcpu->cap.proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1378 	    ("nmi_window_exiting not set %#x", vcpu->cap.proc_ctls));
1379 	vcpu->cap.proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1380 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1381 	VMX_CTR0(vcpu, "Disabling NMI window exiting");
1382 }
1383 
1384 int
1385 vmx_set_tsc_offset(struct vmx_vcpu *vcpu, uint64_t offset)
1386 {
1387 	int error;
1388 
1389 	if ((vcpu->cap.proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1390 		vcpu->cap.proc_ctls |= PROCBASED_TSC_OFFSET;
1391 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1392 		VMX_CTR0(vcpu, "Enabling TSC offsetting");
1393 	}
1394 
1395 	error = vmwrite(VMCS_TSC_OFFSET, offset);
1396 #ifdef BHYVE_SNAPSHOT
1397 	if (error == 0)
1398 		vm_set_tsc_offset(vcpu->vcpu, offset);
1399 #endif
1400 	return (error);
1401 }
1402 
1403 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1404 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1405 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1406 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1407 
1408 static void
1409 vmx_inject_nmi(struct vmx_vcpu *vcpu)
1410 {
1411 	uint32_t gi __diagused, info;
1412 
1413 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1414 	KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1415 	    "interruptibility-state %#x", gi));
1416 
1417 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1418 	KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1419 	    "VM-entry interruption information %#x", info));
1420 
1421 	/*
1422 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1423 	 * or the VMCS entry check will fail.
1424 	 */
1425 	info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1426 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1427 
1428 	VMX_CTR0(vcpu, "Injecting vNMI");
1429 
1430 	/* Clear the request */
1431 	vm_nmi_clear(vcpu->vcpu);
1432 }
1433 
1434 static void
1435 vmx_inject_interrupts(struct vmx_vcpu *vcpu, struct vlapic *vlapic,
1436     uint64_t guestrip)
1437 {
1438 	int vector, need_nmi_exiting, extint_pending;
1439 	uint64_t rflags, entryinfo;
1440 	uint32_t gi, info;
1441 
1442 	if (vcpu->cap.set & (1 << VM_CAP_MASK_HWINTR)) {
1443 		return;
1444 	}
1445 
1446 	if (vcpu->state.nextrip != guestrip) {
1447 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1448 		if (gi & HWINTR_BLOCKING) {
1449 			VMX_CTR2(vcpu, "Guest interrupt blocking "
1450 			    "cleared due to rip change: %#lx/%#lx",
1451 			    vcpu->state.nextrip, guestrip);
1452 			gi &= ~HWINTR_BLOCKING;
1453 			vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1454 		}
1455 	}
1456 
1457 	if (vm_entry_intinfo(vcpu->vcpu, &entryinfo)) {
1458 		KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1459 		    "intinfo is not valid: %#lx", __func__, entryinfo));
1460 
1461 		info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1462 		KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1463 		     "pending exception: %#lx/%#x", __func__, entryinfo, info));
1464 
1465 		info = entryinfo;
1466 		vector = info & 0xff;
1467 		if (vector == IDT_BP || vector == IDT_OF) {
1468 			/*
1469 			 * VT-x requires #BP and #OF to be injected as software
1470 			 * exceptions.
1471 			 */
1472 			info &= ~VMCS_INTR_T_MASK;
1473 			info |= VMCS_INTR_T_SWEXCEPTION;
1474 		}
1475 
1476 		if (info & VMCS_INTR_DEL_ERRCODE)
1477 			vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1478 
1479 		vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1480 	}
1481 
1482 	if (vm_nmi_pending(vcpu->vcpu)) {
1483 		/*
1484 		 * If there are no conditions blocking NMI injection then
1485 		 * inject it directly here otherwise enable "NMI window
1486 		 * exiting" to inject it as soon as we can.
1487 		 *
1488 		 * We also check for STI_BLOCKING because some implementations
1489 		 * don't allow NMI injection in this case. If we are running
1490 		 * on a processor that doesn't have this restriction it will
1491 		 * immediately exit and the NMI will be injected in the
1492 		 * "NMI window exiting" handler.
1493 		 */
1494 		need_nmi_exiting = 1;
1495 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1496 		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1497 			info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1498 			if ((info & VMCS_INTR_VALID) == 0) {
1499 				vmx_inject_nmi(vcpu);
1500 				need_nmi_exiting = 0;
1501 			} else {
1502 				VMX_CTR1(vcpu, "Cannot inject NMI "
1503 				    "due to VM-entry intr info %#x", info);
1504 			}
1505 		} else {
1506 			VMX_CTR1(vcpu, "Cannot inject NMI due to "
1507 			    "Guest Interruptibility-state %#x", gi);
1508 		}
1509 
1510 		if (need_nmi_exiting)
1511 			vmx_set_nmi_window_exiting(vcpu);
1512 	}
1513 
1514 	extint_pending = vm_extint_pending(vcpu->vcpu);
1515 
1516 	if (!extint_pending && virtual_interrupt_delivery) {
1517 		vmx_inject_pir(vlapic);
1518 		return;
1519 	}
1520 
1521 	/*
1522 	 * If interrupt-window exiting is already in effect then don't bother
1523 	 * checking for pending interrupts. This is just an optimization and
1524 	 * not needed for correctness.
1525 	 */
1526 	if ((vcpu->cap.proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1527 		VMX_CTR0(vcpu, "Skip interrupt injection due to "
1528 		    "pending int_window_exiting");
1529 		return;
1530 	}
1531 
1532 	if (!extint_pending) {
1533 		/* Ask the local apic for a vector to inject */
1534 		if (!vlapic_pending_intr(vlapic, &vector))
1535 			return;
1536 
1537 		/*
1538 		 * From the Intel SDM, Volume 3, Section "Maskable
1539 		 * Hardware Interrupts":
1540 		 * - maskable interrupt vectors [16,255] can be delivered
1541 		 *   through the local APIC.
1542 		*/
1543 		KASSERT(vector >= 16 && vector <= 255,
1544 		    ("invalid vector %d from local APIC", vector));
1545 	} else {
1546 		/* Ask the legacy pic for a vector to inject */
1547 		vatpic_pending_intr(vcpu->vmx->vm, &vector);
1548 
1549 		/*
1550 		 * From the Intel SDM, Volume 3, Section "Maskable
1551 		 * Hardware Interrupts":
1552 		 * - maskable interrupt vectors [0,255] can be delivered
1553 		 *   through the INTR pin.
1554 		 */
1555 		KASSERT(vector >= 0 && vector <= 255,
1556 		    ("invalid vector %d from INTR", vector));
1557 	}
1558 
1559 	/* Check RFLAGS.IF and the interruptibility state of the guest */
1560 	rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1561 	if ((rflags & PSL_I) == 0) {
1562 		VMX_CTR2(vcpu, "Cannot inject vector %d due to "
1563 		    "rflags %#lx", vector, rflags);
1564 		goto cantinject;
1565 	}
1566 
1567 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1568 	if (gi & HWINTR_BLOCKING) {
1569 		VMX_CTR2(vcpu, "Cannot inject vector %d due to "
1570 		    "Guest Interruptibility-state %#x", vector, gi);
1571 		goto cantinject;
1572 	}
1573 
1574 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1575 	if (info & VMCS_INTR_VALID) {
1576 		/*
1577 		 * This is expected and could happen for multiple reasons:
1578 		 * - A vectoring VM-entry was aborted due to astpending
1579 		 * - A VM-exit happened during event injection.
1580 		 * - An exception was injected above.
1581 		 * - An NMI was injected above or after "NMI window exiting"
1582 		 */
1583 		VMX_CTR2(vcpu, "Cannot inject vector %d due to "
1584 		    "VM-entry intr info %#x", vector, info);
1585 		goto cantinject;
1586 	}
1587 
1588 	/* Inject the interrupt */
1589 	info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1590 	info |= vector;
1591 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1592 
1593 	if (!extint_pending) {
1594 		/* Update the Local APIC ISR */
1595 		vlapic_intr_accepted(vlapic, vector);
1596 	} else {
1597 		vm_extint_clear(vcpu->vcpu);
1598 		vatpic_intr_accepted(vcpu->vmx->vm, vector);
1599 
1600 		/*
1601 		 * After we accepted the current ExtINT the PIC may
1602 		 * have posted another one.  If that is the case, set
1603 		 * the Interrupt Window Exiting execution control so
1604 		 * we can inject that one too.
1605 		 *
1606 		 * Also, interrupt window exiting allows us to inject any
1607 		 * pending APIC vector that was preempted by the ExtINT
1608 		 * as soon as possible. This applies both for the software
1609 		 * emulated vlapic and the hardware assisted virtual APIC.
1610 		 */
1611 		vmx_set_int_window_exiting(vcpu);
1612 	}
1613 
1614 	VMX_CTR1(vcpu, "Injecting hwintr at vector %d", vector);
1615 
1616 	return;
1617 
1618 cantinject:
1619 	/*
1620 	 * Set the Interrupt Window Exiting execution control so we can inject
1621 	 * the interrupt as soon as blocking condition goes away.
1622 	 */
1623 	vmx_set_int_window_exiting(vcpu);
1624 }
1625 
1626 /*
1627  * If the Virtual NMIs execution control is '1' then the logical processor
1628  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1629  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1630  * virtual-NMI blocking.
1631  *
1632  * This unblocking occurs even if the IRET causes a fault. In this case the
1633  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1634  */
1635 static void
1636 vmx_restore_nmi_blocking(struct vmx_vcpu *vcpu)
1637 {
1638 	uint32_t gi;
1639 
1640 	VMX_CTR0(vcpu, "Restore Virtual-NMI blocking");
1641 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1642 	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1643 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1644 }
1645 
1646 static void
1647 vmx_clear_nmi_blocking(struct vmx_vcpu *vcpu)
1648 {
1649 	uint32_t gi;
1650 
1651 	VMX_CTR0(vcpu, "Clear Virtual-NMI blocking");
1652 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1653 	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1654 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1655 }
1656 
1657 static void
1658 vmx_assert_nmi_blocking(struct vmx_vcpu *vcpu)
1659 {
1660 	uint32_t gi __diagused;
1661 
1662 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1663 	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1664 	    ("NMI blocking is not in effect %#x", gi));
1665 }
1666 
1667 static int
1668 vmx_emulate_xsetbv(struct vmx *vmx, struct vmx_vcpu *vcpu,
1669     struct vm_exit *vmexit)
1670 {
1671 	struct vmxctx *vmxctx;
1672 	uint64_t xcrval;
1673 	const struct xsave_limits *limits;
1674 
1675 	vmxctx = &vcpu->ctx;
1676 	limits = vmm_get_xsave_limits();
1677 
1678 	/*
1679 	 * Note that the processor raises a GP# fault on its own if
1680 	 * xsetbv is executed for CPL != 0, so we do not have to
1681 	 * emulate that fault here.
1682 	 */
1683 
1684 	/* Only xcr0 is supported. */
1685 	if (vmxctx->guest_rcx != 0) {
1686 		vm_inject_gp(vcpu->vcpu);
1687 		return (HANDLED);
1688 	}
1689 
1690 	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1691 	if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1692 		vm_inject_ud(vcpu->vcpu);
1693 		return (HANDLED);
1694 	}
1695 
1696 	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1697 	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1698 		vm_inject_gp(vcpu->vcpu);
1699 		return (HANDLED);
1700 	}
1701 
1702 	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1703 		vm_inject_gp(vcpu->vcpu);
1704 		return (HANDLED);
1705 	}
1706 
1707 	/* AVX (YMM_Hi128) requires SSE. */
1708 	if (xcrval & XFEATURE_ENABLED_AVX &&
1709 	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1710 		vm_inject_gp(vcpu->vcpu);
1711 		return (HANDLED);
1712 	}
1713 
1714 	/*
1715 	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1716 	 * ZMM_Hi256, and Hi16_ZMM.
1717 	 */
1718 	if (xcrval & XFEATURE_AVX512 &&
1719 	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1720 	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1721 		vm_inject_gp(vcpu->vcpu);
1722 		return (HANDLED);
1723 	}
1724 
1725 	/*
1726 	 * Intel MPX requires both bound register state flags to be
1727 	 * set.
1728 	 */
1729 	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1730 	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1731 		vm_inject_gp(vcpu->vcpu);
1732 		return (HANDLED);
1733 	}
1734 
1735 	/*
1736 	 * This runs "inside" vmrun() with the guest's FPU state, so
1737 	 * modifying xcr0 directly modifies the guest's xcr0, not the
1738 	 * host's.
1739 	 */
1740 	load_xcr(0, xcrval);
1741 	return (HANDLED);
1742 }
1743 
1744 static uint64_t
1745 vmx_get_guest_reg(struct vmx_vcpu *vcpu, int ident)
1746 {
1747 	const struct vmxctx *vmxctx;
1748 
1749 	vmxctx = &vcpu->ctx;
1750 
1751 	switch (ident) {
1752 	case 0:
1753 		return (vmxctx->guest_rax);
1754 	case 1:
1755 		return (vmxctx->guest_rcx);
1756 	case 2:
1757 		return (vmxctx->guest_rdx);
1758 	case 3:
1759 		return (vmxctx->guest_rbx);
1760 	case 4:
1761 		return (vmcs_read(VMCS_GUEST_RSP));
1762 	case 5:
1763 		return (vmxctx->guest_rbp);
1764 	case 6:
1765 		return (vmxctx->guest_rsi);
1766 	case 7:
1767 		return (vmxctx->guest_rdi);
1768 	case 8:
1769 		return (vmxctx->guest_r8);
1770 	case 9:
1771 		return (vmxctx->guest_r9);
1772 	case 10:
1773 		return (vmxctx->guest_r10);
1774 	case 11:
1775 		return (vmxctx->guest_r11);
1776 	case 12:
1777 		return (vmxctx->guest_r12);
1778 	case 13:
1779 		return (vmxctx->guest_r13);
1780 	case 14:
1781 		return (vmxctx->guest_r14);
1782 	case 15:
1783 		return (vmxctx->guest_r15);
1784 	default:
1785 		panic("invalid vmx register %d", ident);
1786 	}
1787 }
1788 
1789 static void
1790 vmx_set_guest_reg(struct vmx_vcpu *vcpu, int ident, uint64_t regval)
1791 {
1792 	struct vmxctx *vmxctx;
1793 
1794 	vmxctx = &vcpu->ctx;
1795 
1796 	switch (ident) {
1797 	case 0:
1798 		vmxctx->guest_rax = regval;
1799 		break;
1800 	case 1:
1801 		vmxctx->guest_rcx = regval;
1802 		break;
1803 	case 2:
1804 		vmxctx->guest_rdx = regval;
1805 		break;
1806 	case 3:
1807 		vmxctx->guest_rbx = regval;
1808 		break;
1809 	case 4:
1810 		vmcs_write(VMCS_GUEST_RSP, regval);
1811 		break;
1812 	case 5:
1813 		vmxctx->guest_rbp = regval;
1814 		break;
1815 	case 6:
1816 		vmxctx->guest_rsi = regval;
1817 		break;
1818 	case 7:
1819 		vmxctx->guest_rdi = regval;
1820 		break;
1821 	case 8:
1822 		vmxctx->guest_r8 = regval;
1823 		break;
1824 	case 9:
1825 		vmxctx->guest_r9 = regval;
1826 		break;
1827 	case 10:
1828 		vmxctx->guest_r10 = regval;
1829 		break;
1830 	case 11:
1831 		vmxctx->guest_r11 = regval;
1832 		break;
1833 	case 12:
1834 		vmxctx->guest_r12 = regval;
1835 		break;
1836 	case 13:
1837 		vmxctx->guest_r13 = regval;
1838 		break;
1839 	case 14:
1840 		vmxctx->guest_r14 = regval;
1841 		break;
1842 	case 15:
1843 		vmxctx->guest_r15 = regval;
1844 		break;
1845 	default:
1846 		panic("invalid vmx register %d", ident);
1847 	}
1848 }
1849 
1850 static int
1851 vmx_emulate_cr0_access(struct vmx_vcpu *vcpu, uint64_t exitqual)
1852 {
1853 	uint64_t crval, regval;
1854 
1855 	/* We only handle mov to %cr0 at this time */
1856 	if ((exitqual & 0xf0) != 0x00)
1857 		return (UNHANDLED);
1858 
1859 	regval = vmx_get_guest_reg(vcpu, (exitqual >> 8) & 0xf);
1860 
1861 	vmcs_write(VMCS_CR0_SHADOW, regval);
1862 
1863 	crval = regval | cr0_ones_mask;
1864 	crval &= ~cr0_zeros_mask;
1865 	vmcs_write(VMCS_GUEST_CR0, crval);
1866 
1867 	if (regval & CR0_PG) {
1868 		uint64_t efer, entry_ctls;
1869 
1870 		/*
1871 		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1872 		 * the "IA-32e mode guest" bit in VM-entry control must be
1873 		 * equal.
1874 		 */
1875 		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1876 		if (efer & EFER_LME) {
1877 			efer |= EFER_LMA;
1878 			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1879 			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1880 			entry_ctls |= VM_ENTRY_GUEST_LMA;
1881 			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1882 		}
1883 	}
1884 
1885 	return (HANDLED);
1886 }
1887 
1888 static int
1889 vmx_emulate_cr4_access(struct vmx_vcpu *vcpu, uint64_t exitqual)
1890 {
1891 	uint64_t crval, regval;
1892 
1893 	/* We only handle mov to %cr4 at this time */
1894 	if ((exitqual & 0xf0) != 0x00)
1895 		return (UNHANDLED);
1896 
1897 	regval = vmx_get_guest_reg(vcpu, (exitqual >> 8) & 0xf);
1898 
1899 	vmcs_write(VMCS_CR4_SHADOW, regval);
1900 
1901 	crval = regval | cr4_ones_mask;
1902 	crval &= ~cr4_zeros_mask;
1903 	vmcs_write(VMCS_GUEST_CR4, crval);
1904 
1905 	return (HANDLED);
1906 }
1907 
1908 static int
1909 vmx_emulate_cr8_access(struct vmx *vmx, struct vmx_vcpu *vcpu,
1910     uint64_t exitqual)
1911 {
1912 	struct vlapic *vlapic;
1913 	uint64_t cr8;
1914 	int regnum;
1915 
1916 	/* We only handle mov %cr8 to/from a register at this time. */
1917 	if ((exitqual & 0xe0) != 0x00) {
1918 		return (UNHANDLED);
1919 	}
1920 
1921 	vlapic = vm_lapic(vcpu->vcpu);
1922 	regnum = (exitqual >> 8) & 0xf;
1923 	if (exitqual & 0x10) {
1924 		cr8 = vlapic_get_cr8(vlapic);
1925 		vmx_set_guest_reg(vcpu, regnum, cr8);
1926 	} else {
1927 		cr8 = vmx_get_guest_reg(vcpu, regnum);
1928 		vlapic_set_cr8(vlapic, cr8);
1929 	}
1930 
1931 	return (HANDLED);
1932 }
1933 
1934 /*
1935  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1936  */
1937 static int
1938 vmx_cpl(void)
1939 {
1940 	uint32_t ssar;
1941 
1942 	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1943 	return ((ssar >> 5) & 0x3);
1944 }
1945 
1946 static enum vm_cpu_mode
1947 vmx_cpu_mode(void)
1948 {
1949 	uint32_t csar;
1950 
1951 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1952 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1953 		if (csar & 0x2000)
1954 			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1955 		else
1956 			return (CPU_MODE_COMPATIBILITY);
1957 	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1958 		return (CPU_MODE_PROTECTED);
1959 	} else {
1960 		return (CPU_MODE_REAL);
1961 	}
1962 }
1963 
1964 static enum vm_paging_mode
1965 vmx_paging_mode(void)
1966 {
1967 	uint64_t cr4;
1968 
1969 	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1970 		return (PAGING_MODE_FLAT);
1971 	cr4 = vmcs_read(VMCS_GUEST_CR4);
1972 	if (!(cr4 & CR4_PAE))
1973 		return (PAGING_MODE_32);
1974 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME) {
1975 		if (!(cr4 & CR4_LA57))
1976 			return (PAGING_MODE_64);
1977 		return (PAGING_MODE_64_LA57);
1978 	} else
1979 		return (PAGING_MODE_PAE);
1980 }
1981 
1982 static uint64_t
1983 inout_str_index(struct vmx_vcpu *vcpu, int in)
1984 {
1985 	uint64_t val;
1986 	int error __diagused;
1987 	enum vm_reg_name reg;
1988 
1989 	reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1990 	error = vmx_getreg(vcpu, reg, &val);
1991 	KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1992 	return (val);
1993 }
1994 
1995 static uint64_t
1996 inout_str_count(struct vmx_vcpu *vcpu, int rep)
1997 {
1998 	uint64_t val;
1999 	int error __diagused;
2000 
2001 	if (rep) {
2002 		error = vmx_getreg(vcpu, VM_REG_GUEST_RCX, &val);
2003 		KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
2004 	} else {
2005 		val = 1;
2006 	}
2007 	return (val);
2008 }
2009 
2010 static int
2011 inout_str_addrsize(uint32_t inst_info)
2012 {
2013 	uint32_t size;
2014 
2015 	size = (inst_info >> 7) & 0x7;
2016 	switch (size) {
2017 	case 0:
2018 		return (2);	/* 16 bit */
2019 	case 1:
2020 		return (4);	/* 32 bit */
2021 	case 2:
2022 		return (8);	/* 64 bit */
2023 	default:
2024 		panic("%s: invalid size encoding %d", __func__, size);
2025 	}
2026 }
2027 
2028 static void
2029 inout_str_seginfo(struct vmx_vcpu *vcpu, uint32_t inst_info, int in,
2030     struct vm_inout_str *vis)
2031 {
2032 	int error __diagused, s;
2033 
2034 	if (in) {
2035 		vis->seg_name = VM_REG_GUEST_ES;
2036 	} else {
2037 		s = (inst_info >> 15) & 0x7;
2038 		vis->seg_name = vm_segment_name(s);
2039 	}
2040 
2041 	error = vmx_getdesc(vcpu, vis->seg_name, &vis->seg_desc);
2042 	KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
2043 }
2044 
2045 static void
2046 vmx_paging_info(struct vm_guest_paging *paging)
2047 {
2048 	paging->cr3 = vmcs_guest_cr3();
2049 	paging->cpl = vmx_cpl();
2050 	paging->cpu_mode = vmx_cpu_mode();
2051 	paging->paging_mode = vmx_paging_mode();
2052 }
2053 
2054 static void
2055 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
2056 {
2057 	struct vm_guest_paging *paging;
2058 	uint32_t csar;
2059 
2060 	paging = &vmexit->u.inst_emul.paging;
2061 
2062 	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
2063 	vmexit->inst_length = 0;
2064 	vmexit->u.inst_emul.gpa = gpa;
2065 	vmexit->u.inst_emul.gla = gla;
2066 	vmx_paging_info(paging);
2067 	switch (paging->cpu_mode) {
2068 	case CPU_MODE_REAL:
2069 		vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
2070 		vmexit->u.inst_emul.cs_d = 0;
2071 		break;
2072 	case CPU_MODE_PROTECTED:
2073 	case CPU_MODE_COMPATIBILITY:
2074 		vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
2075 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
2076 		vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
2077 		break;
2078 	default:
2079 		vmexit->u.inst_emul.cs_base = 0;
2080 		vmexit->u.inst_emul.cs_d = 0;
2081 		break;
2082 	}
2083 	vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
2084 }
2085 
2086 static int
2087 ept_fault_type(uint64_t ept_qual)
2088 {
2089 	int fault_type;
2090 
2091 	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
2092 		fault_type = VM_PROT_WRITE;
2093 	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
2094 		fault_type = VM_PROT_EXECUTE;
2095 	else
2096 		fault_type= VM_PROT_READ;
2097 
2098 	return (fault_type);
2099 }
2100 
2101 static bool
2102 ept_emulation_fault(uint64_t ept_qual)
2103 {
2104 	int read, write;
2105 
2106 	/* EPT fault on an instruction fetch doesn't make sense here */
2107 	if (ept_qual & EPT_VIOLATION_INST_FETCH)
2108 		return (false);
2109 
2110 	/* EPT fault must be a read fault or a write fault */
2111 	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
2112 	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
2113 	if ((read | write) == 0)
2114 		return (false);
2115 
2116 	/*
2117 	 * The EPT violation must have been caused by accessing a
2118 	 * guest-physical address that is a translation of a guest-linear
2119 	 * address.
2120 	 */
2121 	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
2122 	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
2123 		return (false);
2124 	}
2125 
2126 	return (true);
2127 }
2128 
2129 static __inline int
2130 apic_access_virtualization(struct vmx_vcpu *vcpu)
2131 {
2132 	uint32_t proc_ctls2;
2133 
2134 	proc_ctls2 = vcpu->cap.proc_ctls2;
2135 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
2136 }
2137 
2138 static __inline int
2139 x2apic_virtualization(struct vmx_vcpu *vcpu)
2140 {
2141 	uint32_t proc_ctls2;
2142 
2143 	proc_ctls2 = vcpu->cap.proc_ctls2;
2144 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
2145 }
2146 
2147 static int
2148 vmx_handle_apic_write(struct vmx_vcpu *vcpu, struct vlapic *vlapic,
2149     uint64_t qual)
2150 {
2151 	int error, handled, offset;
2152 	uint32_t *apic_regs, vector;
2153 	bool retu;
2154 
2155 	handled = HANDLED;
2156 	offset = APIC_WRITE_OFFSET(qual);
2157 
2158 	if (!apic_access_virtualization(vcpu)) {
2159 		/*
2160 		 * In general there should not be any APIC write VM-exits
2161 		 * unless APIC-access virtualization is enabled.
2162 		 *
2163 		 * However self-IPI virtualization can legitimately trigger
2164 		 * an APIC-write VM-exit so treat it specially.
2165 		 */
2166 		if (x2apic_virtualization(vcpu) &&
2167 		    offset == APIC_OFFSET_SELF_IPI) {
2168 			apic_regs = (uint32_t *)(vlapic->apic_page);
2169 			vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
2170 			vlapic_self_ipi_handler(vlapic, vector);
2171 			return (HANDLED);
2172 		} else
2173 			return (UNHANDLED);
2174 	}
2175 
2176 	switch (offset) {
2177 	case APIC_OFFSET_ID:
2178 		vlapic_id_write_handler(vlapic);
2179 		break;
2180 	case APIC_OFFSET_LDR:
2181 		vlapic_ldr_write_handler(vlapic);
2182 		break;
2183 	case APIC_OFFSET_DFR:
2184 		vlapic_dfr_write_handler(vlapic);
2185 		break;
2186 	case APIC_OFFSET_SVR:
2187 		vlapic_svr_write_handler(vlapic);
2188 		break;
2189 	case APIC_OFFSET_ESR:
2190 		vlapic_esr_write_handler(vlapic);
2191 		break;
2192 	case APIC_OFFSET_ICR_LOW:
2193 		retu = false;
2194 		error = vlapic_icrlo_write_handler(vlapic, &retu);
2195 		if (error != 0 || retu)
2196 			handled = UNHANDLED;
2197 		break;
2198 	case APIC_OFFSET_CMCI_LVT:
2199 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
2200 		vlapic_lvt_write_handler(vlapic, offset);
2201 		break;
2202 	case APIC_OFFSET_TIMER_ICR:
2203 		vlapic_icrtmr_write_handler(vlapic);
2204 		break;
2205 	case APIC_OFFSET_TIMER_DCR:
2206 		vlapic_dcr_write_handler(vlapic);
2207 		break;
2208 	default:
2209 		handled = UNHANDLED;
2210 		break;
2211 	}
2212 	return (handled);
2213 }
2214 
2215 static bool
2216 apic_access_fault(struct vmx_vcpu *vcpu, uint64_t gpa)
2217 {
2218 
2219 	if (apic_access_virtualization(vcpu) &&
2220 	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
2221 		return (true);
2222 	else
2223 		return (false);
2224 }
2225 
2226 static int
2227 vmx_handle_apic_access(struct vmx_vcpu *vcpu, struct vm_exit *vmexit)
2228 {
2229 	uint64_t qual;
2230 	int access_type, offset, allowed;
2231 
2232 	if (!apic_access_virtualization(vcpu))
2233 		return (UNHANDLED);
2234 
2235 	qual = vmexit->u.vmx.exit_qualification;
2236 	access_type = APIC_ACCESS_TYPE(qual);
2237 	offset = APIC_ACCESS_OFFSET(qual);
2238 
2239 	allowed = 0;
2240 	if (access_type == 0) {
2241 		/*
2242 		 * Read data access to the following registers is expected.
2243 		 */
2244 		switch (offset) {
2245 		case APIC_OFFSET_APR:
2246 		case APIC_OFFSET_PPR:
2247 		case APIC_OFFSET_RRR:
2248 		case APIC_OFFSET_CMCI_LVT:
2249 		case APIC_OFFSET_TIMER_CCR:
2250 			allowed = 1;
2251 			break;
2252 		default:
2253 			break;
2254 		}
2255 	} else if (access_type == 1) {
2256 		/*
2257 		 * Write data access to the following registers is expected.
2258 		 */
2259 		switch (offset) {
2260 		case APIC_OFFSET_VER:
2261 		case APIC_OFFSET_APR:
2262 		case APIC_OFFSET_PPR:
2263 		case APIC_OFFSET_RRR:
2264 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2265 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2266 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2267 		case APIC_OFFSET_CMCI_LVT:
2268 		case APIC_OFFSET_TIMER_CCR:
2269 			allowed = 1;
2270 			break;
2271 		default:
2272 			break;
2273 		}
2274 	}
2275 
2276 	if (allowed) {
2277 		vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2278 		    VIE_INVALID_GLA);
2279 	}
2280 
2281 	/*
2282 	 * Regardless of whether the APIC-access is allowed this handler
2283 	 * always returns UNHANDLED:
2284 	 * - if the access is allowed then it is handled by emulating the
2285 	 *   instruction that caused the VM-exit (outside the critical section)
2286 	 * - if the access is not allowed then it will be converted to an
2287 	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2288 	 */
2289 	return (UNHANDLED);
2290 }
2291 
2292 static enum task_switch_reason
2293 vmx_task_switch_reason(uint64_t qual)
2294 {
2295 	int reason;
2296 
2297 	reason = (qual >> 30) & 0x3;
2298 	switch (reason) {
2299 	case 0:
2300 		return (TSR_CALL);
2301 	case 1:
2302 		return (TSR_IRET);
2303 	case 2:
2304 		return (TSR_JMP);
2305 	case 3:
2306 		return (TSR_IDT_GATE);
2307 	default:
2308 		panic("%s: invalid reason %d", __func__, reason);
2309 	}
2310 }
2311 
2312 static int
2313 emulate_wrmsr(struct vmx_vcpu *vcpu, u_int num, uint64_t val, bool *retu)
2314 {
2315 	int error;
2316 
2317 	if (lapic_msr(num))
2318 		error = lapic_wrmsr(vcpu->vcpu, num, val, retu);
2319 	else
2320 		error = vmx_wrmsr(vcpu, num, val, retu);
2321 
2322 	return (error);
2323 }
2324 
2325 static int
2326 emulate_rdmsr(struct vmx_vcpu *vcpu, u_int num, bool *retu)
2327 {
2328 	struct vmxctx *vmxctx;
2329 	uint64_t result;
2330 	uint32_t eax, edx;
2331 	int error;
2332 
2333 	if (lapic_msr(num))
2334 		error = lapic_rdmsr(vcpu->vcpu, num, &result, retu);
2335 	else
2336 		error = vmx_rdmsr(vcpu, num, &result, retu);
2337 
2338 	if (error == 0) {
2339 		eax = result;
2340 		vmxctx = &vcpu->ctx;
2341 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2342 		KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2343 
2344 		edx = result >> 32;
2345 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2346 		KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2347 	}
2348 
2349 	return (error);
2350 }
2351 
2352 static int
2353 vmx_exit_process(struct vmx *vmx, struct vmx_vcpu *vcpu, struct vm_exit *vmexit)
2354 {
2355 	int error, errcode, errcode_valid, handled, in;
2356 	struct vmxctx *vmxctx;
2357 	struct vlapic *vlapic;
2358 	struct vm_inout_str *vis;
2359 	struct vm_task_switch *ts;
2360 	uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2361 	uint32_t intr_type, intr_vec, reason;
2362 	uint64_t exitintinfo, qual, gpa;
2363 #ifdef KDTRACE_HOOKS
2364 	int vcpuid;
2365 #endif
2366 	bool retu;
2367 
2368 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2369 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2370 
2371 	handled = UNHANDLED;
2372 	vmxctx = &vcpu->ctx;
2373 #ifdef KDTRACE_HOOKS
2374 	vcpuid = vcpu->vcpuid;
2375 #endif
2376 
2377 	qual = vmexit->u.vmx.exit_qualification;
2378 	reason = vmexit->u.vmx.exit_reason;
2379 	vmexit->exitcode = VM_EXITCODE_BOGUS;
2380 
2381 	vmm_stat_incr(vcpu->vcpu, VMEXIT_COUNT, 1);
2382 	SDT_PROBE3(vmm, vmx, exit, entry, vmx, vcpuid, vmexit);
2383 
2384 	/*
2385 	 * VM-entry failures during or after loading guest state.
2386 	 *
2387 	 * These VM-exits are uncommon but must be handled specially
2388 	 * as most VM-exit fields are not populated as usual.
2389 	 */
2390 	if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2391 		VMX_CTR0(vcpu, "Handling MCE during VM-entry");
2392 		__asm __volatile("int $18");
2393 		return (1);
2394 	}
2395 
2396 	/*
2397 	 * VM exits that can be triggered during event delivery need to
2398 	 * be handled specially by re-injecting the event if the IDT
2399 	 * vectoring information field's valid bit is set.
2400 	 *
2401 	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2402 	 * for details.
2403 	 */
2404 	idtvec_info = vmcs_idt_vectoring_info();
2405 	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2406 		idtvec_info &= ~(1 << 12); /* clear undefined bit */
2407 		exitintinfo = idtvec_info;
2408 		if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2409 			idtvec_err = vmcs_idt_vectoring_err();
2410 			exitintinfo |= (uint64_t)idtvec_err << 32;
2411 		}
2412 		error = vm_exit_intinfo(vcpu->vcpu, exitintinfo);
2413 		KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2414 		    __func__, error));
2415 
2416 		/*
2417 		 * If 'virtual NMIs' are being used and the VM-exit
2418 		 * happened while injecting an NMI during the previous
2419 		 * VM-entry, then clear "blocking by NMI" in the
2420 		 * Guest Interruptibility-State so the NMI can be
2421 		 * reinjected on the subsequent VM-entry.
2422 		 *
2423 		 * However, if the NMI was being delivered through a task
2424 		 * gate, then the new task must start execution with NMIs
2425 		 * blocked so don't clear NMI blocking in this case.
2426 		 */
2427 		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2428 		if (intr_type == VMCS_INTR_T_NMI) {
2429 			if (reason != EXIT_REASON_TASK_SWITCH)
2430 				vmx_clear_nmi_blocking(vcpu);
2431 			else
2432 				vmx_assert_nmi_blocking(vcpu);
2433 		}
2434 
2435 		/*
2436 		 * Update VM-entry instruction length if the event being
2437 		 * delivered was a software interrupt or software exception.
2438 		 */
2439 		if (intr_type == VMCS_INTR_T_SWINTR ||
2440 		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2441 		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2442 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2443 		}
2444 	}
2445 
2446 	switch (reason) {
2447 	case EXIT_REASON_TASK_SWITCH:
2448 		ts = &vmexit->u.task_switch;
2449 		ts->tsssel = qual & 0xffff;
2450 		ts->reason = vmx_task_switch_reason(qual);
2451 		ts->ext = 0;
2452 		ts->errcode_valid = 0;
2453 		vmx_paging_info(&ts->paging);
2454 		/*
2455 		 * If the task switch was due to a CALL, JMP, IRET, software
2456 		 * interrupt (INT n) or software exception (INT3, INTO),
2457 		 * then the saved %rip references the instruction that caused
2458 		 * the task switch. The instruction length field in the VMCS
2459 		 * is valid in this case.
2460 		 *
2461 		 * In all other cases (e.g., NMI, hardware exception) the
2462 		 * saved %rip is one that would have been saved in the old TSS
2463 		 * had the task switch completed normally so the instruction
2464 		 * length field is not needed in this case and is explicitly
2465 		 * set to 0.
2466 		 */
2467 		if (ts->reason == TSR_IDT_GATE) {
2468 			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2469 			    ("invalid idtvec_info %#x for IDT task switch",
2470 			    idtvec_info));
2471 			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2472 			if (intr_type != VMCS_INTR_T_SWINTR &&
2473 			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2474 			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2475 				/* Task switch triggered by external event */
2476 				ts->ext = 1;
2477 				vmexit->inst_length = 0;
2478 				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2479 					ts->errcode_valid = 1;
2480 					ts->errcode = vmcs_idt_vectoring_err();
2481 				}
2482 			}
2483 		}
2484 		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2485 		SDT_PROBE4(vmm, vmx, exit, taskswitch, vmx, vcpuid, vmexit, ts);
2486 		VMX_CTR4(vcpu, "task switch reason %d, tss 0x%04x, "
2487 		    "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2488 		    ts->ext ? "external" : "internal",
2489 		    ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2490 		break;
2491 	case EXIT_REASON_CR_ACCESS:
2492 		vmm_stat_incr(vcpu->vcpu, VMEXIT_CR_ACCESS, 1);
2493 		SDT_PROBE4(vmm, vmx, exit, craccess, vmx, vcpuid, vmexit, qual);
2494 		switch (qual & 0xf) {
2495 		case 0:
2496 			handled = vmx_emulate_cr0_access(vcpu, qual);
2497 			break;
2498 		case 4:
2499 			handled = vmx_emulate_cr4_access(vcpu, qual);
2500 			break;
2501 		case 8:
2502 			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2503 			break;
2504 		}
2505 		break;
2506 	case EXIT_REASON_RDMSR:
2507 		vmm_stat_incr(vcpu->vcpu, VMEXIT_RDMSR, 1);
2508 		retu = false;
2509 		ecx = vmxctx->guest_rcx;
2510 		VMX_CTR1(vcpu, "rdmsr 0x%08x", ecx);
2511 		SDT_PROBE4(vmm, vmx, exit, rdmsr, vmx, vcpuid, vmexit, ecx);
2512 		error = emulate_rdmsr(vcpu, ecx, &retu);
2513 		if (error) {
2514 			vmexit->exitcode = VM_EXITCODE_RDMSR;
2515 			vmexit->u.msr.code = ecx;
2516 		} else if (!retu) {
2517 			handled = HANDLED;
2518 		} else {
2519 			/* Return to userspace with a valid exitcode */
2520 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2521 			    ("emulate_rdmsr retu with bogus exitcode"));
2522 		}
2523 		break;
2524 	case EXIT_REASON_WRMSR:
2525 		vmm_stat_incr(vcpu->vcpu, VMEXIT_WRMSR, 1);
2526 		retu = false;
2527 		eax = vmxctx->guest_rax;
2528 		ecx = vmxctx->guest_rcx;
2529 		edx = vmxctx->guest_rdx;
2530 		VMX_CTR2(vcpu, "wrmsr 0x%08x value 0x%016lx",
2531 		    ecx, (uint64_t)edx << 32 | eax);
2532 		SDT_PROBE5(vmm, vmx, exit, wrmsr, vmx, vmexit, vcpuid, ecx,
2533 		    (uint64_t)edx << 32 | eax);
2534 		error = emulate_wrmsr(vcpu, ecx, (uint64_t)edx << 32 | eax,
2535 		    &retu);
2536 		if (error) {
2537 			vmexit->exitcode = VM_EXITCODE_WRMSR;
2538 			vmexit->u.msr.code = ecx;
2539 			vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2540 		} else if (!retu) {
2541 			handled = HANDLED;
2542 		} else {
2543 			/* Return to userspace with a valid exitcode */
2544 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2545 			    ("emulate_wrmsr retu with bogus exitcode"));
2546 		}
2547 		break;
2548 	case EXIT_REASON_HLT:
2549 		vmm_stat_incr(vcpu->vcpu, VMEXIT_HLT, 1);
2550 		SDT_PROBE3(vmm, vmx, exit, halt, vmx, vcpuid, vmexit);
2551 		vmexit->exitcode = VM_EXITCODE_HLT;
2552 		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2553 		if (virtual_interrupt_delivery)
2554 			vmexit->u.hlt.intr_status =
2555 			    vmcs_read(VMCS_GUEST_INTR_STATUS);
2556 		else
2557 			vmexit->u.hlt.intr_status = 0;
2558 		break;
2559 	case EXIT_REASON_MTF:
2560 		vmm_stat_incr(vcpu->vcpu, VMEXIT_MTRAP, 1);
2561 		SDT_PROBE3(vmm, vmx, exit, mtrap, vmx, vcpuid, vmexit);
2562 		vmexit->exitcode = VM_EXITCODE_MTRAP;
2563 		vmexit->inst_length = 0;
2564 		break;
2565 	case EXIT_REASON_PAUSE:
2566 		vmm_stat_incr(vcpu->vcpu, VMEXIT_PAUSE, 1);
2567 		SDT_PROBE3(vmm, vmx, exit, pause, vmx, vcpuid, vmexit);
2568 		vmexit->exitcode = VM_EXITCODE_PAUSE;
2569 		break;
2570 	case EXIT_REASON_INTR_WINDOW:
2571 		vmm_stat_incr(vcpu->vcpu, VMEXIT_INTR_WINDOW, 1);
2572 		SDT_PROBE3(vmm, vmx, exit, intrwindow, vmx, vcpuid, vmexit);
2573 		vmx_clear_int_window_exiting(vcpu);
2574 		return (1);
2575 	case EXIT_REASON_EXT_INTR:
2576 		/*
2577 		 * External interrupts serve only to cause VM exits and allow
2578 		 * the host interrupt handler to run.
2579 		 *
2580 		 * If this external interrupt triggers a virtual interrupt
2581 		 * to a VM, then that state will be recorded by the
2582 		 * host interrupt handler in the VM's softc. We will inject
2583 		 * this virtual interrupt during the subsequent VM enter.
2584 		 */
2585 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2586 		SDT_PROBE4(vmm, vmx, exit, interrupt,
2587 		    vmx, vcpuid, vmexit, intr_info);
2588 
2589 		/*
2590 		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2591 		 * This appears to be a bug in VMware Fusion?
2592 		 */
2593 		if (!(intr_info & VMCS_INTR_VALID))
2594 			return (1);
2595 		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2596 		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2597 		    ("VM exit interruption info invalid: %#x", intr_info));
2598 		vmx_trigger_hostintr(intr_info & 0xff);
2599 
2600 		/*
2601 		 * This is special. We want to treat this as an 'handled'
2602 		 * VM-exit but not increment the instruction pointer.
2603 		 */
2604 		vmm_stat_incr(vcpu->vcpu, VMEXIT_EXTINT, 1);
2605 		return (1);
2606 	case EXIT_REASON_NMI_WINDOW:
2607 		SDT_PROBE3(vmm, vmx, exit, nmiwindow, vmx, vcpuid, vmexit);
2608 		/* Exit to allow the pending virtual NMI to be injected */
2609 		if (vm_nmi_pending(vcpu->vcpu))
2610 			vmx_inject_nmi(vcpu);
2611 		vmx_clear_nmi_window_exiting(vcpu);
2612 		vmm_stat_incr(vcpu->vcpu, VMEXIT_NMI_WINDOW, 1);
2613 		return (1);
2614 	case EXIT_REASON_INOUT:
2615 		vmm_stat_incr(vcpu->vcpu, VMEXIT_INOUT, 1);
2616 		vmexit->exitcode = VM_EXITCODE_INOUT;
2617 		vmexit->u.inout.bytes = (qual & 0x7) + 1;
2618 		vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2619 		vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2620 		vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2621 		vmexit->u.inout.port = (uint16_t)(qual >> 16);
2622 		vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2623 		if (vmexit->u.inout.string) {
2624 			inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2625 			vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2626 			vis = &vmexit->u.inout_str;
2627 			vmx_paging_info(&vis->paging);
2628 			vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2629 			vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2630 			vis->index = inout_str_index(vcpu, in);
2631 			vis->count = inout_str_count(vcpu, vis->inout.rep);
2632 			vis->addrsize = inout_str_addrsize(inst_info);
2633 			inout_str_seginfo(vcpu, inst_info, in, vis);
2634 		}
2635 		SDT_PROBE3(vmm, vmx, exit, inout, vmx, vcpuid, vmexit);
2636 		break;
2637 	case EXIT_REASON_CPUID:
2638 		vmm_stat_incr(vcpu->vcpu, VMEXIT_CPUID, 1);
2639 		SDT_PROBE3(vmm, vmx, exit, cpuid, vmx, vcpuid, vmexit);
2640 		handled = vmx_handle_cpuid(vcpu, vmxctx);
2641 		break;
2642 	case EXIT_REASON_EXCEPTION:
2643 		vmm_stat_incr(vcpu->vcpu, VMEXIT_EXCEPTION, 1);
2644 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2645 		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2646 		    ("VM exit interruption info invalid: %#x", intr_info));
2647 
2648 		intr_vec = intr_info & 0xff;
2649 		intr_type = intr_info & VMCS_INTR_T_MASK;
2650 
2651 		/*
2652 		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2653 		 * fault encountered during the execution of IRET then we must
2654 		 * restore the state of "virtual-NMI blocking" before resuming
2655 		 * the guest.
2656 		 *
2657 		 * See "Resuming Guest Software after Handling an Exception".
2658 		 * See "Information for VM Exits Due to Vectored Events".
2659 		 */
2660 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2661 		    (intr_vec != IDT_DF) &&
2662 		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2663 			vmx_restore_nmi_blocking(vcpu);
2664 
2665 		/*
2666 		 * The NMI has already been handled in vmx_exit_handle_nmi().
2667 		 */
2668 		if (intr_type == VMCS_INTR_T_NMI)
2669 			return (1);
2670 
2671 		/*
2672 		 * Call the machine check handler by hand. Also don't reflect
2673 		 * the machine check back into the guest.
2674 		 */
2675 		if (intr_vec == IDT_MC) {
2676 			VMX_CTR0(vcpu, "Vectoring to MCE handler");
2677 			__asm __volatile("int $18");
2678 			return (1);
2679 		}
2680 
2681 		/*
2682 		 * If the hypervisor has requested user exits for
2683 		 * debug exceptions, bounce them out to userland.
2684 		 */
2685 		if (intr_type == VMCS_INTR_T_SWEXCEPTION && intr_vec == IDT_BP &&
2686 		    (vcpu->cap.set & (1 << VM_CAP_BPT_EXIT))) {
2687 			vmexit->exitcode = VM_EXITCODE_BPT;
2688 			vmexit->u.bpt.inst_length = vmexit->inst_length;
2689 			vmexit->inst_length = 0;
2690 			break;
2691 		}
2692 
2693 		if (intr_vec == IDT_PF) {
2694 			error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2695 			KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2696 			    __func__, error));
2697 		}
2698 
2699 		/*
2700 		 * Software exceptions exhibit trap-like behavior. This in
2701 		 * turn requires populating the VM-entry instruction length
2702 		 * so that the %rip in the trap frame is past the INT3/INTO
2703 		 * instruction.
2704 		 */
2705 		if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2706 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2707 
2708 		/* Reflect all other exceptions back into the guest */
2709 		errcode_valid = errcode = 0;
2710 		if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2711 			errcode_valid = 1;
2712 			errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2713 		}
2714 		VMX_CTR2(vcpu, "Reflecting exception %d/%#x into "
2715 		    "the guest", intr_vec, errcode);
2716 		SDT_PROBE5(vmm, vmx, exit, exception,
2717 		    vmx, vcpuid, vmexit, intr_vec, errcode);
2718 		error = vm_inject_exception(vcpu->vcpu, intr_vec,
2719 		    errcode_valid, errcode, 0);
2720 		KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2721 		    __func__, error));
2722 		return (1);
2723 
2724 	case EXIT_REASON_EPT_FAULT:
2725 		/*
2726 		 * If 'gpa' lies within the address space allocated to
2727 		 * memory then this must be a nested page fault otherwise
2728 		 * this must be an instruction that accesses MMIO space.
2729 		 */
2730 		gpa = vmcs_gpa();
2731 		if (vm_mem_allocated(vcpu->vcpu, gpa) ||
2732 		    apic_access_fault(vcpu, gpa)) {
2733 			vmexit->exitcode = VM_EXITCODE_PAGING;
2734 			vmexit->inst_length = 0;
2735 			vmexit->u.paging.gpa = gpa;
2736 			vmexit->u.paging.fault_type = ept_fault_type(qual);
2737 			vmm_stat_incr(vcpu->vcpu, VMEXIT_NESTED_FAULT, 1);
2738 			SDT_PROBE5(vmm, vmx, exit, nestedfault,
2739 			    vmx, vcpuid, vmexit, gpa, qual);
2740 		} else if (ept_emulation_fault(qual)) {
2741 			vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2742 			vmm_stat_incr(vcpu->vcpu, VMEXIT_INST_EMUL, 1);
2743 			SDT_PROBE4(vmm, vmx, exit, mmiofault,
2744 			    vmx, vcpuid, vmexit, gpa);
2745 		}
2746 		/*
2747 		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2748 		 * EPT fault during the execution of IRET then we must restore
2749 		 * the state of "virtual-NMI blocking" before resuming.
2750 		 *
2751 		 * See description of "NMI unblocking due to IRET" in
2752 		 * "Exit Qualification for EPT Violations".
2753 		 */
2754 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2755 		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2756 			vmx_restore_nmi_blocking(vcpu);
2757 		break;
2758 	case EXIT_REASON_VIRTUALIZED_EOI:
2759 		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2760 		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2761 		SDT_PROBE3(vmm, vmx, exit, eoi, vmx, vcpuid, vmexit);
2762 		vmexit->inst_length = 0;	/* trap-like */
2763 		break;
2764 	case EXIT_REASON_APIC_ACCESS:
2765 		SDT_PROBE3(vmm, vmx, exit, apicaccess, vmx, vcpuid, vmexit);
2766 		handled = vmx_handle_apic_access(vcpu, vmexit);
2767 		break;
2768 	case EXIT_REASON_APIC_WRITE:
2769 		/*
2770 		 * APIC-write VM exit is trap-like so the %rip is already
2771 		 * pointing to the next instruction.
2772 		 */
2773 		vmexit->inst_length = 0;
2774 		vlapic = vm_lapic(vcpu->vcpu);
2775 		SDT_PROBE4(vmm, vmx, exit, apicwrite,
2776 		    vmx, vcpuid, vmexit, vlapic);
2777 		handled = vmx_handle_apic_write(vcpu, vlapic, qual);
2778 		break;
2779 	case EXIT_REASON_XSETBV:
2780 		SDT_PROBE3(vmm, vmx, exit, xsetbv, vmx, vcpuid, vmexit);
2781 		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2782 		break;
2783 	case EXIT_REASON_MONITOR:
2784 		SDT_PROBE3(vmm, vmx, exit, monitor, vmx, vcpuid, vmexit);
2785 		vmexit->exitcode = VM_EXITCODE_MONITOR;
2786 		break;
2787 	case EXIT_REASON_MWAIT:
2788 		SDT_PROBE3(vmm, vmx, exit, mwait, vmx, vcpuid, vmexit);
2789 		vmexit->exitcode = VM_EXITCODE_MWAIT;
2790 		break;
2791 	case EXIT_REASON_TPR:
2792 		vlapic = vm_lapic(vcpu->vcpu);
2793 		vlapic_sync_tpr(vlapic);
2794 		vmexit->inst_length = 0;
2795 		handled = HANDLED;
2796 		break;
2797 	case EXIT_REASON_VMCALL:
2798 	case EXIT_REASON_VMCLEAR:
2799 	case EXIT_REASON_VMLAUNCH:
2800 	case EXIT_REASON_VMPTRLD:
2801 	case EXIT_REASON_VMPTRST:
2802 	case EXIT_REASON_VMREAD:
2803 	case EXIT_REASON_VMRESUME:
2804 	case EXIT_REASON_VMWRITE:
2805 	case EXIT_REASON_VMXOFF:
2806 	case EXIT_REASON_VMXON:
2807 		SDT_PROBE3(vmm, vmx, exit, vminsn, vmx, vcpuid, vmexit);
2808 		vmexit->exitcode = VM_EXITCODE_VMINSN;
2809 		break;
2810 	case EXIT_REASON_INVD:
2811 	case EXIT_REASON_WBINVD:
2812 		/* ignore exit */
2813 		handled = HANDLED;
2814 		break;
2815 	default:
2816 		SDT_PROBE4(vmm, vmx, exit, unknown,
2817 		    vmx, vcpuid, vmexit, reason);
2818 		vmm_stat_incr(vcpu->vcpu, VMEXIT_UNKNOWN, 1);
2819 		break;
2820 	}
2821 
2822 	if (handled) {
2823 		/*
2824 		 * It is possible that control is returned to userland
2825 		 * even though we were able to handle the VM exit in the
2826 		 * kernel.
2827 		 *
2828 		 * In such a case we want to make sure that the userland
2829 		 * restarts guest execution at the instruction *after*
2830 		 * the one we just processed. Therefore we update the
2831 		 * guest rip in the VMCS and in 'vmexit'.
2832 		 */
2833 		vmexit->rip += vmexit->inst_length;
2834 		vmexit->inst_length = 0;
2835 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2836 	} else {
2837 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2838 			/*
2839 			 * If this VM exit was not claimed by anybody then
2840 			 * treat it as a generic VMX exit.
2841 			 */
2842 			vmexit->exitcode = VM_EXITCODE_VMX;
2843 			vmexit->u.vmx.status = VM_SUCCESS;
2844 			vmexit->u.vmx.inst_type = 0;
2845 			vmexit->u.vmx.inst_error = 0;
2846 		} else {
2847 			/*
2848 			 * The exitcode and collateral have been populated.
2849 			 * The VM exit will be processed further in userland.
2850 			 */
2851 		}
2852 	}
2853 
2854 	SDT_PROBE4(vmm, vmx, exit, return,
2855 	    vmx, vcpuid, vmexit, handled);
2856 	return (handled);
2857 }
2858 
2859 static __inline void
2860 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2861 {
2862 
2863 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2864 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2865 	    vmxctx->inst_fail_status));
2866 
2867 	vmexit->inst_length = 0;
2868 	vmexit->exitcode = VM_EXITCODE_VMX;
2869 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2870 	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2871 	vmexit->u.vmx.exit_reason = ~0;
2872 	vmexit->u.vmx.exit_qualification = ~0;
2873 
2874 	switch (rc) {
2875 	case VMX_VMRESUME_ERROR:
2876 	case VMX_VMLAUNCH_ERROR:
2877 		vmexit->u.vmx.inst_type = rc;
2878 		break;
2879 	default:
2880 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2881 	}
2882 }
2883 
2884 /*
2885  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2886  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2887  * sufficient to simply vector to the NMI handler via a software interrupt.
2888  * However, this must be done before maskable interrupts are enabled
2889  * otherwise the "iret" issued by an interrupt handler will incorrectly
2890  * clear NMI blocking.
2891  */
2892 static __inline void
2893 vmx_exit_handle_nmi(struct vmx_vcpu *vcpu, struct vm_exit *vmexit)
2894 {
2895 	uint32_t intr_info;
2896 
2897 	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2898 
2899 	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2900 		return;
2901 
2902 	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2903 	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2904 	    ("VM exit interruption info invalid: %#x", intr_info));
2905 
2906 	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2907 		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2908 		    "to NMI has invalid vector: %#x", intr_info));
2909 		VMX_CTR0(vcpu, "Vectoring to NMI handler");
2910 		__asm __volatile("int $2");
2911 	}
2912 }
2913 
2914 static __inline void
2915 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2916 {
2917 	register_t rflags;
2918 
2919 	/* Save host control debug registers. */
2920 	vmxctx->host_dr7 = rdr7();
2921 	vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2922 
2923 	/*
2924 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2925 	 * exceptions in the host based on the guest DRx values.  The
2926 	 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2927 	 */
2928 	load_dr7(0);
2929 	wrmsr(MSR_DEBUGCTLMSR, 0);
2930 
2931 	/*
2932 	 * Disable single stepping the kernel to avoid corrupting the
2933 	 * guest DR6.  A debugger might still be able to corrupt the
2934 	 * guest DR6 by setting a breakpoint after this point and then
2935 	 * single stepping.
2936 	 */
2937 	rflags = read_rflags();
2938 	vmxctx->host_tf = rflags & PSL_T;
2939 	write_rflags(rflags & ~PSL_T);
2940 
2941 	/* Save host debug registers. */
2942 	vmxctx->host_dr0 = rdr0();
2943 	vmxctx->host_dr1 = rdr1();
2944 	vmxctx->host_dr2 = rdr2();
2945 	vmxctx->host_dr3 = rdr3();
2946 	vmxctx->host_dr6 = rdr6();
2947 
2948 	/* Restore guest debug registers. */
2949 	load_dr0(vmxctx->guest_dr0);
2950 	load_dr1(vmxctx->guest_dr1);
2951 	load_dr2(vmxctx->guest_dr2);
2952 	load_dr3(vmxctx->guest_dr3);
2953 	load_dr6(vmxctx->guest_dr6);
2954 }
2955 
2956 static __inline void
2957 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2958 {
2959 
2960 	/* Save guest debug registers. */
2961 	vmxctx->guest_dr0 = rdr0();
2962 	vmxctx->guest_dr1 = rdr1();
2963 	vmxctx->guest_dr2 = rdr2();
2964 	vmxctx->guest_dr3 = rdr3();
2965 	vmxctx->guest_dr6 = rdr6();
2966 
2967 	/*
2968 	 * Restore host debug registers.  Restore DR7, DEBUGCTL, and
2969 	 * PSL_T last.
2970 	 */
2971 	load_dr0(vmxctx->host_dr0);
2972 	load_dr1(vmxctx->host_dr1);
2973 	load_dr2(vmxctx->host_dr2);
2974 	load_dr3(vmxctx->host_dr3);
2975 	load_dr6(vmxctx->host_dr6);
2976 	wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2977 	load_dr7(vmxctx->host_dr7);
2978 	write_rflags(read_rflags() | vmxctx->host_tf);
2979 }
2980 
2981 static __inline void
2982 vmx_pmap_activate(struct vmx *vmx, pmap_t pmap)
2983 {
2984 	long eptgen;
2985 	int cpu;
2986 
2987 	cpu = curcpu;
2988 
2989 	CPU_SET_ATOMIC(cpu, &pmap->pm_active);
2990 	smr_enter(pmap->pm_eptsmr);
2991 	eptgen = atomic_load_long(&pmap->pm_eptgen);
2992 	if (eptgen != vmx->eptgen[cpu]) {
2993 		vmx->eptgen[cpu] = eptgen;
2994 		invept(INVEPT_TYPE_SINGLE_CONTEXT,
2995 		    (struct invept_desc){ .eptp = vmx->eptp, ._res = 0 });
2996 	}
2997 }
2998 
2999 static __inline void
3000 vmx_pmap_deactivate(struct vmx *vmx, pmap_t pmap)
3001 {
3002 	smr_exit(pmap->pm_eptsmr);
3003 	CPU_CLR_ATOMIC(curcpu, &pmap->pm_active);
3004 }
3005 
3006 static int
3007 vmx_run(void *vcpui, register_t rip, pmap_t pmap, struct vm_eventinfo *evinfo)
3008 {
3009 	int rc, handled, launched;
3010 	struct vmx *vmx;
3011 	struct vmx_vcpu *vcpu;
3012 	struct vmxctx *vmxctx;
3013 	struct vmcs *vmcs;
3014 	struct vm_exit *vmexit;
3015 	struct vlapic *vlapic;
3016 	uint32_t exit_reason;
3017 	struct region_descriptor gdtr, idtr;
3018 	uint16_t ldt_sel;
3019 
3020 	vcpu = vcpui;
3021 	vmx = vcpu->vmx;
3022 	vmcs = vcpu->vmcs;
3023 	vmxctx = &vcpu->ctx;
3024 	vlapic = vm_lapic(vcpu->vcpu);
3025 	vmexit = vm_exitinfo(vcpu->vcpu);
3026 	launched = 0;
3027 
3028 	KASSERT(vmxctx->pmap == pmap,
3029 	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
3030 
3031 	vmx_msr_guest_enter(vcpu);
3032 
3033 	VMPTRLD(vmcs);
3034 
3035 	/*
3036 	 * XXX
3037 	 * We do this every time because we may setup the virtual machine
3038 	 * from a different process than the one that actually runs it.
3039 	 *
3040 	 * If the life of a virtual machine was spent entirely in the context
3041 	 * of a single process we could do this once in vmx_init().
3042 	 */
3043 	vmcs_write(VMCS_HOST_CR3, rcr3());
3044 
3045 	vmcs_write(VMCS_GUEST_RIP, rip);
3046 	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
3047 	do {
3048 		KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
3049 		    "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
3050 
3051 		handled = UNHANDLED;
3052 		/*
3053 		 * Interrupts are disabled from this point on until the
3054 		 * guest starts executing. This is done for the following
3055 		 * reasons:
3056 		 *
3057 		 * If an AST is asserted on this thread after the check below,
3058 		 * then the IPI_AST notification will not be lost, because it
3059 		 * will cause a VM exit due to external interrupt as soon as
3060 		 * the guest state is loaded.
3061 		 *
3062 		 * A posted interrupt after 'vmx_inject_interrupts()' will
3063 		 * not be "lost" because it will be held pending in the host
3064 		 * APIC because interrupts are disabled. The pending interrupt
3065 		 * will be recognized as soon as the guest state is loaded.
3066 		 *
3067 		 * The same reasoning applies to the IPI generated by
3068 		 * pmap_invalidate_ept().
3069 		 */
3070 		disable_intr();
3071 		vmx_inject_interrupts(vcpu, vlapic, rip);
3072 
3073 		/*
3074 		 * Check for vcpu suspension after injecting events because
3075 		 * vmx_inject_interrupts() can suspend the vcpu due to a
3076 		 * triple fault.
3077 		 */
3078 		if (vcpu_suspended(evinfo)) {
3079 			enable_intr();
3080 			vm_exit_suspended(vcpu->vcpu, rip);
3081 			break;
3082 		}
3083 
3084 		if (vcpu_rendezvous_pending(vcpu->vcpu, evinfo)) {
3085 			enable_intr();
3086 			vm_exit_rendezvous(vcpu->vcpu, rip);
3087 			break;
3088 		}
3089 
3090 		if (vcpu_reqidle(evinfo)) {
3091 			enable_intr();
3092 			vm_exit_reqidle(vcpu->vcpu, rip);
3093 			break;
3094 		}
3095 
3096 		if (vcpu_should_yield(vcpu->vcpu)) {
3097 			enable_intr();
3098 			vm_exit_astpending(vcpu->vcpu, rip);
3099 			vmx_astpending_trace(vcpu, rip);
3100 			handled = HANDLED;
3101 			break;
3102 		}
3103 
3104 		if (vcpu_debugged(vcpu->vcpu)) {
3105 			enable_intr();
3106 			vm_exit_debug(vcpu->vcpu, rip);
3107 			break;
3108 		}
3109 
3110 		/*
3111 		 * If TPR Shadowing is enabled, the TPR Threshold
3112 		 * must be updated right before entering the guest.
3113 		 */
3114 		if (tpr_shadowing && !virtual_interrupt_delivery) {
3115 			if ((vcpu->cap.proc_ctls & PROCBASED_USE_TPR_SHADOW) != 0) {
3116 				vmcs_write(VMCS_TPR_THRESHOLD, vlapic_get_cr8(vlapic));
3117 			}
3118 		}
3119 
3120 		/*
3121 		 * VM exits restore the base address but not the
3122 		 * limits of GDTR and IDTR.  The VMCS only stores the
3123 		 * base address, so VM exits set the limits to 0xffff.
3124 		 * Save and restore the full GDTR and IDTR to restore
3125 		 * the limits.
3126 		 *
3127 		 * The VMCS does not save the LDTR at all, and VM
3128 		 * exits clear LDTR as if a NULL selector were loaded.
3129 		 * The userspace hypervisor probably doesn't use a
3130 		 * LDT, but save and restore it to be safe.
3131 		 */
3132 		sgdt(&gdtr);
3133 		sidt(&idtr);
3134 		ldt_sel = sldt();
3135 
3136 		/*
3137 		 * The TSC_AUX MSR must be saved/restored while interrupts
3138 		 * are disabled so that it is not possible for the guest
3139 		 * TSC_AUX MSR value to be overwritten by the resume
3140 		 * portion of the IPI_SUSPEND codepath. This is why the
3141 		 * transition of this MSR is handled separately from those
3142 		 * handled by vmx_msr_guest_{enter,exit}(), which are ok to
3143 		 * be transitioned with preemption disabled but interrupts
3144 		 * enabled.
3145 		 *
3146 		 * These vmx_msr_guest_{enter,exit}_tsc_aux() calls can be
3147 		 * anywhere in this loop so long as they happen with
3148 		 * interrupts disabled. This location is chosen for
3149 		 * simplicity.
3150 		 */
3151 		vmx_msr_guest_enter_tsc_aux(vmx, vcpu);
3152 
3153 		vmx_dr_enter_guest(vmxctx);
3154 
3155 		/*
3156 		 * Mark the EPT as active on this host CPU and invalidate
3157 		 * EPTP-tagged TLB entries if required.
3158 		 */
3159 		vmx_pmap_activate(vmx, pmap);
3160 
3161 		vmx_run_trace(vcpu);
3162 		rc = vmx_enter_guest(vmxctx, vmx, launched);
3163 
3164 		vmx_pmap_deactivate(vmx, pmap);
3165 		vmx_dr_leave_guest(vmxctx);
3166 		vmx_msr_guest_exit_tsc_aux(vmx, vcpu);
3167 
3168 		bare_lgdt(&gdtr);
3169 		lidt(&idtr);
3170 		lldt(ldt_sel);
3171 
3172 		/* Collect some information for VM exit processing */
3173 		vmexit->rip = rip = vmcs_guest_rip();
3174 		vmexit->inst_length = vmexit_instruction_length();
3175 		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
3176 		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
3177 
3178 		/* Update 'nextrip' */
3179 		vcpu->state.nextrip = rip;
3180 
3181 		if (rc == VMX_GUEST_VMEXIT) {
3182 			vmx_exit_handle_nmi(vcpu, vmexit);
3183 			enable_intr();
3184 			handled = vmx_exit_process(vmx, vcpu, vmexit);
3185 		} else {
3186 			enable_intr();
3187 			vmx_exit_inst_error(vmxctx, rc, vmexit);
3188 		}
3189 		launched = 1;
3190 		vmx_exit_trace(vcpu, rip, exit_reason, handled);
3191 		rip = vmexit->rip;
3192 	} while (handled);
3193 
3194 	/*
3195 	 * If a VM exit has been handled then the exitcode must be BOGUS
3196 	 * If a VM exit is not handled then the exitcode must not be BOGUS
3197 	 */
3198 	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
3199 	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
3200 		panic("Mismatch between handled (%d) and exitcode (%d)",
3201 		      handled, vmexit->exitcode);
3202 	}
3203 
3204 	VMX_CTR1(vcpu, "returning from vmx_run: exitcode %d",
3205 	    vmexit->exitcode);
3206 
3207 	VMCLEAR(vmcs);
3208 	vmx_msr_guest_exit(vcpu);
3209 
3210 	return (0);
3211 }
3212 
3213 static void
3214 vmx_vcpu_cleanup(void *vcpui)
3215 {
3216 	struct vmx_vcpu *vcpu = vcpui;
3217 
3218 	vpid_free(vcpu->state.vpid);
3219 	free(vcpu->pir_desc, M_VMX);
3220 	free(vcpu->apic_page, M_VMX);
3221 	free(vcpu->vmcs, M_VMX);
3222 	free(vcpu, M_VMX);
3223 }
3224 
3225 static void
3226 vmx_cleanup(void *vmi)
3227 {
3228 	struct vmx *vmx = vmi;
3229 
3230 	if (virtual_interrupt_delivery)
3231 		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3232 
3233 	free(vmx->msr_bitmap, M_VMX);
3234 	free(vmx, M_VMX);
3235 
3236 	return;
3237 }
3238 
3239 static register_t *
3240 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
3241 {
3242 
3243 	switch (reg) {
3244 	case VM_REG_GUEST_RAX:
3245 		return (&vmxctx->guest_rax);
3246 	case VM_REG_GUEST_RBX:
3247 		return (&vmxctx->guest_rbx);
3248 	case VM_REG_GUEST_RCX:
3249 		return (&vmxctx->guest_rcx);
3250 	case VM_REG_GUEST_RDX:
3251 		return (&vmxctx->guest_rdx);
3252 	case VM_REG_GUEST_RSI:
3253 		return (&vmxctx->guest_rsi);
3254 	case VM_REG_GUEST_RDI:
3255 		return (&vmxctx->guest_rdi);
3256 	case VM_REG_GUEST_RBP:
3257 		return (&vmxctx->guest_rbp);
3258 	case VM_REG_GUEST_R8:
3259 		return (&vmxctx->guest_r8);
3260 	case VM_REG_GUEST_R9:
3261 		return (&vmxctx->guest_r9);
3262 	case VM_REG_GUEST_R10:
3263 		return (&vmxctx->guest_r10);
3264 	case VM_REG_GUEST_R11:
3265 		return (&vmxctx->guest_r11);
3266 	case VM_REG_GUEST_R12:
3267 		return (&vmxctx->guest_r12);
3268 	case VM_REG_GUEST_R13:
3269 		return (&vmxctx->guest_r13);
3270 	case VM_REG_GUEST_R14:
3271 		return (&vmxctx->guest_r14);
3272 	case VM_REG_GUEST_R15:
3273 		return (&vmxctx->guest_r15);
3274 	case VM_REG_GUEST_CR2:
3275 		return (&vmxctx->guest_cr2);
3276 	case VM_REG_GUEST_DR0:
3277 		return (&vmxctx->guest_dr0);
3278 	case VM_REG_GUEST_DR1:
3279 		return (&vmxctx->guest_dr1);
3280 	case VM_REG_GUEST_DR2:
3281 		return (&vmxctx->guest_dr2);
3282 	case VM_REG_GUEST_DR3:
3283 		return (&vmxctx->guest_dr3);
3284 	case VM_REG_GUEST_DR6:
3285 		return (&vmxctx->guest_dr6);
3286 	default:
3287 		break;
3288 	}
3289 	return (NULL);
3290 }
3291 
3292 static int
3293 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
3294 {
3295 	register_t *regp;
3296 
3297 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
3298 		*retval = *regp;
3299 		return (0);
3300 	} else
3301 		return (EINVAL);
3302 }
3303 
3304 static int
3305 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
3306 {
3307 	register_t *regp;
3308 
3309 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
3310 		*regp = val;
3311 		return (0);
3312 	} else
3313 		return (EINVAL);
3314 }
3315 
3316 static int
3317 vmx_get_intr_shadow(struct vmx_vcpu *vcpu, int running, uint64_t *retval)
3318 {
3319 	uint64_t gi;
3320 	int error;
3321 
3322 	error = vmcs_getreg(vcpu->vmcs, running,
3323 	    VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
3324 	*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
3325 	return (error);
3326 }
3327 
3328 static int
3329 vmx_modify_intr_shadow(struct vmx_vcpu *vcpu, int running, uint64_t val)
3330 {
3331 	struct vmcs *vmcs;
3332 	uint64_t gi;
3333 	int error, ident;
3334 
3335 	/*
3336 	 * Forcing the vcpu into an interrupt shadow is not supported.
3337 	 */
3338 	if (val) {
3339 		error = EINVAL;
3340 		goto done;
3341 	}
3342 
3343 	vmcs = vcpu->vmcs;
3344 	ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
3345 	error = vmcs_getreg(vmcs, running, ident, &gi);
3346 	if (error == 0) {
3347 		gi &= ~HWINTR_BLOCKING;
3348 		error = vmcs_setreg(vmcs, running, ident, gi);
3349 	}
3350 done:
3351 	VMX_CTR2(vcpu, "Setting intr_shadow to %#lx %s", val,
3352 	    error ? "failed" : "succeeded");
3353 	return (error);
3354 }
3355 
3356 static int
3357 vmx_shadow_reg(int reg)
3358 {
3359 	int shreg;
3360 
3361 	shreg = -1;
3362 
3363 	switch (reg) {
3364 	case VM_REG_GUEST_CR0:
3365 		shreg = VMCS_CR0_SHADOW;
3366 		break;
3367 	case VM_REG_GUEST_CR4:
3368 		shreg = VMCS_CR4_SHADOW;
3369 		break;
3370 	default:
3371 		break;
3372 	}
3373 
3374 	return (shreg);
3375 }
3376 
3377 static int
3378 vmx_getreg(void *vcpui, int reg, uint64_t *retval)
3379 {
3380 	int running, hostcpu;
3381 	struct vmx_vcpu *vcpu = vcpui;
3382 	struct vmx *vmx = vcpu->vmx;
3383 
3384 	running = vcpu_is_running(vcpu->vcpu, &hostcpu);
3385 	if (running && hostcpu != curcpu)
3386 		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm),
3387 		    vcpu->vcpuid);
3388 
3389 	if (reg == VM_REG_GUEST_INTR_SHADOW)
3390 		return (vmx_get_intr_shadow(vcpu, running, retval));
3391 
3392 	if (vmxctx_getreg(&vcpu->ctx, reg, retval) == 0)
3393 		return (0);
3394 
3395 	return (vmcs_getreg(vcpu->vmcs, running, reg, retval));
3396 }
3397 
3398 static int
3399 vmx_setreg(void *vcpui, int reg, uint64_t val)
3400 {
3401 	int error, hostcpu, running, shadow;
3402 	uint64_t ctls;
3403 	pmap_t pmap;
3404 	struct vmx_vcpu *vcpu = vcpui;
3405 	struct vmx *vmx = vcpu->vmx;
3406 
3407 	running = vcpu_is_running(vcpu->vcpu, &hostcpu);
3408 	if (running && hostcpu != curcpu)
3409 		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm),
3410 		    vcpu->vcpuid);
3411 
3412 	if (reg == VM_REG_GUEST_INTR_SHADOW)
3413 		return (vmx_modify_intr_shadow(vcpu, running, val));
3414 
3415 	if (vmxctx_setreg(&vcpu->ctx, reg, val) == 0)
3416 		return (0);
3417 
3418 	/* Do not permit user write access to VMCS fields by offset. */
3419 	if (reg < 0)
3420 		return (EINVAL);
3421 
3422 	error = vmcs_setreg(vcpu->vmcs, running, reg, val);
3423 
3424 	if (error == 0) {
3425 		/*
3426 		 * If the "load EFER" VM-entry control is 1 then the
3427 		 * value of EFER.LMA must be identical to "IA-32e mode guest"
3428 		 * bit in the VM-entry control.
3429 		 */
3430 		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
3431 		    (reg == VM_REG_GUEST_EFER)) {
3432 			vmcs_getreg(vcpu->vmcs, running,
3433 				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
3434 			if (val & EFER_LMA)
3435 				ctls |= VM_ENTRY_GUEST_LMA;
3436 			else
3437 				ctls &= ~VM_ENTRY_GUEST_LMA;
3438 			vmcs_setreg(vcpu->vmcs, running,
3439 				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
3440 		}
3441 
3442 		shadow = vmx_shadow_reg(reg);
3443 		if (shadow > 0) {
3444 			/*
3445 			 * Store the unmodified value in the shadow
3446 			 */
3447 			error = vmcs_setreg(vcpu->vmcs, running,
3448 				    VMCS_IDENT(shadow), val);
3449 		}
3450 
3451 		if (reg == VM_REG_GUEST_CR3) {
3452 			/*
3453 			 * Invalidate the guest vcpu's TLB mappings to emulate
3454 			 * the behavior of updating %cr3.
3455 			 *
3456 			 * XXX the processor retains global mappings when %cr3
3457 			 * is updated but vmx_invvpid() does not.
3458 			 */
3459 			pmap = vcpu->ctx.pmap;
3460 			vmx_invvpid(vmx, vcpu, pmap, running);
3461 		}
3462 	}
3463 
3464 	return (error);
3465 }
3466 
3467 static int
3468 vmx_getdesc(void *vcpui, int reg, struct seg_desc *desc)
3469 {
3470 	int hostcpu, running;
3471 	struct vmx_vcpu *vcpu = vcpui;
3472 	struct vmx *vmx = vcpu->vmx;
3473 
3474 	running = vcpu_is_running(vcpu->vcpu, &hostcpu);
3475 	if (running && hostcpu != curcpu)
3476 		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm),
3477 		    vcpu->vcpuid);
3478 
3479 	return (vmcs_getdesc(vcpu->vmcs, running, reg, desc));
3480 }
3481 
3482 static int
3483 vmx_setdesc(void *vcpui, int reg, struct seg_desc *desc)
3484 {
3485 	int hostcpu, running;
3486 	struct vmx_vcpu *vcpu = vcpui;
3487 	struct vmx *vmx = vcpu->vmx;
3488 
3489 	running = vcpu_is_running(vcpu->vcpu, &hostcpu);
3490 	if (running && hostcpu != curcpu)
3491 		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm),
3492 		    vcpu->vcpuid);
3493 
3494 	return (vmcs_setdesc(vcpu->vmcs, running, reg, desc));
3495 }
3496 
3497 static int
3498 vmx_getcap(void *vcpui, int type, int *retval)
3499 {
3500 	struct vmx_vcpu *vcpu = vcpui;
3501 	int vcap;
3502 	int ret;
3503 
3504 	ret = ENOENT;
3505 
3506 	vcap = vcpu->cap.set;
3507 
3508 	switch (type) {
3509 	case VM_CAP_HALT_EXIT:
3510 		if (cap_halt_exit)
3511 			ret = 0;
3512 		break;
3513 	case VM_CAP_PAUSE_EXIT:
3514 		if (cap_pause_exit)
3515 			ret = 0;
3516 		break;
3517 	case VM_CAP_MTRAP_EXIT:
3518 		if (cap_monitor_trap)
3519 			ret = 0;
3520 		break;
3521 	case VM_CAP_RDPID:
3522 		if (cap_rdpid)
3523 			ret = 0;
3524 		break;
3525 	case VM_CAP_RDTSCP:
3526 		if (cap_rdtscp)
3527 			ret = 0;
3528 		break;
3529 	case VM_CAP_UNRESTRICTED_GUEST:
3530 		if (cap_unrestricted_guest)
3531 			ret = 0;
3532 		break;
3533 	case VM_CAP_ENABLE_INVPCID:
3534 		if (cap_invpcid)
3535 			ret = 0;
3536 		break;
3537 	case VM_CAP_BPT_EXIT:
3538 	case VM_CAP_IPI_EXIT:
3539 		ret = 0;
3540 		break;
3541 	default:
3542 		break;
3543 	}
3544 
3545 	if (ret == 0)
3546 		*retval = (vcap & (1 << type)) ? 1 : 0;
3547 
3548 	return (ret);
3549 }
3550 
3551 static int
3552 vmx_setcap(void *vcpui, int type, int val)
3553 {
3554 	struct vmx_vcpu *vcpu = vcpui;
3555 	struct vmcs *vmcs = vcpu->vmcs;
3556 	struct vlapic *vlapic;
3557 	uint32_t baseval;
3558 	uint32_t *pptr;
3559 	int error;
3560 	int flag;
3561 	int reg;
3562 	int retval;
3563 
3564 	retval = ENOENT;
3565 	pptr = NULL;
3566 
3567 	switch (type) {
3568 	case VM_CAP_HALT_EXIT:
3569 		if (cap_halt_exit) {
3570 			retval = 0;
3571 			pptr = &vcpu->cap.proc_ctls;
3572 			baseval = *pptr;
3573 			flag = PROCBASED_HLT_EXITING;
3574 			reg = VMCS_PRI_PROC_BASED_CTLS;
3575 		}
3576 		break;
3577 	case VM_CAP_MTRAP_EXIT:
3578 		if (cap_monitor_trap) {
3579 			retval = 0;
3580 			pptr = &vcpu->cap.proc_ctls;
3581 			baseval = *pptr;
3582 			flag = PROCBASED_MTF;
3583 			reg = VMCS_PRI_PROC_BASED_CTLS;
3584 		}
3585 		break;
3586 	case VM_CAP_PAUSE_EXIT:
3587 		if (cap_pause_exit) {
3588 			retval = 0;
3589 			pptr = &vcpu->cap.proc_ctls;
3590 			baseval = *pptr;
3591 			flag = PROCBASED_PAUSE_EXITING;
3592 			reg = VMCS_PRI_PROC_BASED_CTLS;
3593 		}
3594 		break;
3595 	case VM_CAP_RDPID:
3596 	case VM_CAP_RDTSCP:
3597 		if (cap_rdpid || cap_rdtscp)
3598 			/*
3599 			 * Choose not to support enabling/disabling
3600 			 * RDPID/RDTSCP via libvmmapi since, as per the
3601 			 * discussion in vmx_modinit(), RDPID/RDTSCP are
3602 			 * either always enabled or always disabled.
3603 			 */
3604 			error = EOPNOTSUPP;
3605 		break;
3606 	case VM_CAP_UNRESTRICTED_GUEST:
3607 		if (cap_unrestricted_guest) {
3608 			retval = 0;
3609 			pptr = &vcpu->cap.proc_ctls2;
3610 			baseval = *pptr;
3611 			flag = PROCBASED2_UNRESTRICTED_GUEST;
3612 			reg = VMCS_SEC_PROC_BASED_CTLS;
3613 		}
3614 		break;
3615 	case VM_CAP_ENABLE_INVPCID:
3616 		if (cap_invpcid) {
3617 			retval = 0;
3618 			pptr = &vcpu->cap.proc_ctls2;
3619 			baseval = *pptr;
3620 			flag = PROCBASED2_ENABLE_INVPCID;
3621 			reg = VMCS_SEC_PROC_BASED_CTLS;
3622 		}
3623 		break;
3624 	case VM_CAP_BPT_EXIT:
3625 		retval = 0;
3626 
3627 		/* Don't change the bitmap if we are tracing all exceptions. */
3628 		if (vcpu->cap.exc_bitmap != 0xffffffff) {
3629 			pptr = &vcpu->cap.exc_bitmap;
3630 			baseval = *pptr;
3631 			flag = (1 << IDT_BP);
3632 			reg = VMCS_EXCEPTION_BITMAP;
3633 		}
3634 		break;
3635 	case VM_CAP_IPI_EXIT:
3636 		retval = 0;
3637 
3638 		vlapic = vm_lapic(vcpu->vcpu);
3639 		vlapic->ipi_exit = val;
3640 		break;
3641 	case VM_CAP_MASK_HWINTR:
3642 		retval = 0;
3643 		break;
3644 	default:
3645 		break;
3646 	}
3647 
3648 	if (retval)
3649 		return (retval);
3650 
3651 	if (pptr != NULL) {
3652 		if (val) {
3653 			baseval |= flag;
3654 		} else {
3655 			baseval &= ~flag;
3656 		}
3657 		VMPTRLD(vmcs);
3658 		error = vmwrite(reg, baseval);
3659 		VMCLEAR(vmcs);
3660 
3661 		if (error)
3662 			return (error);
3663 
3664 		/*
3665 		 * Update optional stored flags, and record
3666 		 * setting
3667 		 */
3668 		*pptr = baseval;
3669 	}
3670 
3671 	if (val) {
3672 		vcpu->cap.set |= (1 << type);
3673 	} else {
3674 		vcpu->cap.set &= ~(1 << type);
3675 	}
3676 
3677 	return (0);
3678 }
3679 
3680 static struct vmspace *
3681 vmx_vmspace_alloc(vm_offset_t min, vm_offset_t max)
3682 {
3683 	return (ept_vmspace_alloc(min, max));
3684 }
3685 
3686 static void
3687 vmx_vmspace_free(struct vmspace *vmspace)
3688 {
3689 	ept_vmspace_free(vmspace);
3690 }
3691 
3692 struct vlapic_vtx {
3693 	struct vlapic	vlapic;
3694 	struct pir_desc	*pir_desc;
3695 	struct vmx_vcpu	*vcpu;
3696 	u_int	pending_prio;
3697 };
3698 
3699 #define VPR_PRIO_BIT(vpr)	(1 << ((vpr) >> 4))
3700 
3701 #define	VMX_CTR_PIR(vlapic, pir_desc, notify, vector, level, msg)	\
3702 do {									\
3703 	VLAPIC_CTR2(vlapic, msg " assert %s-triggered vector %d",	\
3704 	    level ? "level" : "edge", vector);				\
3705 	VLAPIC_CTR1(vlapic, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3706 	VLAPIC_CTR1(vlapic, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3707 	VLAPIC_CTR1(vlapic, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3708 	VLAPIC_CTR1(vlapic, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3709 	VLAPIC_CTR1(vlapic, msg " notify: %s", notify ? "yes" : "no");	\
3710 } while (0)
3711 
3712 /*
3713  * vlapic->ops handlers that utilize the APICv hardware assist described in
3714  * Chapter 29 of the Intel SDM.
3715  */
3716 static int
3717 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3718 {
3719 	struct vlapic_vtx *vlapic_vtx;
3720 	struct pir_desc *pir_desc;
3721 	uint64_t mask;
3722 	int idx, notify = 0;
3723 
3724 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3725 	pir_desc = vlapic_vtx->pir_desc;
3726 
3727 	/*
3728 	 * Keep track of interrupt requests in the PIR descriptor. This is
3729 	 * because the virtual APIC page pointed to by the VMCS cannot be
3730 	 * modified if the vcpu is running.
3731 	 */
3732 	idx = vector / 64;
3733 	mask = 1UL << (vector % 64);
3734 	atomic_set_long(&pir_desc->pir[idx], mask);
3735 
3736 	/*
3737 	 * A notification is required whenever the 'pending' bit makes a
3738 	 * transition from 0->1.
3739 	 *
3740 	 * Even if the 'pending' bit is already asserted, notification about
3741 	 * the incoming interrupt may still be necessary.  For example, if a
3742 	 * vCPU is HLTed with a high PPR, a low priority interrupt would cause
3743 	 * the 0->1 'pending' transition with a notification, but the vCPU
3744 	 * would ignore the interrupt for the time being.  The same vCPU would
3745 	 * need to then be notified if a high-priority interrupt arrived which
3746 	 * satisfied the PPR.
3747 	 *
3748 	 * The priorities of interrupts injected while 'pending' is asserted
3749 	 * are tracked in a custom bitfield 'pending_prio'.  Should the
3750 	 * to-be-injected interrupt exceed the priorities already present, the
3751 	 * notification is sent.  The priorities recorded in 'pending_prio' are
3752 	 * cleared whenever the 'pending' bit makes another 0->1 transition.
3753 	 */
3754 	if (atomic_cmpset_long(&pir_desc->pending, 0, 1) != 0) {
3755 		notify = 1;
3756 		vlapic_vtx->pending_prio = 0;
3757 	} else {
3758 		const u_int old_prio = vlapic_vtx->pending_prio;
3759 		const u_int prio_bit = VPR_PRIO_BIT(vector & APIC_TPR_INT);
3760 
3761 		if ((old_prio & prio_bit) == 0 && prio_bit > old_prio) {
3762 			atomic_set_int(&vlapic_vtx->pending_prio, prio_bit);
3763 			notify = 1;
3764 		}
3765 	}
3766 
3767 	VMX_CTR_PIR(vlapic, pir_desc, notify, vector, level,
3768 	    "vmx_set_intr_ready");
3769 	return (notify);
3770 }
3771 
3772 static int
3773 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3774 {
3775 	struct vlapic_vtx *vlapic_vtx;
3776 	struct pir_desc *pir_desc;
3777 	struct LAPIC *lapic;
3778 	uint64_t pending, pirval;
3779 	uint8_t ppr, vpr, rvi;
3780 	struct vm_exit *vmexit;
3781 	int i;
3782 
3783 	/*
3784 	 * This function is only expected to be called from the 'HLT' exit
3785 	 * handler which does not care about the vector that is pending.
3786 	 */
3787 	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3788 
3789 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3790 	pir_desc = vlapic_vtx->pir_desc;
3791 	lapic = vlapic->apic_page;
3792 
3793 	/*
3794 	 * While a virtual interrupt may have already been
3795 	 * processed the actual delivery maybe pending the
3796 	 * interruptibility of the guest.  Recognize a pending
3797 	 * interrupt by reevaluating virtual interrupts
3798 	 * following Section 30.2.1 in the Intel SDM Volume 3.
3799 	 */
3800 	vmexit = vm_exitinfo(vlapic->vcpu);
3801 	KASSERT(vmexit->exitcode == VM_EXITCODE_HLT,
3802 	    ("vmx_pending_intr: exitcode not 'HLT'"));
3803 	rvi = vmexit->u.hlt.intr_status & APIC_TPR_INT;
3804 	ppr = lapic->ppr & APIC_TPR_INT;
3805 	if (rvi > ppr)
3806 		return (1);
3807 
3808 	pending = atomic_load_acq_long(&pir_desc->pending);
3809 	if (!pending)
3810 		return (0);
3811 
3812 	/*
3813 	 * If there is an interrupt pending then it will be recognized only
3814 	 * if its priority is greater than the processor priority.
3815 	 *
3816 	 * Special case: if the processor priority is zero then any pending
3817 	 * interrupt will be recognized.
3818 	 */
3819 	if (ppr == 0)
3820 		return (1);
3821 
3822 	VLAPIC_CTR1(vlapic, "HLT with non-zero PPR %d", lapic->ppr);
3823 
3824 	vpr = 0;
3825 	for (i = 3; i >= 0; i--) {
3826 		pirval = pir_desc->pir[i];
3827 		if (pirval != 0) {
3828 			vpr = (i * 64 + flsl(pirval) - 1) & APIC_TPR_INT;
3829 			break;
3830 		}
3831 	}
3832 
3833 	/*
3834 	 * If the highest-priority pending interrupt falls short of the
3835 	 * processor priority of this vCPU, ensure that 'pending_prio' does not
3836 	 * have any stale bits which would preclude a higher-priority interrupt
3837 	 * from incurring a notification later.
3838 	 */
3839 	if (vpr <= ppr) {
3840 		const u_int prio_bit = VPR_PRIO_BIT(vpr);
3841 		const u_int old = vlapic_vtx->pending_prio;
3842 
3843 		if (old > prio_bit && (old & prio_bit) == 0) {
3844 			vlapic_vtx->pending_prio = prio_bit;
3845 		}
3846 		return (0);
3847 	}
3848 	return (1);
3849 }
3850 
3851 static void
3852 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3853 {
3854 
3855 	panic("vmx_intr_accepted: not expected to be called");
3856 }
3857 
3858 static void
3859 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3860 {
3861 	struct vlapic_vtx *vlapic_vtx;
3862 	struct vmcs *vmcs;
3863 	uint64_t mask, val;
3864 
3865 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3866 	KASSERT(!vcpu_is_running(vlapic->vcpu, NULL),
3867 	    ("vmx_set_tmr: vcpu cannot be running"));
3868 
3869 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3870 	vmcs = vlapic_vtx->vcpu->vmcs;
3871 	mask = 1UL << (vector % 64);
3872 
3873 	VMPTRLD(vmcs);
3874 	val = vmcs_read(VMCS_EOI_EXIT(vector));
3875 	if (level)
3876 		val |= mask;
3877 	else
3878 		val &= ~mask;
3879 	vmcs_write(VMCS_EOI_EXIT(vector), val);
3880 	VMCLEAR(vmcs);
3881 }
3882 
3883 static void
3884 vmx_enable_x2apic_mode_ts(struct vlapic *vlapic)
3885 {
3886 	struct vlapic_vtx *vlapic_vtx;
3887 	struct vmx_vcpu *vcpu;
3888 	struct vmcs *vmcs;
3889 	uint32_t proc_ctls;
3890 
3891 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3892 	vcpu = vlapic_vtx->vcpu;
3893 	vmcs = vcpu->vmcs;
3894 
3895 	proc_ctls = vcpu->cap.proc_ctls;
3896 	proc_ctls &= ~PROCBASED_USE_TPR_SHADOW;
3897 	proc_ctls |= PROCBASED_CR8_LOAD_EXITING;
3898 	proc_ctls |= PROCBASED_CR8_STORE_EXITING;
3899 	vcpu->cap.proc_ctls = proc_ctls;
3900 
3901 	VMPTRLD(vmcs);
3902 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
3903 	VMCLEAR(vmcs);
3904 }
3905 
3906 static void
3907 vmx_enable_x2apic_mode_vid(struct vlapic *vlapic)
3908 {
3909 	struct vlapic_vtx *vlapic_vtx;
3910 	struct vmx *vmx;
3911 	struct vmx_vcpu *vcpu;
3912 	struct vmcs *vmcs;
3913 	uint32_t proc_ctls2;
3914 	int error __diagused;
3915 
3916 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3917 	vcpu = vlapic_vtx->vcpu;
3918 	vmx = vcpu->vmx;
3919 	vmcs = vcpu->vmcs;
3920 
3921 	proc_ctls2 = vcpu->cap.proc_ctls2;
3922 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3923 	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3924 
3925 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3926 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3927 	vcpu->cap.proc_ctls2 = proc_ctls2;
3928 
3929 	VMPTRLD(vmcs);
3930 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3931 	VMCLEAR(vmcs);
3932 
3933 	if (vlapic->vcpuid == 0) {
3934 		/*
3935 		 * The nested page table mappings are shared by all vcpus
3936 		 * so unmap the APIC access page just once.
3937 		 */
3938 		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3939 		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3940 		    __func__, error));
3941 
3942 		/*
3943 		 * The MSR bitmap is shared by all vcpus so modify it only
3944 		 * once in the context of vcpu 0.
3945 		 */
3946 		error = vmx_allow_x2apic_msrs(vmx);
3947 		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3948 		    __func__, error));
3949 	}
3950 }
3951 
3952 static void
3953 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3954 {
3955 
3956 	ipi_cpu(hostcpu, pirvec);
3957 }
3958 
3959 /*
3960  * Transfer the pending interrupts in the PIR descriptor to the IRR
3961  * in the virtual APIC page.
3962  */
3963 static void
3964 vmx_inject_pir(struct vlapic *vlapic)
3965 {
3966 	struct vlapic_vtx *vlapic_vtx;
3967 	struct pir_desc *pir_desc;
3968 	struct LAPIC *lapic;
3969 	uint64_t val, pirval;
3970 	int rvi, pirbase = -1;
3971 	uint16_t intr_status_old, intr_status_new;
3972 
3973 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3974 	pir_desc = vlapic_vtx->pir_desc;
3975 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3976 		VLAPIC_CTR0(vlapic, "vmx_inject_pir: "
3977 		    "no posted interrupt pending");
3978 		return;
3979 	}
3980 
3981 	pirval = 0;
3982 	pirbase = -1;
3983 	lapic = vlapic->apic_page;
3984 
3985 	val = atomic_readandclear_long(&pir_desc->pir[0]);
3986 	if (val != 0) {
3987 		lapic->irr0 |= val;
3988 		lapic->irr1 |= val >> 32;
3989 		pirbase = 0;
3990 		pirval = val;
3991 	}
3992 
3993 	val = atomic_readandclear_long(&pir_desc->pir[1]);
3994 	if (val != 0) {
3995 		lapic->irr2 |= val;
3996 		lapic->irr3 |= val >> 32;
3997 		pirbase = 64;
3998 		pirval = val;
3999 	}
4000 
4001 	val = atomic_readandclear_long(&pir_desc->pir[2]);
4002 	if (val != 0) {
4003 		lapic->irr4 |= val;
4004 		lapic->irr5 |= val >> 32;
4005 		pirbase = 128;
4006 		pirval = val;
4007 	}
4008 
4009 	val = atomic_readandclear_long(&pir_desc->pir[3]);
4010 	if (val != 0) {
4011 		lapic->irr6 |= val;
4012 		lapic->irr7 |= val >> 32;
4013 		pirbase = 192;
4014 		pirval = val;
4015 	}
4016 
4017 	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
4018 
4019 	/*
4020 	 * Update RVI so the processor can evaluate pending virtual
4021 	 * interrupts on VM-entry.
4022 	 *
4023 	 * It is possible for pirval to be 0 here, even though the
4024 	 * pending bit has been set. The scenario is:
4025 	 * CPU-Y is sending a posted interrupt to CPU-X, which
4026 	 * is running a guest and processing posted interrupts in h/w.
4027 	 * CPU-X will eventually exit and the state seen in s/w is
4028 	 * the pending bit set, but no PIR bits set.
4029 	 *
4030 	 *      CPU-X                      CPU-Y
4031 	 *   (vm running)                (host running)
4032 	 *   rx posted interrupt
4033 	 *   CLEAR pending bit
4034 	 *				 SET PIR bit
4035 	 *   READ/CLEAR PIR bits
4036 	 *				 SET pending bit
4037 	 *   (vm exit)
4038 	 *   pending bit set, PIR 0
4039 	 */
4040 	if (pirval != 0) {
4041 		rvi = pirbase + flsl(pirval) - 1;
4042 		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
4043 		intr_status_new = (intr_status_old & 0xFF00) | rvi;
4044 		if (intr_status_new > intr_status_old) {
4045 			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
4046 			VLAPIC_CTR2(vlapic, "vmx_inject_pir: "
4047 			    "guest_intr_status changed from 0x%04x to 0x%04x",
4048 			    intr_status_old, intr_status_new);
4049 		}
4050 	}
4051 }
4052 
4053 static struct vlapic *
4054 vmx_vlapic_init(void *vcpui)
4055 {
4056 	struct vmx *vmx;
4057 	struct vmx_vcpu *vcpu;
4058 	struct vlapic *vlapic;
4059 	struct vlapic_vtx *vlapic_vtx;
4060 
4061 	vcpu = vcpui;
4062 	vmx = vcpu->vmx;
4063 
4064 	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
4065 	vlapic->vm = vmx->vm;
4066 	vlapic->vcpu = vcpu->vcpu;
4067 	vlapic->vcpuid = vcpu->vcpuid;
4068 	vlapic->apic_page = (struct LAPIC *)vcpu->apic_page;
4069 
4070 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
4071 	vlapic_vtx->pir_desc = vcpu->pir_desc;
4072 	vlapic_vtx->vcpu = vcpu;
4073 
4074 	if (tpr_shadowing) {
4075 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_ts;
4076 	}
4077 
4078 	if (virtual_interrupt_delivery) {
4079 		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
4080 		vlapic->ops.pending_intr = vmx_pending_intr;
4081 		vlapic->ops.intr_accepted = vmx_intr_accepted;
4082 		vlapic->ops.set_tmr = vmx_set_tmr;
4083 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_vid;
4084 	}
4085 
4086 	if (posted_interrupts)
4087 		vlapic->ops.post_intr = vmx_post_intr;
4088 
4089 	vlapic_init(vlapic);
4090 
4091 	return (vlapic);
4092 }
4093 
4094 static void
4095 vmx_vlapic_cleanup(struct vlapic *vlapic)
4096 {
4097 
4098 	vlapic_cleanup(vlapic);
4099 	free(vlapic, M_VLAPIC);
4100 }
4101 
4102 #ifdef BHYVE_SNAPSHOT
4103 static int
4104 vmx_vcpu_snapshot(void *vcpui, struct vm_snapshot_meta *meta)
4105 {
4106 	struct vmcs *vmcs;
4107 	struct vmx *vmx;
4108 	struct vmx_vcpu *vcpu;
4109 	struct vmxctx *vmxctx;
4110 	int err, run, hostcpu;
4111 
4112 	err = 0;
4113 	vcpu = vcpui;
4114 	vmx = vcpu->vmx;
4115 	vmcs = vcpu->vmcs;
4116 
4117 	run = vcpu_is_running(vcpu->vcpu, &hostcpu);
4118 	if (run && hostcpu != curcpu) {
4119 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm),
4120 		    vcpu->vcpuid);
4121 		return (EINVAL);
4122 	}
4123 
4124 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR0, meta);
4125 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR3, meta);
4126 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR4, meta);
4127 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DR7, meta);
4128 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RSP, meta);
4129 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RIP, meta);
4130 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RFLAGS, meta);
4131 
4132 	/* Guest segments */
4133 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_ES, meta);
4134 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_ES, meta);
4135 
4136 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CS, meta);
4137 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_CS, meta);
4138 
4139 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_SS, meta);
4140 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_SS, meta);
4141 
4142 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DS, meta);
4143 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_DS, meta);
4144 
4145 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_FS, meta);
4146 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_FS, meta);
4147 
4148 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_GS, meta);
4149 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GS, meta);
4150 
4151 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_TR, meta);
4152 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_TR, meta);
4153 
4154 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_LDTR, meta);
4155 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_LDTR, meta);
4156 
4157 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_EFER, meta);
4158 
4159 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_IDTR, meta);
4160 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GDTR, meta);
4161 
4162 	/* Guest page tables */
4163 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE0, meta);
4164 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE1, meta);
4165 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE2, meta);
4166 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE3, meta);
4167 
4168 	/* Other guest state */
4169 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_CS, meta);
4170 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_ESP, meta);
4171 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_EIP, meta);
4172 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_INTERRUPTIBILITY, meta);
4173 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_ACTIVITY, meta);
4174 	err += vmcs_snapshot_any(vmcs, run, VMCS_ENTRY_CTLS, meta);
4175 	err += vmcs_snapshot_any(vmcs, run, VMCS_EXIT_CTLS, meta);
4176 	if (err != 0)
4177 		goto done;
4178 
4179 	SNAPSHOT_BUF_OR_LEAVE(vcpu->guest_msrs,
4180 	    sizeof(vcpu->guest_msrs), meta, err, done);
4181 
4182 	SNAPSHOT_BUF_OR_LEAVE(vcpu->pir_desc,
4183 	    sizeof(*vcpu->pir_desc), meta, err, done);
4184 
4185 	vmxctx = &vcpu->ctx;
4186 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdi, meta, err, done);
4187 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rsi, meta, err, done);
4188 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdx, meta, err, done);
4189 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rcx, meta, err, done);
4190 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r8, meta, err, done);
4191 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r9, meta, err, done);
4192 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rax, meta, err, done);
4193 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbx, meta, err, done);
4194 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbp, meta, err, done);
4195 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r10, meta, err, done);
4196 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r11, meta, err, done);
4197 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r12, meta, err, done);
4198 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r13, meta, err, done);
4199 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r14, meta, err, done);
4200 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r15, meta, err, done);
4201 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_cr2, meta, err, done);
4202 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr0, meta, err, done);
4203 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr1, meta, err, done);
4204 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr2, meta, err, done);
4205 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr3, meta, err, done);
4206 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr6, meta, err, done);
4207 
4208 done:
4209 	return (err);
4210 }
4211 
4212 static int
4213 vmx_restore_tsc(void *vcpui, uint64_t offset)
4214 {
4215 	struct vmx_vcpu *vcpu = vcpui;
4216 	struct vmcs *vmcs;
4217 	struct vmx *vmx;
4218 	int error, running, hostcpu;
4219 
4220 	vmx = vcpu->vmx;
4221 	vmcs = vcpu->vmcs;
4222 
4223 	running = vcpu_is_running(vcpu->vcpu, &hostcpu);
4224 	if (running && hostcpu != curcpu) {
4225 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm),
4226 		    vcpu->vcpuid);
4227 		return (EINVAL);
4228 	}
4229 
4230 	if (!running)
4231 		VMPTRLD(vmcs);
4232 
4233 	error = vmx_set_tsc_offset(vcpu, offset);
4234 
4235 	if (!running)
4236 		VMCLEAR(vmcs);
4237 	return (error);
4238 }
4239 #endif
4240 
4241 const struct vmm_ops vmm_ops_intel = {
4242 	.modinit	= vmx_modinit,
4243 	.modcleanup	= vmx_modcleanup,
4244 	.modresume	= vmx_modresume,
4245 	.init		= vmx_init,
4246 	.run		= vmx_run,
4247 	.cleanup	= vmx_cleanup,
4248 	.vcpu_init	= vmx_vcpu_init,
4249 	.vcpu_cleanup	= vmx_vcpu_cleanup,
4250 	.getreg		= vmx_getreg,
4251 	.setreg		= vmx_setreg,
4252 	.getdesc	= vmx_getdesc,
4253 	.setdesc	= vmx_setdesc,
4254 	.getcap		= vmx_getcap,
4255 	.setcap		= vmx_setcap,
4256 	.vmspace_alloc	= vmx_vmspace_alloc,
4257 	.vmspace_free	= vmx_vmspace_free,
4258 	.vlapic_init	= vmx_vlapic_init,
4259 	.vlapic_cleanup	= vmx_vlapic_cleanup,
4260 #ifdef BHYVE_SNAPSHOT
4261 	.vcpu_snapshot	= vmx_vcpu_snapshot,
4262 	.restore_tsc	= vmx_restore_tsc,
4263 #endif
4264 };
4265