xref: /freebsd/sys/amd64/vmm/intel/vmx.c (revision b10e100d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  * Copyright (c) 2018 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_bhyve_snapshot.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/smp.h>
40 #include <sys/kernel.h>
41 #include <sys/malloc.h>
42 #include <sys/pcpu.h>
43 #include <sys/proc.h>
44 #include <sys/reg.h>
45 #include <sys/smr.h>
46 #include <sys/sysctl.h>
47 
48 #include <vm/vm.h>
49 #include <vm/vm_extern.h>
50 #include <vm/pmap.h>
51 
52 #include <machine/psl.h>
53 #include <machine/cpufunc.h>
54 #include <machine/md_var.h>
55 #include <machine/segments.h>
56 #include <machine/smp.h>
57 #include <machine/specialreg.h>
58 #include <machine/vmparam.h>
59 
60 #include <machine/vmm.h>
61 #include <machine/vmm_dev.h>
62 #include <machine/vmm_instruction_emul.h>
63 #include <machine/vmm_snapshot.h>
64 
65 #include "vmm_lapic.h"
66 #include "vmm_host.h"
67 #include "vmm_ioport.h"
68 #include "vmm_ktr.h"
69 #include "vmm_stat.h"
70 #include "vatpic.h"
71 #include "vlapic.h"
72 #include "vlapic_priv.h"
73 
74 #include "ept.h"
75 #include "vmx_cpufunc.h"
76 #include "vmx.h"
77 #include "vmx_msr.h"
78 #include "x86.h"
79 #include "vmx_controls.h"
80 
81 #define	PINBASED_CTLS_ONE_SETTING					\
82 	(PINBASED_EXTINT_EXITING	|				\
83 	 PINBASED_NMI_EXITING		|				\
84 	 PINBASED_VIRTUAL_NMI)
85 #define	PINBASED_CTLS_ZERO_SETTING	0
86 
87 #define PROCBASED_CTLS_WINDOW_SETTING					\
88 	(PROCBASED_INT_WINDOW_EXITING	|				\
89 	 PROCBASED_NMI_WINDOW_EXITING)
90 
91 #define	PROCBASED_CTLS_ONE_SETTING					\
92 	(PROCBASED_SECONDARY_CONTROLS	|				\
93 	 PROCBASED_MWAIT_EXITING	|				\
94 	 PROCBASED_MONITOR_EXITING	|				\
95 	 PROCBASED_IO_EXITING		|				\
96 	 PROCBASED_MSR_BITMAPS		|				\
97 	 PROCBASED_CTLS_WINDOW_SETTING	|				\
98 	 PROCBASED_CR8_LOAD_EXITING	|				\
99 	 PROCBASED_CR8_STORE_EXITING)
100 #define	PROCBASED_CTLS_ZERO_SETTING	\
101 	(PROCBASED_CR3_LOAD_EXITING |	\
102 	PROCBASED_CR3_STORE_EXITING |	\
103 	PROCBASED_IO_BITMAPS)
104 
105 #define	PROCBASED_CTLS2_ONE_SETTING	PROCBASED2_ENABLE_EPT
106 #define	PROCBASED_CTLS2_ZERO_SETTING	0
107 
108 #define	VM_EXIT_CTLS_ONE_SETTING					\
109 	(VM_EXIT_SAVE_DEBUG_CONTROLS		|			\
110 	VM_EXIT_HOST_LMA			|			\
111 	VM_EXIT_SAVE_EFER			|			\
112 	VM_EXIT_LOAD_EFER			|			\
113 	VM_EXIT_ACKNOWLEDGE_INTERRUPT)
114 
115 #define	VM_EXIT_CTLS_ZERO_SETTING	0
116 
117 #define	VM_ENTRY_CTLS_ONE_SETTING					\
118 	(VM_ENTRY_LOAD_DEBUG_CONTROLS		|			\
119 	VM_ENTRY_LOAD_EFER)
120 
121 #define	VM_ENTRY_CTLS_ZERO_SETTING					\
122 	(VM_ENTRY_INTO_SMM			|			\
123 	VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
124 
125 #define	HANDLED		1
126 #define	UNHANDLED	0
127 
128 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
129 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
130 
131 bool vmx_have_msr_tsc_aux;
132 
133 SYSCTL_DECL(_hw_vmm);
134 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
135     NULL);
136 
137 int vmxon_enabled[MAXCPU];
138 static uint8_t *vmxon_region;
139 
140 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
141 static uint32_t exit_ctls, entry_ctls;
142 
143 static uint64_t cr0_ones_mask, cr0_zeros_mask;
144 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
145 	     &cr0_ones_mask, 0, NULL);
146 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
147 	     &cr0_zeros_mask, 0, NULL);
148 
149 static uint64_t cr4_ones_mask, cr4_zeros_mask;
150 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
151 	     &cr4_ones_mask, 0, NULL);
152 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
153 	     &cr4_zeros_mask, 0, NULL);
154 
155 static int vmx_initialized;
156 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
157 	   &vmx_initialized, 0, "Intel VMX initialized");
158 
159 /*
160  * Optional capabilities
161  */
162 static SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap,
163     CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
164     NULL);
165 
166 static int cap_halt_exit;
167 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
168     "HLT triggers a VM-exit");
169 
170 static int cap_pause_exit;
171 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
172     0, "PAUSE triggers a VM-exit");
173 
174 static int cap_wbinvd_exit;
175 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, wbinvd_exit, CTLFLAG_RD, &cap_wbinvd_exit,
176     0, "WBINVD triggers a VM-exit");
177 
178 static int cap_rdpid;
179 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, rdpid, CTLFLAG_RD, &cap_rdpid, 0,
180     "Guests are allowed to use RDPID");
181 
182 static int cap_rdtscp;
183 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, rdtscp, CTLFLAG_RD, &cap_rdtscp, 0,
184     "Guests are allowed to use RDTSCP");
185 
186 static int cap_unrestricted_guest;
187 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
188     &cap_unrestricted_guest, 0, "Unrestricted guests");
189 
190 static int cap_monitor_trap;
191 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
192     &cap_monitor_trap, 0, "Monitor trap flag");
193 
194 static int cap_invpcid;
195 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
196     0, "Guests are allowed to use INVPCID");
197 
198 static int tpr_shadowing;
199 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, tpr_shadowing, CTLFLAG_RD,
200     &tpr_shadowing, 0, "TPR shadowing support");
201 
202 static int virtual_interrupt_delivery;
203 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
204     &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
205 
206 static int posted_interrupts;
207 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
208     &posted_interrupts, 0, "APICv posted interrupt support");
209 
210 static int pirvec = -1;
211 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
212     &pirvec, 0, "APICv posted interrupt vector");
213 
214 static struct unrhdr *vpid_unr;
215 static u_int vpid_alloc_failed;
216 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
217 	    &vpid_alloc_failed, 0, NULL);
218 
219 int guest_l1d_flush;
220 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush, CTLFLAG_RD,
221     &guest_l1d_flush, 0, NULL);
222 int guest_l1d_flush_sw;
223 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, l1d_flush_sw, CTLFLAG_RD,
224     &guest_l1d_flush_sw, 0, NULL);
225 
226 static struct msr_entry msr_load_list[1] __aligned(16);
227 
228 /*
229  * The definitions of SDT probes for VMX.
230  */
231 
232 SDT_PROBE_DEFINE3(vmm, vmx, exit, entry,
233     "struct vmx *", "int", "struct vm_exit *");
234 
235 SDT_PROBE_DEFINE4(vmm, vmx, exit, taskswitch,
236     "struct vmx *", "int", "struct vm_exit *", "struct vm_task_switch *");
237 
238 SDT_PROBE_DEFINE4(vmm, vmx, exit, craccess,
239     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
240 
241 SDT_PROBE_DEFINE4(vmm, vmx, exit, rdmsr,
242     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
243 
244 SDT_PROBE_DEFINE5(vmm, vmx, exit, wrmsr,
245     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "uint64_t");
246 
247 SDT_PROBE_DEFINE3(vmm, vmx, exit, halt,
248     "struct vmx *", "int", "struct vm_exit *");
249 
250 SDT_PROBE_DEFINE3(vmm, vmx, exit, mtrap,
251     "struct vmx *", "int", "struct vm_exit *");
252 
253 SDT_PROBE_DEFINE3(vmm, vmx, exit, pause,
254     "struct vmx *", "int", "struct vm_exit *");
255 
256 SDT_PROBE_DEFINE3(vmm, vmx, exit, intrwindow,
257     "struct vmx *", "int", "struct vm_exit *");
258 
259 SDT_PROBE_DEFINE4(vmm, vmx, exit, interrupt,
260     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
261 
262 SDT_PROBE_DEFINE3(vmm, vmx, exit, nmiwindow,
263     "struct vmx *", "int", "struct vm_exit *");
264 
265 SDT_PROBE_DEFINE3(vmm, vmx, exit, inout,
266     "struct vmx *", "int", "struct vm_exit *");
267 
268 SDT_PROBE_DEFINE3(vmm, vmx, exit, cpuid,
269     "struct vmx *", "int", "struct vm_exit *");
270 
271 SDT_PROBE_DEFINE5(vmm, vmx, exit, exception,
272     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "int");
273 
274 SDT_PROBE_DEFINE5(vmm, vmx, exit, nestedfault,
275     "struct vmx *", "int", "struct vm_exit *", "uint64_t", "uint64_t");
276 
277 SDT_PROBE_DEFINE4(vmm, vmx, exit, mmiofault,
278     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
279 
280 SDT_PROBE_DEFINE3(vmm, vmx, exit, eoi,
281     "struct vmx *", "int", "struct vm_exit *");
282 
283 SDT_PROBE_DEFINE3(vmm, vmx, exit, apicaccess,
284     "struct vmx *", "int", "struct vm_exit *");
285 
286 SDT_PROBE_DEFINE4(vmm, vmx, exit, apicwrite,
287     "struct vmx *", "int", "struct vm_exit *", "struct vlapic *");
288 
289 SDT_PROBE_DEFINE3(vmm, vmx, exit, xsetbv,
290     "struct vmx *", "int", "struct vm_exit *");
291 
292 SDT_PROBE_DEFINE3(vmm, vmx, exit, monitor,
293     "struct vmx *", "int", "struct vm_exit *");
294 
295 SDT_PROBE_DEFINE3(vmm, vmx, exit, mwait,
296     "struct vmx *", "int", "struct vm_exit *");
297 
298 SDT_PROBE_DEFINE3(vmm, vmx, exit, vminsn,
299     "struct vmx *", "int", "struct vm_exit *");
300 
301 SDT_PROBE_DEFINE4(vmm, vmx, exit, unknown,
302     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
303 
304 SDT_PROBE_DEFINE4(vmm, vmx, exit, return,
305     "struct vmx *", "int", "struct vm_exit *", "int");
306 
307 /*
308  * Use the last page below 4GB as the APIC access address. This address is
309  * occupied by the boot firmware so it is guaranteed that it will not conflict
310  * with a page in system memory.
311  */
312 #define	APIC_ACCESS_ADDRESS	0xFFFFF000
313 
314 static int vmx_getdesc(void *vcpui, int reg, struct seg_desc *desc);
315 static int vmx_getreg(void *vcpui, int reg, uint64_t *retval);
316 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
317 static void vmx_inject_pir(struct vlapic *vlapic);
318 #ifdef BHYVE_SNAPSHOT
319 static int vmx_restore_tsc(void *vcpui, uint64_t now);
320 #endif
321 
322 static inline bool
323 host_has_rdpid(void)
324 {
325 	return ((cpu_stdext_feature2 & CPUID_STDEXT2_RDPID) != 0);
326 }
327 
328 static inline bool
329 host_has_rdtscp(void)
330 {
331 	return ((amd_feature & AMDID_RDTSCP) != 0);
332 }
333 
334 #ifdef KTR
335 static const char *
336 exit_reason_to_str(int reason)
337 {
338 	static char reasonbuf[32];
339 
340 	switch (reason) {
341 	case EXIT_REASON_EXCEPTION:
342 		return "exception";
343 	case EXIT_REASON_EXT_INTR:
344 		return "extint";
345 	case EXIT_REASON_TRIPLE_FAULT:
346 		return "triplefault";
347 	case EXIT_REASON_INIT:
348 		return "init";
349 	case EXIT_REASON_SIPI:
350 		return "sipi";
351 	case EXIT_REASON_IO_SMI:
352 		return "iosmi";
353 	case EXIT_REASON_SMI:
354 		return "smi";
355 	case EXIT_REASON_INTR_WINDOW:
356 		return "intrwindow";
357 	case EXIT_REASON_NMI_WINDOW:
358 		return "nmiwindow";
359 	case EXIT_REASON_TASK_SWITCH:
360 		return "taskswitch";
361 	case EXIT_REASON_CPUID:
362 		return "cpuid";
363 	case EXIT_REASON_GETSEC:
364 		return "getsec";
365 	case EXIT_REASON_HLT:
366 		return "hlt";
367 	case EXIT_REASON_INVD:
368 		return "invd";
369 	case EXIT_REASON_INVLPG:
370 		return "invlpg";
371 	case EXIT_REASON_RDPMC:
372 		return "rdpmc";
373 	case EXIT_REASON_RDTSC:
374 		return "rdtsc";
375 	case EXIT_REASON_RSM:
376 		return "rsm";
377 	case EXIT_REASON_VMCALL:
378 		return "vmcall";
379 	case EXIT_REASON_VMCLEAR:
380 		return "vmclear";
381 	case EXIT_REASON_VMLAUNCH:
382 		return "vmlaunch";
383 	case EXIT_REASON_VMPTRLD:
384 		return "vmptrld";
385 	case EXIT_REASON_VMPTRST:
386 		return "vmptrst";
387 	case EXIT_REASON_VMREAD:
388 		return "vmread";
389 	case EXIT_REASON_VMRESUME:
390 		return "vmresume";
391 	case EXIT_REASON_VMWRITE:
392 		return "vmwrite";
393 	case EXIT_REASON_VMXOFF:
394 		return "vmxoff";
395 	case EXIT_REASON_VMXON:
396 		return "vmxon";
397 	case EXIT_REASON_CR_ACCESS:
398 		return "craccess";
399 	case EXIT_REASON_DR_ACCESS:
400 		return "draccess";
401 	case EXIT_REASON_INOUT:
402 		return "inout";
403 	case EXIT_REASON_RDMSR:
404 		return "rdmsr";
405 	case EXIT_REASON_WRMSR:
406 		return "wrmsr";
407 	case EXIT_REASON_INVAL_VMCS:
408 		return "invalvmcs";
409 	case EXIT_REASON_INVAL_MSR:
410 		return "invalmsr";
411 	case EXIT_REASON_MWAIT:
412 		return "mwait";
413 	case EXIT_REASON_MTF:
414 		return "mtf";
415 	case EXIT_REASON_MONITOR:
416 		return "monitor";
417 	case EXIT_REASON_PAUSE:
418 		return "pause";
419 	case EXIT_REASON_MCE_DURING_ENTRY:
420 		return "mce-during-entry";
421 	case EXIT_REASON_TPR:
422 		return "tpr";
423 	case EXIT_REASON_APIC_ACCESS:
424 		return "apic-access";
425 	case EXIT_REASON_GDTR_IDTR:
426 		return "gdtridtr";
427 	case EXIT_REASON_LDTR_TR:
428 		return "ldtrtr";
429 	case EXIT_REASON_EPT_FAULT:
430 		return "eptfault";
431 	case EXIT_REASON_EPT_MISCONFIG:
432 		return "eptmisconfig";
433 	case EXIT_REASON_INVEPT:
434 		return "invept";
435 	case EXIT_REASON_RDTSCP:
436 		return "rdtscp";
437 	case EXIT_REASON_VMX_PREEMPT:
438 		return "vmxpreempt";
439 	case EXIT_REASON_INVVPID:
440 		return "invvpid";
441 	case EXIT_REASON_WBINVD:
442 		return "wbinvd";
443 	case EXIT_REASON_XSETBV:
444 		return "xsetbv";
445 	case EXIT_REASON_APIC_WRITE:
446 		return "apic-write";
447 	default:
448 		snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
449 		return (reasonbuf);
450 	}
451 }
452 #endif	/* KTR */
453 
454 static int
455 vmx_allow_x2apic_msrs(struct vmx *vmx)
456 {
457 	int i, error;
458 
459 	error = 0;
460 
461 	/*
462 	 * Allow readonly access to the following x2APIC MSRs from the guest.
463 	 */
464 	error += guest_msr_ro(vmx, MSR_APIC_ID);
465 	error += guest_msr_ro(vmx, MSR_APIC_VERSION);
466 	error += guest_msr_ro(vmx, MSR_APIC_LDR);
467 	error += guest_msr_ro(vmx, MSR_APIC_SVR);
468 
469 	for (i = 0; i < 8; i++)
470 		error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
471 
472 	for (i = 0; i < 8; i++)
473 		error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
474 
475 	for (i = 0; i < 8; i++)
476 		error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
477 
478 	error += guest_msr_ro(vmx, MSR_APIC_ESR);
479 	error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
480 	error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
481 	error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
482 	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
483 	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
484 	error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
485 	error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
486 	error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
487 	error += guest_msr_ro(vmx, MSR_APIC_ICR);
488 
489 	/*
490 	 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
491 	 *
492 	 * These registers get special treatment described in the section
493 	 * "Virtualizing MSR-Based APIC Accesses".
494 	 */
495 	error += guest_msr_rw(vmx, MSR_APIC_TPR);
496 	error += guest_msr_rw(vmx, MSR_APIC_EOI);
497 	error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
498 
499 	return (error);
500 }
501 
502 u_long
503 vmx_fix_cr0(u_long cr0)
504 {
505 
506 	return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
507 }
508 
509 u_long
510 vmx_fix_cr4(u_long cr4)
511 {
512 
513 	return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
514 }
515 
516 static void
517 vpid_free(int vpid)
518 {
519 	if (vpid < 0 || vpid > 0xffff)
520 		panic("vpid_free: invalid vpid %d", vpid);
521 
522 	/*
523 	 * VPIDs [0,vm_maxcpu] are special and are not allocated from
524 	 * the unit number allocator.
525 	 */
526 
527 	if (vpid > vm_maxcpu)
528 		free_unr(vpid_unr, vpid);
529 }
530 
531 static uint16_t
532 vpid_alloc(int vcpuid)
533 {
534 	int x;
535 
536 	/*
537 	 * If the "enable vpid" execution control is not enabled then the
538 	 * VPID is required to be 0 for all vcpus.
539 	 */
540 	if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0)
541 		return (0);
542 
543 	/*
544 	 * Try to allocate a unique VPID for each from the unit number
545 	 * allocator.
546 	 */
547 	x = alloc_unr(vpid_unr);
548 
549 	if (x == -1) {
550 		atomic_add_int(&vpid_alloc_failed, 1);
551 
552 		/*
553 		 * If the unit number allocator does not have enough unique
554 		 * VPIDs then we need to allocate from the [1,vm_maxcpu] range.
555 		 *
556 		 * These VPIDs are not be unique across VMs but this does not
557 		 * affect correctness because the combined mappings are also
558 		 * tagged with the EP4TA which is unique for each VM.
559 		 *
560 		 * It is still sub-optimal because the invvpid will invalidate
561 		 * combined mappings for a particular VPID across all EP4TAs.
562 		 */
563 		return (vcpuid + 1);
564 	}
565 
566 	return (x);
567 }
568 
569 static void
570 vpid_init(void)
571 {
572 	/*
573 	 * VPID 0 is required when the "enable VPID" execution control is
574 	 * disabled.
575 	 *
576 	 * VPIDs [1,vm_maxcpu] are used as the "overflow namespace" when the
577 	 * unit number allocator does not have sufficient unique VPIDs to
578 	 * satisfy the allocation.
579 	 *
580 	 * The remaining VPIDs are managed by the unit number allocator.
581 	 */
582 	vpid_unr = new_unrhdr(vm_maxcpu + 1, 0xffff, NULL);
583 }
584 
585 static void
586 vmx_disable(void *arg __unused)
587 {
588 	struct invvpid_desc invvpid_desc = { 0 };
589 	struct invept_desc invept_desc = { 0 };
590 
591 	if (vmxon_enabled[curcpu]) {
592 		/*
593 		 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
594 		 *
595 		 * VMXON or VMXOFF are not required to invalidate any TLB
596 		 * caching structures. This prevents potential retention of
597 		 * cached information in the TLB between distinct VMX episodes.
598 		 */
599 		invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
600 		invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
601 		vmxoff();
602 	}
603 	load_cr4(rcr4() & ~CR4_VMXE);
604 }
605 
606 static int
607 vmx_modcleanup(void)
608 {
609 
610 	if (pirvec >= 0)
611 		lapic_ipi_free(pirvec);
612 
613 	if (vpid_unr != NULL) {
614 		delete_unrhdr(vpid_unr);
615 		vpid_unr = NULL;
616 	}
617 
618 	if (nmi_flush_l1d_sw == 1)
619 		nmi_flush_l1d_sw = 0;
620 
621 	smp_rendezvous(NULL, vmx_disable, NULL, NULL);
622 
623 	if (vmxon_region != NULL)
624 		kmem_free(vmxon_region, (mp_maxid + 1) * PAGE_SIZE);
625 
626 	return (0);
627 }
628 
629 static void
630 vmx_enable(void *arg __unused)
631 {
632 	int error;
633 	uint64_t feature_control;
634 
635 	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
636 	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
637 	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
638 		wrmsr(MSR_IA32_FEATURE_CONTROL,
639 		    feature_control | IA32_FEATURE_CONTROL_VMX_EN |
640 		    IA32_FEATURE_CONTROL_LOCK);
641 	}
642 
643 	load_cr4(rcr4() | CR4_VMXE);
644 
645 	*(uint32_t *)&vmxon_region[curcpu * PAGE_SIZE] = vmx_revision();
646 	error = vmxon(&vmxon_region[curcpu * PAGE_SIZE]);
647 	if (error == 0)
648 		vmxon_enabled[curcpu] = 1;
649 }
650 
651 static void
652 vmx_modresume(void)
653 {
654 
655 	if (vmxon_enabled[curcpu])
656 		vmxon(&vmxon_region[curcpu * PAGE_SIZE]);
657 }
658 
659 static int
660 vmx_modinit(int ipinum)
661 {
662 	int error;
663 	uint64_t basic, fixed0, fixed1, feature_control;
664 	uint32_t tmp, procbased2_vid_bits;
665 
666 	/* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
667 	if (!(cpu_feature2 & CPUID2_VMX)) {
668 		printf("vmx_modinit: processor does not support VMX "
669 		    "operation\n");
670 		return (ENXIO);
671 	}
672 
673 	/*
674 	 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
675 	 * are set (bits 0 and 2 respectively).
676 	 */
677 	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
678 	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
679 	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
680 		printf("vmx_modinit: VMX operation disabled by BIOS\n");
681 		return (ENXIO);
682 	}
683 
684 	/*
685 	 * Verify capabilities MSR_VMX_BASIC:
686 	 * - bit 54 indicates support for INS/OUTS decoding
687 	 */
688 	basic = rdmsr(MSR_VMX_BASIC);
689 	if ((basic & (1UL << 54)) == 0) {
690 		printf("vmx_modinit: processor does not support desired basic "
691 		    "capabilities\n");
692 		return (EINVAL);
693 	}
694 
695 	/* Check support for primary processor-based VM-execution controls */
696 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
697 			       MSR_VMX_TRUE_PROCBASED_CTLS,
698 			       PROCBASED_CTLS_ONE_SETTING,
699 			       PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
700 	if (error) {
701 		printf("vmx_modinit: processor does not support desired "
702 		    "primary processor-based controls\n");
703 		return (error);
704 	}
705 
706 	/* Clear the processor-based ctl bits that are set on demand */
707 	procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
708 
709 	/* Check support for secondary processor-based VM-execution controls */
710 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
711 			       MSR_VMX_PROCBASED_CTLS2,
712 			       PROCBASED_CTLS2_ONE_SETTING,
713 			       PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
714 	if (error) {
715 		printf("vmx_modinit: processor does not support desired "
716 		    "secondary processor-based controls\n");
717 		return (error);
718 	}
719 
720 	/* Check support for VPID */
721 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
722 			       PROCBASED2_ENABLE_VPID, 0, &tmp);
723 	if (error == 0)
724 		procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
725 
726 	/* Check support for pin-based VM-execution controls */
727 	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
728 			       MSR_VMX_TRUE_PINBASED_CTLS,
729 			       PINBASED_CTLS_ONE_SETTING,
730 			       PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
731 	if (error) {
732 		printf("vmx_modinit: processor does not support desired "
733 		    "pin-based controls\n");
734 		return (error);
735 	}
736 
737 	/* Check support for VM-exit controls */
738 	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
739 			       VM_EXIT_CTLS_ONE_SETTING,
740 			       VM_EXIT_CTLS_ZERO_SETTING,
741 			       &exit_ctls);
742 	if (error) {
743 		printf("vmx_modinit: processor does not support desired "
744 		    "exit controls\n");
745 		return (error);
746 	}
747 
748 	/* Check support for VM-entry controls */
749 	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
750 	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
751 	    &entry_ctls);
752 	if (error) {
753 		printf("vmx_modinit: processor does not support desired "
754 		    "entry controls\n");
755 		return (error);
756 	}
757 
758 	/*
759 	 * Check support for optional features by testing them
760 	 * as individual bits
761 	 */
762 	cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
763 					MSR_VMX_TRUE_PROCBASED_CTLS,
764 					PROCBASED_HLT_EXITING, 0,
765 					&tmp) == 0);
766 
767 	cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
768 					MSR_VMX_PROCBASED_CTLS,
769 					PROCBASED_MTF, 0,
770 					&tmp) == 0);
771 
772 	cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
773 					 MSR_VMX_TRUE_PROCBASED_CTLS,
774 					 PROCBASED_PAUSE_EXITING, 0,
775 					 &tmp) == 0);
776 
777 	cap_wbinvd_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
778 					MSR_VMX_PROCBASED_CTLS2,
779 					PROCBASED2_WBINVD_EXITING,
780 					0,
781 					&tmp) == 0);
782 
783 	/*
784 	 * Check support for RDPID and/or RDTSCP.
785 	 *
786 	 * Support a pass-through-based implementation of these via the
787 	 * "enable RDTSCP" VM-execution control and the "RDTSC exiting"
788 	 * VM-execution control.
789 	 *
790 	 * The "enable RDTSCP" VM-execution control applies to both RDPID
791 	 * and RDTSCP (see SDM volume 3, section 25.3, "Changes to
792 	 * Instruction Behavior in VMX Non-root operation"); this is why
793 	 * only this VM-execution control needs to be enabled in order to
794 	 * enable passing through whichever of RDPID and/or RDTSCP are
795 	 * supported by the host.
796 	 *
797 	 * The "RDTSC exiting" VM-execution control applies to both RDTSC
798 	 * and RDTSCP (again, per SDM volume 3, section 25.3), and is
799 	 * already set up for RDTSC and RDTSCP pass-through by the current
800 	 * implementation of RDTSC.
801 	 *
802 	 * Although RDPID and RDTSCP are optional capabilities, since there
803 	 * does not currently seem to be a use case for enabling/disabling
804 	 * these via libvmmapi, choose not to support this and, instead,
805 	 * just statically always enable or always disable this support
806 	 * across all vCPUs on all VMs. (Note that there may be some
807 	 * complications to providing this functionality, e.g., the MSR
808 	 * bitmap is currently per-VM rather than per-vCPU while the
809 	 * capability API wants to be able to control capabilities on a
810 	 * per-vCPU basis).
811 	 */
812 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
813 			       MSR_VMX_PROCBASED_CTLS2,
814 			       PROCBASED2_ENABLE_RDTSCP, 0, &tmp);
815 	cap_rdpid = error == 0 && host_has_rdpid();
816 	cap_rdtscp = error == 0 && host_has_rdtscp();
817 	if (cap_rdpid || cap_rdtscp) {
818 		procbased_ctls2 |= PROCBASED2_ENABLE_RDTSCP;
819 		vmx_have_msr_tsc_aux = true;
820 	}
821 
822 	cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
823 					MSR_VMX_PROCBASED_CTLS2,
824 					PROCBASED2_UNRESTRICTED_GUEST, 0,
825 				        &tmp) == 0);
826 
827 	cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
828 	    MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
829 	    &tmp) == 0);
830 
831 	/*
832 	 * Check support for TPR shadow.
833 	 */
834 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
835 	    MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
836 	    &tmp);
837 	if (error == 0) {
838 		tpr_shadowing = 1;
839 		TUNABLE_INT_FETCH("hw.vmm.vmx.use_tpr_shadowing",
840 		    &tpr_shadowing);
841 	}
842 
843 	if (tpr_shadowing) {
844 		procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
845 		procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
846 		procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
847 	}
848 
849 	/*
850 	 * Check support for virtual interrupt delivery.
851 	 */
852 	procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
853 	    PROCBASED2_VIRTUALIZE_X2APIC_MODE |
854 	    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
855 	    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
856 
857 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
858 	    procbased2_vid_bits, 0, &tmp);
859 	if (error == 0 && tpr_shadowing) {
860 		virtual_interrupt_delivery = 1;
861 		TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
862 		    &virtual_interrupt_delivery);
863 	}
864 
865 	if (virtual_interrupt_delivery) {
866 		procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
867 		procbased_ctls2 |= procbased2_vid_bits;
868 		procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
869 
870 		/*
871 		 * Check for Posted Interrupts only if Virtual Interrupt
872 		 * Delivery is enabled.
873 		 */
874 		error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
875 		    MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
876 		    &tmp);
877 		if (error == 0) {
878 			pirvec = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
879 			    &IDTVEC(justreturn));
880 			if (pirvec < 0) {
881 				if (bootverbose) {
882 					printf("vmx_modinit: unable to "
883 					    "allocate posted interrupt "
884 					    "vector\n");
885 				}
886 			} else {
887 				posted_interrupts = 1;
888 				TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
889 				    &posted_interrupts);
890 			}
891 		}
892 	}
893 
894 	if (posted_interrupts)
895 		    pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
896 
897 	/* Initialize EPT */
898 	error = ept_init(ipinum);
899 	if (error) {
900 		printf("vmx_modinit: ept initialization failed (%d)\n", error);
901 		return (error);
902 	}
903 
904 	guest_l1d_flush = (cpu_ia32_arch_caps &
905 	    IA32_ARCH_CAP_SKIP_L1DFL_VMENTRY) == 0;
906 	TUNABLE_INT_FETCH("hw.vmm.l1d_flush", &guest_l1d_flush);
907 
908 	/*
909 	 * L1D cache flush is enabled.  Use IA32_FLUSH_CMD MSR when
910 	 * available.  Otherwise fall back to the software flush
911 	 * method which loads enough data from the kernel text to
912 	 * flush existing L1D content, both on VMX entry and on NMI
913 	 * return.
914 	 */
915 	if (guest_l1d_flush) {
916 		if ((cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) == 0) {
917 			guest_l1d_flush_sw = 1;
918 			TUNABLE_INT_FETCH("hw.vmm.l1d_flush_sw",
919 			    &guest_l1d_flush_sw);
920 		}
921 		if (guest_l1d_flush_sw) {
922 			if (nmi_flush_l1d_sw <= 1)
923 				nmi_flush_l1d_sw = 1;
924 		} else {
925 			msr_load_list[0].index = MSR_IA32_FLUSH_CMD;
926 			msr_load_list[0].val = IA32_FLUSH_CMD_L1D;
927 		}
928 	}
929 
930 	/*
931 	 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
932 	 */
933 	fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
934 	fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
935 	cr0_ones_mask = fixed0 & fixed1;
936 	cr0_zeros_mask = ~fixed0 & ~fixed1;
937 
938 	/*
939 	 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
940 	 * if unrestricted guest execution is allowed.
941 	 */
942 	if (cap_unrestricted_guest)
943 		cr0_ones_mask &= ~(CR0_PG | CR0_PE);
944 
945 	/*
946 	 * Do not allow the guest to set CR0_NW or CR0_CD.
947 	 */
948 	cr0_zeros_mask |= (CR0_NW | CR0_CD);
949 
950 	fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
951 	fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
952 	cr4_ones_mask = fixed0 & fixed1;
953 	cr4_zeros_mask = ~fixed0 & ~fixed1;
954 
955 	vpid_init();
956 
957 	vmx_msr_init();
958 
959 	/* enable VMX operation */
960 	vmxon_region = kmem_malloc((mp_maxid + 1) * PAGE_SIZE,
961 	    M_WAITOK | M_ZERO);
962 	smp_rendezvous(NULL, vmx_enable, NULL, NULL);
963 
964 	vmx_initialized = 1;
965 
966 	return (0);
967 }
968 
969 static void
970 vmx_trigger_hostintr(int vector)
971 {
972 	uintptr_t func;
973 	struct gate_descriptor *gd;
974 
975 	gd = &idt[vector];
976 
977 	KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
978 	    "invalid vector %d", vector));
979 	KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
980 	    vector));
981 	KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
982 	    "has invalid type %d", vector, gd->gd_type));
983 	KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
984 	    "has invalid dpl %d", vector, gd->gd_dpl));
985 	KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
986 	    "for vector %d has invalid selector %d", vector, gd->gd_selector));
987 	KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
988 	    "IST %d", vector, gd->gd_ist));
989 
990 	func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
991 	vmx_call_isr(func);
992 }
993 
994 static int
995 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
996 {
997 	int error, mask_ident, shadow_ident;
998 	uint64_t mask_value;
999 
1000 	if (which != 0 && which != 4)
1001 		panic("vmx_setup_cr_shadow: unknown cr%d", which);
1002 
1003 	if (which == 0) {
1004 		mask_ident = VMCS_CR0_MASK;
1005 		mask_value = cr0_ones_mask | cr0_zeros_mask;
1006 		shadow_ident = VMCS_CR0_SHADOW;
1007 	} else {
1008 		mask_ident = VMCS_CR4_MASK;
1009 		mask_value = cr4_ones_mask | cr4_zeros_mask;
1010 		shadow_ident = VMCS_CR4_SHADOW;
1011 	}
1012 
1013 	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
1014 	if (error)
1015 		return (error);
1016 
1017 	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
1018 	if (error)
1019 		return (error);
1020 
1021 	return (0);
1022 }
1023 #define	vmx_setup_cr0_shadow(vmcs,init)	vmx_setup_cr_shadow(0, (vmcs), (init))
1024 #define	vmx_setup_cr4_shadow(vmcs,init)	vmx_setup_cr_shadow(4, (vmcs), (init))
1025 
1026 static void *
1027 vmx_init(struct vm *vm, pmap_t pmap)
1028 {
1029 	int error __diagused;
1030 	struct vmx *vmx;
1031 
1032 	vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
1033 	vmx->vm = vm;
1034 
1035 	vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pmltop));
1036 
1037 	/*
1038 	 * Clean up EPTP-tagged guest physical and combined mappings
1039 	 *
1040 	 * VMX transitions are not required to invalidate any guest physical
1041 	 * mappings. So, it may be possible for stale guest physical mappings
1042 	 * to be present in the processor TLBs.
1043 	 *
1044 	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
1045 	 */
1046 	ept_invalidate_mappings(vmx->eptp);
1047 
1048 	vmx->msr_bitmap = malloc_aligned(PAGE_SIZE, PAGE_SIZE, M_VMX,
1049 	    M_WAITOK | M_ZERO);
1050 	msr_bitmap_initialize(vmx->msr_bitmap);
1051 
1052 	/*
1053 	 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
1054 	 * The guest FSBASE and GSBASE are saved and restored during
1055 	 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
1056 	 * always restored from the vmcs host state area on vm-exit.
1057 	 *
1058 	 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
1059 	 * how they are saved/restored so can be directly accessed by the
1060 	 * guest.
1061 	 *
1062 	 * MSR_EFER is saved and restored in the guest VMCS area on a
1063 	 * VM exit and entry respectively. It is also restored from the
1064 	 * host VMCS area on a VM exit.
1065 	 *
1066 	 * The TSC MSR is exposed read-only. Writes are disallowed as
1067 	 * that will impact the host TSC.  If the guest does a write
1068 	 * the "use TSC offsetting" execution control is enabled and the
1069 	 * difference between the host TSC and the guest TSC is written
1070 	 * into the TSC offset in the VMCS.
1071 	 *
1072 	 * Guest TSC_AUX support is enabled if any of guest RDPID and/or
1073 	 * guest RDTSCP support are enabled (since, as per Table 2-2 in SDM
1074 	 * volume 4, TSC_AUX is supported if any of RDPID and/or RDTSCP are
1075 	 * supported). If guest TSC_AUX support is enabled, TSC_AUX is
1076 	 * exposed read-only so that the VMM can do one fewer MSR read per
1077 	 * exit than if this register were exposed read-write; the guest
1078 	 * restore value can be updated during guest writes (expected to be
1079 	 * rare) instead of during all exits (common).
1080 	 */
1081 	if (guest_msr_rw(vmx, MSR_GSBASE) ||
1082 	    guest_msr_rw(vmx, MSR_FSBASE) ||
1083 	    guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
1084 	    guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
1085 	    guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
1086 	    guest_msr_rw(vmx, MSR_EFER) ||
1087 	    guest_msr_ro(vmx, MSR_TSC) ||
1088 	    ((cap_rdpid || cap_rdtscp) && guest_msr_ro(vmx, MSR_TSC_AUX)))
1089 		panic("vmx_init: error setting guest msr access");
1090 
1091 	if (virtual_interrupt_delivery) {
1092 		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
1093 		    APIC_ACCESS_ADDRESS);
1094 		/* XXX this should really return an error to the caller */
1095 		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
1096 	}
1097 
1098 	vmx->pmap = pmap;
1099 	return (vmx);
1100 }
1101 
1102 static void *
1103 vmx_vcpu_init(void *vmi, struct vcpu *vcpu1, int vcpuid)
1104 {
1105 	struct vmx *vmx = vmi;
1106 	struct vmcs *vmcs;
1107 	struct vmx_vcpu *vcpu;
1108 	uint32_t exc_bitmap;
1109 	uint16_t vpid;
1110 	int error;
1111 
1112 	vpid = vpid_alloc(vcpuid);
1113 
1114 	vcpu = malloc(sizeof(*vcpu), M_VMX, M_WAITOK | M_ZERO);
1115 	vcpu->vmx = vmx;
1116 	vcpu->vcpu = vcpu1;
1117 	vcpu->vcpuid = vcpuid;
1118 	vcpu->vmcs = malloc_aligned(sizeof(*vmcs), PAGE_SIZE, M_VMX,
1119 	    M_WAITOK | M_ZERO);
1120 	vcpu->apic_page = malloc_aligned(PAGE_SIZE, PAGE_SIZE, M_VMX,
1121 	    M_WAITOK | M_ZERO);
1122 	vcpu->pir_desc = malloc_aligned(sizeof(*vcpu->pir_desc), 64, M_VMX,
1123 	    M_WAITOK | M_ZERO);
1124 
1125 	vmcs = vcpu->vmcs;
1126 	vmcs->identifier = vmx_revision();
1127 	error = vmclear(vmcs);
1128 	if (error != 0) {
1129 		panic("vmx_init: vmclear error %d on vcpu %d\n",
1130 		    error, vcpuid);
1131 	}
1132 
1133 	vmx_msr_guest_init(vmx, vcpu);
1134 
1135 	error = vmcs_init(vmcs);
1136 	KASSERT(error == 0, ("vmcs_init error %d", error));
1137 
1138 	VMPTRLD(vmcs);
1139 	error = 0;
1140 	error += vmwrite(VMCS_HOST_RSP, (u_long)&vcpu->ctx);
1141 	error += vmwrite(VMCS_EPTP, vmx->eptp);
1142 	error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
1143 	error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
1144 	if (vcpu_trap_wbinvd(vcpu->vcpu)) {
1145 		KASSERT(cap_wbinvd_exit, ("WBINVD trap not available"));
1146 		procbased_ctls2 |= PROCBASED2_WBINVD_EXITING;
1147 	}
1148 	error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
1149 	error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
1150 	error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
1151 	error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
1152 	error += vmwrite(VMCS_VPID, vpid);
1153 
1154 	if (guest_l1d_flush && !guest_l1d_flush_sw) {
1155 		vmcs_write(VMCS_ENTRY_MSR_LOAD, pmap_kextract(
1156 			(vm_offset_t)&msr_load_list[0]));
1157 		vmcs_write(VMCS_ENTRY_MSR_LOAD_COUNT,
1158 		    nitems(msr_load_list));
1159 		vmcs_write(VMCS_EXIT_MSR_STORE, 0);
1160 		vmcs_write(VMCS_EXIT_MSR_STORE_COUNT, 0);
1161 	}
1162 
1163 	/* exception bitmap */
1164 	if (vcpu_trace_exceptions(vcpu->vcpu))
1165 		exc_bitmap = 0xffffffff;
1166 	else
1167 		exc_bitmap = 1 << IDT_MC;
1168 	error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
1169 
1170 	vcpu->ctx.guest_dr6 = DBREG_DR6_RESERVED1;
1171 	error += vmwrite(VMCS_GUEST_DR7, DBREG_DR7_RESERVED1);
1172 
1173 	if (tpr_shadowing) {
1174 		error += vmwrite(VMCS_VIRTUAL_APIC, vtophys(vcpu->apic_page));
1175 	}
1176 
1177 	if (virtual_interrupt_delivery) {
1178 		error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
1179 		error += vmwrite(VMCS_EOI_EXIT0, 0);
1180 		error += vmwrite(VMCS_EOI_EXIT1, 0);
1181 		error += vmwrite(VMCS_EOI_EXIT2, 0);
1182 		error += vmwrite(VMCS_EOI_EXIT3, 0);
1183 	}
1184 	if (posted_interrupts) {
1185 		error += vmwrite(VMCS_PIR_VECTOR, pirvec);
1186 		error += vmwrite(VMCS_PIR_DESC, vtophys(vcpu->pir_desc));
1187 	}
1188 	VMCLEAR(vmcs);
1189 	KASSERT(error == 0, ("vmx_init: error customizing the vmcs"));
1190 
1191 	vcpu->cap.set = 0;
1192 	vcpu->cap.set |= cap_rdpid != 0 ? 1 << VM_CAP_RDPID : 0;
1193 	vcpu->cap.set |= cap_rdtscp != 0 ? 1 << VM_CAP_RDTSCP : 0;
1194 	vcpu->cap.proc_ctls = procbased_ctls;
1195 	vcpu->cap.proc_ctls2 = procbased_ctls2;
1196 	vcpu->cap.exc_bitmap = exc_bitmap;
1197 
1198 	vcpu->state.nextrip = ~0;
1199 	vcpu->state.lastcpu = NOCPU;
1200 	vcpu->state.vpid = vpid;
1201 
1202 	/*
1203 	 * Set up the CR0/4 shadows, and init the read shadow
1204 	 * to the power-on register value from the Intel Sys Arch.
1205 	 *  CR0 - 0x60000010
1206 	 *  CR4 - 0
1207 	 */
1208 	error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
1209 	if (error != 0)
1210 		panic("vmx_setup_cr0_shadow %d", error);
1211 
1212 	error = vmx_setup_cr4_shadow(vmcs, 0);
1213 	if (error != 0)
1214 		panic("vmx_setup_cr4_shadow %d", error);
1215 
1216 	vcpu->ctx.pmap = vmx->pmap;
1217 
1218 	return (vcpu);
1219 }
1220 
1221 static int
1222 vmx_handle_cpuid(struct vmx_vcpu *vcpu, struct vmxctx *vmxctx)
1223 {
1224 	int handled;
1225 
1226 	handled = x86_emulate_cpuid(vcpu->vcpu, (uint64_t *)&vmxctx->guest_rax,
1227 	    (uint64_t *)&vmxctx->guest_rbx, (uint64_t *)&vmxctx->guest_rcx,
1228 	    (uint64_t *)&vmxctx->guest_rdx);
1229 	return (handled);
1230 }
1231 
1232 static __inline void
1233 vmx_run_trace(struct vmx_vcpu *vcpu)
1234 {
1235 	VMX_CTR1(vcpu, "Resume execution at %#lx", vmcs_guest_rip());
1236 }
1237 
1238 static __inline void
1239 vmx_exit_trace(struct vmx_vcpu *vcpu, uint64_t rip, uint32_t exit_reason,
1240     int handled)
1241 {
1242 	VMX_CTR3(vcpu, "%s %s vmexit at 0x%0lx",
1243 		 handled ? "handled" : "unhandled",
1244 		 exit_reason_to_str(exit_reason), rip);
1245 }
1246 
1247 static __inline void
1248 vmx_astpending_trace(struct vmx_vcpu *vcpu, uint64_t rip)
1249 {
1250 	VMX_CTR1(vcpu, "astpending vmexit at 0x%0lx", rip);
1251 }
1252 
1253 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1254 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1255 
1256 /*
1257  * Invalidate guest mappings identified by its vpid from the TLB.
1258  */
1259 static __inline void
1260 vmx_invvpid(struct vmx *vmx, struct vmx_vcpu *vcpu, pmap_t pmap, int running)
1261 {
1262 	struct vmxstate *vmxstate;
1263 	struct invvpid_desc invvpid_desc;
1264 
1265 	vmxstate = &vcpu->state;
1266 	if (vmxstate->vpid == 0)
1267 		return;
1268 
1269 	if (!running) {
1270 		/*
1271 		 * Set the 'lastcpu' to an invalid host cpu.
1272 		 *
1273 		 * This will invalidate TLB entries tagged with the vcpu's
1274 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
1275 		 */
1276 		vmxstate->lastcpu = NOCPU;
1277 		return;
1278 	}
1279 
1280 	KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1281 	    "critical section", __func__, vcpu->vcpuid));
1282 
1283 	/*
1284 	 * Invalidate all mappings tagged with 'vpid'
1285 	 *
1286 	 * We do this because this vcpu was executing on a different host
1287 	 * cpu when it last ran. We do not track whether it invalidated
1288 	 * mappings associated with its 'vpid' during that run. So we must
1289 	 * assume that the mappings associated with 'vpid' on 'curcpu' are
1290 	 * stale and invalidate them.
1291 	 *
1292 	 * Note that we incur this penalty only when the scheduler chooses to
1293 	 * move the thread associated with this vcpu between host cpus.
1294 	 *
1295 	 * Note also that this will invalidate mappings tagged with 'vpid'
1296 	 * for "all" EP4TAs.
1297 	 */
1298 	if (atomic_load_long(&pmap->pm_eptgen) == vmx->eptgen[curcpu]) {
1299 		invvpid_desc._res1 = 0;
1300 		invvpid_desc._res2 = 0;
1301 		invvpid_desc.vpid = vmxstate->vpid;
1302 		invvpid_desc.linear_addr = 0;
1303 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1304 		vmm_stat_incr(vcpu->vcpu, VCPU_INVVPID_DONE, 1);
1305 	} else {
1306 		/*
1307 		 * The invvpid can be skipped if an invept is going to
1308 		 * be performed before entering the guest. The invept
1309 		 * will invalidate combined mappings tagged with
1310 		 * 'vmx->eptp' for all vpids.
1311 		 */
1312 		vmm_stat_incr(vcpu->vcpu, VCPU_INVVPID_SAVED, 1);
1313 	}
1314 }
1315 
1316 static void
1317 vmx_set_pcpu_defaults(struct vmx *vmx, struct vmx_vcpu *vcpu, pmap_t pmap)
1318 {
1319 	struct vmxstate *vmxstate;
1320 
1321 	vmxstate = &vcpu->state;
1322 	if (vmxstate->lastcpu == curcpu)
1323 		return;
1324 
1325 	vmxstate->lastcpu = curcpu;
1326 
1327 	vmm_stat_incr(vcpu->vcpu, VCPU_MIGRATIONS, 1);
1328 
1329 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1330 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1331 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1332 	vmx_invvpid(vmx, vcpu, pmap, 1);
1333 }
1334 
1335 /*
1336  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1337  */
1338 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1339 
1340 static void __inline
1341 vmx_set_int_window_exiting(struct vmx_vcpu *vcpu)
1342 {
1343 
1344 	if ((vcpu->cap.proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1345 		vcpu->cap.proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1346 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1347 		VMX_CTR0(vcpu, "Enabling interrupt window exiting");
1348 	}
1349 }
1350 
1351 static void __inline
1352 vmx_clear_int_window_exiting(struct vmx_vcpu *vcpu)
1353 {
1354 
1355 	KASSERT((vcpu->cap.proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1356 	    ("intr_window_exiting not set: %#x", vcpu->cap.proc_ctls));
1357 	vcpu->cap.proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1358 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1359 	VMX_CTR0(vcpu, "Disabling interrupt window exiting");
1360 }
1361 
1362 static void __inline
1363 vmx_set_nmi_window_exiting(struct vmx_vcpu *vcpu)
1364 {
1365 
1366 	if ((vcpu->cap.proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1367 		vcpu->cap.proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1368 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1369 		VMX_CTR0(vcpu, "Enabling NMI window exiting");
1370 	}
1371 }
1372 
1373 static void __inline
1374 vmx_clear_nmi_window_exiting(struct vmx_vcpu *vcpu)
1375 {
1376 
1377 	KASSERT((vcpu->cap.proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1378 	    ("nmi_window_exiting not set %#x", vcpu->cap.proc_ctls));
1379 	vcpu->cap.proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1380 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1381 	VMX_CTR0(vcpu, "Disabling NMI window exiting");
1382 }
1383 
1384 int
1385 vmx_set_tsc_offset(struct vmx_vcpu *vcpu, uint64_t offset)
1386 {
1387 	int error;
1388 
1389 	if ((vcpu->cap.proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1390 		vcpu->cap.proc_ctls |= PROCBASED_TSC_OFFSET;
1391 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vcpu->cap.proc_ctls);
1392 		VMX_CTR0(vcpu, "Enabling TSC offsetting");
1393 	}
1394 
1395 	error = vmwrite(VMCS_TSC_OFFSET, offset);
1396 #ifdef BHYVE_SNAPSHOT
1397 	if (error == 0)
1398 		vm_set_tsc_offset(vcpu->vcpu, offset);
1399 #endif
1400 	return (error);
1401 }
1402 
1403 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1404 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1405 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1406 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1407 
1408 static void
1409 vmx_inject_nmi(struct vmx_vcpu *vcpu)
1410 {
1411 	uint32_t gi __diagused, info;
1412 
1413 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1414 	KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1415 	    "interruptibility-state %#x", gi));
1416 
1417 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1418 	KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1419 	    "VM-entry interruption information %#x", info));
1420 
1421 	/*
1422 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1423 	 * or the VMCS entry check will fail.
1424 	 */
1425 	info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1426 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1427 
1428 	VMX_CTR0(vcpu, "Injecting vNMI");
1429 
1430 	/* Clear the request */
1431 	vm_nmi_clear(vcpu->vcpu);
1432 }
1433 
1434 static void
1435 vmx_inject_interrupts(struct vmx_vcpu *vcpu, struct vlapic *vlapic,
1436     uint64_t guestrip)
1437 {
1438 	int vector, need_nmi_exiting, extint_pending;
1439 	uint64_t rflags, entryinfo;
1440 	uint32_t gi, info;
1441 
1442 	if (vcpu->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 	default:
3638 		break;
3639 	}
3640 
3641 	if (retval)
3642 		return (retval);
3643 
3644 	if (pptr != NULL) {
3645 		if (val) {
3646 			baseval |= flag;
3647 		} else {
3648 			baseval &= ~flag;
3649 		}
3650 		VMPTRLD(vmcs);
3651 		error = vmwrite(reg, baseval);
3652 		VMCLEAR(vmcs);
3653 
3654 		if (error)
3655 			return (error);
3656 
3657 		/*
3658 		 * Update optional stored flags, and record
3659 		 * setting
3660 		 */
3661 		*pptr = baseval;
3662 	}
3663 
3664 	if (val) {
3665 		vcpu->cap.set |= (1 << type);
3666 	} else {
3667 		vcpu->cap.set &= ~(1 << type);
3668 	}
3669 
3670 	return (0);
3671 }
3672 
3673 static struct vmspace *
3674 vmx_vmspace_alloc(vm_offset_t min, vm_offset_t max)
3675 {
3676 	return (ept_vmspace_alloc(min, max));
3677 }
3678 
3679 static void
3680 vmx_vmspace_free(struct vmspace *vmspace)
3681 {
3682 	ept_vmspace_free(vmspace);
3683 }
3684 
3685 struct vlapic_vtx {
3686 	struct vlapic	vlapic;
3687 	struct pir_desc	*pir_desc;
3688 	struct vmx_vcpu	*vcpu;
3689 	u_int	pending_prio;
3690 };
3691 
3692 #define VPR_PRIO_BIT(vpr)	(1 << ((vpr) >> 4))
3693 
3694 #define	VMX_CTR_PIR(vlapic, pir_desc, notify, vector, level, msg)	\
3695 do {									\
3696 	VLAPIC_CTR2(vlapic, msg " assert %s-triggered vector %d",	\
3697 	    level ? "level" : "edge", vector);				\
3698 	VLAPIC_CTR1(vlapic, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3699 	VLAPIC_CTR1(vlapic, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3700 	VLAPIC_CTR1(vlapic, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3701 	VLAPIC_CTR1(vlapic, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3702 	VLAPIC_CTR1(vlapic, msg " notify: %s", notify ? "yes" : "no");	\
3703 } while (0)
3704 
3705 /*
3706  * vlapic->ops handlers that utilize the APICv hardware assist described in
3707  * Chapter 29 of the Intel SDM.
3708  */
3709 static int
3710 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3711 {
3712 	struct vlapic_vtx *vlapic_vtx;
3713 	struct pir_desc *pir_desc;
3714 	uint64_t mask;
3715 	int idx, notify = 0;
3716 
3717 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3718 	pir_desc = vlapic_vtx->pir_desc;
3719 
3720 	/*
3721 	 * Keep track of interrupt requests in the PIR descriptor. This is
3722 	 * because the virtual APIC page pointed to by the VMCS cannot be
3723 	 * modified if the vcpu is running.
3724 	 */
3725 	idx = vector / 64;
3726 	mask = 1UL << (vector % 64);
3727 	atomic_set_long(&pir_desc->pir[idx], mask);
3728 
3729 	/*
3730 	 * A notification is required whenever the 'pending' bit makes a
3731 	 * transition from 0->1.
3732 	 *
3733 	 * Even if the 'pending' bit is already asserted, notification about
3734 	 * the incoming interrupt may still be necessary.  For example, if a
3735 	 * vCPU is HLTed with a high PPR, a low priority interrupt would cause
3736 	 * the 0->1 'pending' transition with a notification, but the vCPU
3737 	 * would ignore the interrupt for the time being.  The same vCPU would
3738 	 * need to then be notified if a high-priority interrupt arrived which
3739 	 * satisfied the PPR.
3740 	 *
3741 	 * The priorities of interrupts injected while 'pending' is asserted
3742 	 * are tracked in a custom bitfield 'pending_prio'.  Should the
3743 	 * to-be-injected interrupt exceed the priorities already present, the
3744 	 * notification is sent.  The priorities recorded in 'pending_prio' are
3745 	 * cleared whenever the 'pending' bit makes another 0->1 transition.
3746 	 */
3747 	if (atomic_cmpset_long(&pir_desc->pending, 0, 1) != 0) {
3748 		notify = 1;
3749 		vlapic_vtx->pending_prio = 0;
3750 	} else {
3751 		const u_int old_prio = vlapic_vtx->pending_prio;
3752 		const u_int prio_bit = VPR_PRIO_BIT(vector & APIC_TPR_INT);
3753 
3754 		if ((old_prio & prio_bit) == 0 && prio_bit > old_prio) {
3755 			atomic_set_int(&vlapic_vtx->pending_prio, prio_bit);
3756 			notify = 1;
3757 		}
3758 	}
3759 
3760 	VMX_CTR_PIR(vlapic, pir_desc, notify, vector, level,
3761 	    "vmx_set_intr_ready");
3762 	return (notify);
3763 }
3764 
3765 static int
3766 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3767 {
3768 	struct vlapic_vtx *vlapic_vtx;
3769 	struct pir_desc *pir_desc;
3770 	struct LAPIC *lapic;
3771 	uint64_t pending, pirval;
3772 	uint8_t ppr, vpr, rvi;
3773 	struct vm_exit *vmexit;
3774 	int i;
3775 
3776 	/*
3777 	 * This function is only expected to be called from the 'HLT' exit
3778 	 * handler which does not care about the vector that is pending.
3779 	 */
3780 	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3781 
3782 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3783 	pir_desc = vlapic_vtx->pir_desc;
3784 	lapic = vlapic->apic_page;
3785 
3786 	/*
3787 	 * While a virtual interrupt may have already been
3788 	 * processed the actual delivery maybe pending the
3789 	 * interruptibility of the guest.  Recognize a pending
3790 	 * interrupt by reevaluating virtual interrupts
3791 	 * following Section 30.2.1 in the Intel SDM Volume 3.
3792 	 */
3793 	vmexit = vm_exitinfo(vlapic->vcpu);
3794 	KASSERT(vmexit->exitcode == VM_EXITCODE_HLT,
3795 	    ("vmx_pending_intr: exitcode not 'HLT'"));
3796 	rvi = vmexit->u.hlt.intr_status & APIC_TPR_INT;
3797 	ppr = lapic->ppr & APIC_TPR_INT;
3798 	if (rvi > ppr)
3799 		return (1);
3800 
3801 	pending = atomic_load_acq_long(&pir_desc->pending);
3802 	if (!pending)
3803 		return (0);
3804 
3805 	/*
3806 	 * If there is an interrupt pending then it will be recognized only
3807 	 * if its priority is greater than the processor priority.
3808 	 *
3809 	 * Special case: if the processor priority is zero then any pending
3810 	 * interrupt will be recognized.
3811 	 */
3812 	if (ppr == 0)
3813 		return (1);
3814 
3815 	VLAPIC_CTR1(vlapic, "HLT with non-zero PPR %d", lapic->ppr);
3816 
3817 	vpr = 0;
3818 	for (i = 3; i >= 0; i--) {
3819 		pirval = pir_desc->pir[i];
3820 		if (pirval != 0) {
3821 			vpr = (i * 64 + flsl(pirval) - 1) & APIC_TPR_INT;
3822 			break;
3823 		}
3824 	}
3825 
3826 	/*
3827 	 * If the highest-priority pending interrupt falls short of the
3828 	 * processor priority of this vCPU, ensure that 'pending_prio' does not
3829 	 * have any stale bits which would preclude a higher-priority interrupt
3830 	 * from incurring a notification later.
3831 	 */
3832 	if (vpr <= ppr) {
3833 		const u_int prio_bit = VPR_PRIO_BIT(vpr);
3834 		const u_int old = vlapic_vtx->pending_prio;
3835 
3836 		if (old > prio_bit && (old & prio_bit) == 0) {
3837 			vlapic_vtx->pending_prio = prio_bit;
3838 		}
3839 		return (0);
3840 	}
3841 	return (1);
3842 }
3843 
3844 static void
3845 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3846 {
3847 
3848 	panic("vmx_intr_accepted: not expected to be called");
3849 }
3850 
3851 static void
3852 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3853 {
3854 	struct vlapic_vtx *vlapic_vtx;
3855 	struct vmcs *vmcs;
3856 	uint64_t mask, val;
3857 
3858 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3859 	KASSERT(!vcpu_is_running(vlapic->vcpu, NULL),
3860 	    ("vmx_set_tmr: vcpu cannot be running"));
3861 
3862 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3863 	vmcs = vlapic_vtx->vcpu->vmcs;
3864 	mask = 1UL << (vector % 64);
3865 
3866 	VMPTRLD(vmcs);
3867 	val = vmcs_read(VMCS_EOI_EXIT(vector));
3868 	if (level)
3869 		val |= mask;
3870 	else
3871 		val &= ~mask;
3872 	vmcs_write(VMCS_EOI_EXIT(vector), val);
3873 	VMCLEAR(vmcs);
3874 }
3875 
3876 static void
3877 vmx_enable_x2apic_mode_ts(struct vlapic *vlapic)
3878 {
3879 	struct vlapic_vtx *vlapic_vtx;
3880 	struct vmx_vcpu *vcpu;
3881 	struct vmcs *vmcs;
3882 	uint32_t proc_ctls;
3883 
3884 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3885 	vcpu = vlapic_vtx->vcpu;
3886 	vmcs = vcpu->vmcs;
3887 
3888 	proc_ctls = vcpu->cap.proc_ctls;
3889 	proc_ctls &= ~PROCBASED_USE_TPR_SHADOW;
3890 	proc_ctls |= PROCBASED_CR8_LOAD_EXITING;
3891 	proc_ctls |= PROCBASED_CR8_STORE_EXITING;
3892 	vcpu->cap.proc_ctls = proc_ctls;
3893 
3894 	VMPTRLD(vmcs);
3895 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
3896 	VMCLEAR(vmcs);
3897 }
3898 
3899 static void
3900 vmx_enable_x2apic_mode_vid(struct vlapic *vlapic)
3901 {
3902 	struct vlapic_vtx *vlapic_vtx;
3903 	struct vmx *vmx;
3904 	struct vmx_vcpu *vcpu;
3905 	struct vmcs *vmcs;
3906 	uint32_t proc_ctls2;
3907 	int error __diagused;
3908 
3909 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3910 	vcpu = vlapic_vtx->vcpu;
3911 	vmx = vcpu->vmx;
3912 	vmcs = vcpu->vmcs;
3913 
3914 	proc_ctls2 = vcpu->cap.proc_ctls2;
3915 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3916 	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3917 
3918 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3919 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3920 	vcpu->cap.proc_ctls2 = proc_ctls2;
3921 
3922 	VMPTRLD(vmcs);
3923 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3924 	VMCLEAR(vmcs);
3925 
3926 	if (vlapic->vcpuid == 0) {
3927 		/*
3928 		 * The nested page table mappings are shared by all vcpus
3929 		 * so unmap the APIC access page just once.
3930 		 */
3931 		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3932 		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3933 		    __func__, error));
3934 
3935 		/*
3936 		 * The MSR bitmap is shared by all vcpus so modify it only
3937 		 * once in the context of vcpu 0.
3938 		 */
3939 		error = vmx_allow_x2apic_msrs(vmx);
3940 		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3941 		    __func__, error));
3942 	}
3943 }
3944 
3945 static void
3946 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3947 {
3948 
3949 	ipi_cpu(hostcpu, pirvec);
3950 }
3951 
3952 /*
3953  * Transfer the pending interrupts in the PIR descriptor to the IRR
3954  * in the virtual APIC page.
3955  */
3956 static void
3957 vmx_inject_pir(struct vlapic *vlapic)
3958 {
3959 	struct vlapic_vtx *vlapic_vtx;
3960 	struct pir_desc *pir_desc;
3961 	struct LAPIC *lapic;
3962 	uint64_t val, pirval;
3963 	int rvi, pirbase = -1;
3964 	uint16_t intr_status_old, intr_status_new;
3965 
3966 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3967 	pir_desc = vlapic_vtx->pir_desc;
3968 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3969 		VLAPIC_CTR0(vlapic, "vmx_inject_pir: "
3970 		    "no posted interrupt pending");
3971 		return;
3972 	}
3973 
3974 	pirval = 0;
3975 	pirbase = -1;
3976 	lapic = vlapic->apic_page;
3977 
3978 	val = atomic_readandclear_long(&pir_desc->pir[0]);
3979 	if (val != 0) {
3980 		lapic->irr0 |= val;
3981 		lapic->irr1 |= val >> 32;
3982 		pirbase = 0;
3983 		pirval = val;
3984 	}
3985 
3986 	val = atomic_readandclear_long(&pir_desc->pir[1]);
3987 	if (val != 0) {
3988 		lapic->irr2 |= val;
3989 		lapic->irr3 |= val >> 32;
3990 		pirbase = 64;
3991 		pirval = val;
3992 	}
3993 
3994 	val = atomic_readandclear_long(&pir_desc->pir[2]);
3995 	if (val != 0) {
3996 		lapic->irr4 |= val;
3997 		lapic->irr5 |= val >> 32;
3998 		pirbase = 128;
3999 		pirval = val;
4000 	}
4001 
4002 	val = atomic_readandclear_long(&pir_desc->pir[3]);
4003 	if (val != 0) {
4004 		lapic->irr6 |= val;
4005 		lapic->irr7 |= val >> 32;
4006 		pirbase = 192;
4007 		pirval = val;
4008 	}
4009 
4010 	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
4011 
4012 	/*
4013 	 * Update RVI so the processor can evaluate pending virtual
4014 	 * interrupts on VM-entry.
4015 	 *
4016 	 * It is possible for pirval to be 0 here, even though the
4017 	 * pending bit has been set. The scenario is:
4018 	 * CPU-Y is sending a posted interrupt to CPU-X, which
4019 	 * is running a guest and processing posted interrupts in h/w.
4020 	 * CPU-X will eventually exit and the state seen in s/w is
4021 	 * the pending bit set, but no PIR bits set.
4022 	 *
4023 	 *      CPU-X                      CPU-Y
4024 	 *   (vm running)                (host running)
4025 	 *   rx posted interrupt
4026 	 *   CLEAR pending bit
4027 	 *				 SET PIR bit
4028 	 *   READ/CLEAR PIR bits
4029 	 *				 SET pending bit
4030 	 *   (vm exit)
4031 	 *   pending bit set, PIR 0
4032 	 */
4033 	if (pirval != 0) {
4034 		rvi = pirbase + flsl(pirval) - 1;
4035 		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
4036 		intr_status_new = (intr_status_old & 0xFF00) | rvi;
4037 		if (intr_status_new > intr_status_old) {
4038 			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
4039 			VLAPIC_CTR2(vlapic, "vmx_inject_pir: "
4040 			    "guest_intr_status changed from 0x%04x to 0x%04x",
4041 			    intr_status_old, intr_status_new);
4042 		}
4043 	}
4044 }
4045 
4046 static struct vlapic *
4047 vmx_vlapic_init(void *vcpui)
4048 {
4049 	struct vmx *vmx;
4050 	struct vmx_vcpu *vcpu;
4051 	struct vlapic *vlapic;
4052 	struct vlapic_vtx *vlapic_vtx;
4053 
4054 	vcpu = vcpui;
4055 	vmx = vcpu->vmx;
4056 
4057 	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
4058 	vlapic->vm = vmx->vm;
4059 	vlapic->vcpu = vcpu->vcpu;
4060 	vlapic->vcpuid = vcpu->vcpuid;
4061 	vlapic->apic_page = (struct LAPIC *)vcpu->apic_page;
4062 
4063 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
4064 	vlapic_vtx->pir_desc = vcpu->pir_desc;
4065 	vlapic_vtx->vcpu = vcpu;
4066 
4067 	if (tpr_shadowing) {
4068 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_ts;
4069 	}
4070 
4071 	if (virtual_interrupt_delivery) {
4072 		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
4073 		vlapic->ops.pending_intr = vmx_pending_intr;
4074 		vlapic->ops.intr_accepted = vmx_intr_accepted;
4075 		vlapic->ops.set_tmr = vmx_set_tmr;
4076 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_vid;
4077 	}
4078 
4079 	if (posted_interrupts)
4080 		vlapic->ops.post_intr = vmx_post_intr;
4081 
4082 	vlapic_init(vlapic);
4083 
4084 	return (vlapic);
4085 }
4086 
4087 static void
4088 vmx_vlapic_cleanup(struct vlapic *vlapic)
4089 {
4090 
4091 	vlapic_cleanup(vlapic);
4092 	free(vlapic, M_VLAPIC);
4093 }
4094 
4095 #ifdef BHYVE_SNAPSHOT
4096 static int
4097 vmx_vcpu_snapshot(void *vcpui, struct vm_snapshot_meta *meta)
4098 {
4099 	struct vmcs *vmcs;
4100 	struct vmx *vmx;
4101 	struct vmx_vcpu *vcpu;
4102 	struct vmxctx *vmxctx;
4103 	int err, run, hostcpu;
4104 
4105 	err = 0;
4106 	vcpu = vcpui;
4107 	vmx = vcpu->vmx;
4108 	vmcs = vcpu->vmcs;
4109 
4110 	run = vcpu_is_running(vcpu->vcpu, &hostcpu);
4111 	if (run && hostcpu != curcpu) {
4112 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm),
4113 		    vcpu->vcpuid);
4114 		return (EINVAL);
4115 	}
4116 
4117 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR0, meta);
4118 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR3, meta);
4119 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR4, meta);
4120 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DR7, meta);
4121 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RSP, meta);
4122 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RIP, meta);
4123 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RFLAGS, meta);
4124 
4125 	/* Guest segments */
4126 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_ES, meta);
4127 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_ES, meta);
4128 
4129 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CS, meta);
4130 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_CS, meta);
4131 
4132 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_SS, meta);
4133 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_SS, meta);
4134 
4135 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DS, meta);
4136 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_DS, meta);
4137 
4138 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_FS, meta);
4139 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_FS, meta);
4140 
4141 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_GS, meta);
4142 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GS, meta);
4143 
4144 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_TR, meta);
4145 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_TR, meta);
4146 
4147 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_LDTR, meta);
4148 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_LDTR, meta);
4149 
4150 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_EFER, meta);
4151 
4152 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_IDTR, meta);
4153 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GDTR, meta);
4154 
4155 	/* Guest page tables */
4156 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE0, meta);
4157 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE1, meta);
4158 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE2, meta);
4159 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE3, meta);
4160 
4161 	/* Other guest state */
4162 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_CS, meta);
4163 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_ESP, meta);
4164 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_EIP, meta);
4165 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_INTERRUPTIBILITY, meta);
4166 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_ACTIVITY, meta);
4167 	err += vmcs_snapshot_any(vmcs, run, VMCS_ENTRY_CTLS, meta);
4168 	err += vmcs_snapshot_any(vmcs, run, VMCS_EXIT_CTLS, meta);
4169 	if (err != 0)
4170 		goto done;
4171 
4172 	SNAPSHOT_BUF_OR_LEAVE(vcpu->guest_msrs,
4173 	    sizeof(vcpu->guest_msrs), meta, err, done);
4174 
4175 	vmxctx = &vcpu->ctx;
4176 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdi, meta, err, done);
4177 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rsi, meta, err, done);
4178 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdx, meta, err, done);
4179 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rcx, meta, err, done);
4180 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r8, meta, err, done);
4181 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r9, meta, err, done);
4182 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rax, meta, err, done);
4183 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbx, meta, err, done);
4184 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbp, meta, err, done);
4185 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r10, meta, err, done);
4186 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r11, meta, err, done);
4187 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r12, meta, err, done);
4188 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r13, meta, err, done);
4189 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r14, meta, err, done);
4190 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r15, meta, err, done);
4191 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_cr2, meta, err, done);
4192 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr0, meta, err, done);
4193 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr1, meta, err, done);
4194 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr2, meta, err, done);
4195 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr3, meta, err, done);
4196 	SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr6, meta, err, done);
4197 
4198 done:
4199 	return (err);
4200 }
4201 
4202 static int
4203 vmx_restore_tsc(void *vcpui, uint64_t offset)
4204 {
4205 	struct vmx_vcpu *vcpu = vcpui;
4206 	struct vmcs *vmcs;
4207 	struct vmx *vmx;
4208 	int error, running, hostcpu;
4209 
4210 	vmx = vcpu->vmx;
4211 	vmcs = vcpu->vmcs;
4212 
4213 	running = vcpu_is_running(vcpu->vcpu, &hostcpu);
4214 	if (running && hostcpu != curcpu) {
4215 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm),
4216 		    vcpu->vcpuid);
4217 		return (EINVAL);
4218 	}
4219 
4220 	if (!running)
4221 		VMPTRLD(vmcs);
4222 
4223 	error = vmx_set_tsc_offset(vcpu, offset);
4224 
4225 	if (!running)
4226 		VMCLEAR(vmcs);
4227 	return (error);
4228 }
4229 #endif
4230 
4231 const struct vmm_ops vmm_ops_intel = {
4232 	.modinit	= vmx_modinit,
4233 	.modcleanup	= vmx_modcleanup,
4234 	.modresume	= vmx_modresume,
4235 	.init		= vmx_init,
4236 	.run		= vmx_run,
4237 	.cleanup	= vmx_cleanup,
4238 	.vcpu_init	= vmx_vcpu_init,
4239 	.vcpu_cleanup	= vmx_vcpu_cleanup,
4240 	.getreg		= vmx_getreg,
4241 	.setreg		= vmx_setreg,
4242 	.getdesc	= vmx_getdesc,
4243 	.setdesc	= vmx_setdesc,
4244 	.getcap		= vmx_getcap,
4245 	.setcap		= vmx_setcap,
4246 	.vmspace_alloc	= vmx_vmspace_alloc,
4247 	.vmspace_free	= vmx_vmspace_free,
4248 	.vlapic_init	= vmx_vlapic_init,
4249 	.vlapic_cleanup	= vmx_vlapic_cleanup,
4250 #ifdef BHYVE_SNAPSHOT
4251 	.vcpu_snapshot	= vmx_vcpu_snapshot,
4252 	.restore_tsc	= vmx_restore_tsc,
4253 #endif
4254 };
4255