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