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