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