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