xref: /freebsd/sys/amd64/vmm/intel/vmx.c (revision 84823cc70824c8d842f503d8c2e6d7b0c2d95b61)
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_INVD:
2794 	case EXIT_REASON_WBINVD:
2795 		/* ignore exit */
2796 		handled = HANDLED;
2797 		break;
2798 	default:
2799 		SDT_PROBE4(vmm, vmx, exit, unknown,
2800 		    vmx, vcpu, vmexit, reason);
2801 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2802 		break;
2803 	}
2804 
2805 	if (handled) {
2806 		/*
2807 		 * It is possible that control is returned to userland
2808 		 * even though we were able to handle the VM exit in the
2809 		 * kernel.
2810 		 *
2811 		 * In such a case we want to make sure that the userland
2812 		 * restarts guest execution at the instruction *after*
2813 		 * the one we just processed. Therefore we update the
2814 		 * guest rip in the VMCS and in 'vmexit'.
2815 		 */
2816 		vmexit->rip += vmexit->inst_length;
2817 		vmexit->inst_length = 0;
2818 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2819 	} else {
2820 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2821 			/*
2822 			 * If this VM exit was not claimed by anybody then
2823 			 * treat it as a generic VMX exit.
2824 			 */
2825 			vmexit->exitcode = VM_EXITCODE_VMX;
2826 			vmexit->u.vmx.status = VM_SUCCESS;
2827 			vmexit->u.vmx.inst_type = 0;
2828 			vmexit->u.vmx.inst_error = 0;
2829 		} else {
2830 			/*
2831 			 * The exitcode and collateral have been populated.
2832 			 * The VM exit will be processed further in userland.
2833 			 */
2834 		}
2835 	}
2836 
2837 	SDT_PROBE4(vmm, vmx, exit, return,
2838 	    vmx, vcpu, vmexit, handled);
2839 	return (handled);
2840 }
2841 
2842 static __inline void
2843 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2844 {
2845 
2846 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2847 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2848 	    vmxctx->inst_fail_status));
2849 
2850 	vmexit->inst_length = 0;
2851 	vmexit->exitcode = VM_EXITCODE_VMX;
2852 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2853 	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2854 	vmexit->u.vmx.exit_reason = ~0;
2855 	vmexit->u.vmx.exit_qualification = ~0;
2856 
2857 	switch (rc) {
2858 	case VMX_VMRESUME_ERROR:
2859 	case VMX_VMLAUNCH_ERROR:
2860 		vmexit->u.vmx.inst_type = rc;
2861 		break;
2862 	default:
2863 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2864 	}
2865 }
2866 
2867 /*
2868  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2869  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2870  * sufficient to simply vector to the NMI handler via a software interrupt.
2871  * However, this must be done before maskable interrupts are enabled
2872  * otherwise the "iret" issued by an interrupt handler will incorrectly
2873  * clear NMI blocking.
2874  */
2875 static __inline void
2876 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2877 {
2878 	uint32_t intr_info;
2879 
2880 	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2881 
2882 	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2883 		return;
2884 
2885 	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2886 	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2887 	    ("VM exit interruption info invalid: %#x", intr_info));
2888 
2889 	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2890 		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2891 		    "to NMI has invalid vector: %#x", intr_info));
2892 		VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2893 		__asm __volatile("int $2");
2894 	}
2895 }
2896 
2897 static __inline void
2898 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2899 {
2900 	register_t rflags;
2901 
2902 	/* Save host control debug registers. */
2903 	vmxctx->host_dr7 = rdr7();
2904 	vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2905 
2906 	/*
2907 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2908 	 * exceptions in the host based on the guest DRx values.  The
2909 	 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2910 	 */
2911 	load_dr7(0);
2912 	wrmsr(MSR_DEBUGCTLMSR, 0);
2913 
2914 	/*
2915 	 * Disable single stepping the kernel to avoid corrupting the
2916 	 * guest DR6.  A debugger might still be able to corrupt the
2917 	 * guest DR6 by setting a breakpoint after this point and then
2918 	 * single stepping.
2919 	 */
2920 	rflags = read_rflags();
2921 	vmxctx->host_tf = rflags & PSL_T;
2922 	write_rflags(rflags & ~PSL_T);
2923 
2924 	/* Save host debug registers. */
2925 	vmxctx->host_dr0 = rdr0();
2926 	vmxctx->host_dr1 = rdr1();
2927 	vmxctx->host_dr2 = rdr2();
2928 	vmxctx->host_dr3 = rdr3();
2929 	vmxctx->host_dr6 = rdr6();
2930 
2931 	/* Restore guest debug registers. */
2932 	load_dr0(vmxctx->guest_dr0);
2933 	load_dr1(vmxctx->guest_dr1);
2934 	load_dr2(vmxctx->guest_dr2);
2935 	load_dr3(vmxctx->guest_dr3);
2936 	load_dr6(vmxctx->guest_dr6);
2937 }
2938 
2939 static __inline void
2940 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2941 {
2942 
2943 	/* Save guest debug registers. */
2944 	vmxctx->guest_dr0 = rdr0();
2945 	vmxctx->guest_dr1 = rdr1();
2946 	vmxctx->guest_dr2 = rdr2();
2947 	vmxctx->guest_dr3 = rdr3();
2948 	vmxctx->guest_dr6 = rdr6();
2949 
2950 	/*
2951 	 * Restore host debug registers.  Restore DR7, DEBUGCTL, and
2952 	 * PSL_T last.
2953 	 */
2954 	load_dr0(vmxctx->host_dr0);
2955 	load_dr1(vmxctx->host_dr1);
2956 	load_dr2(vmxctx->host_dr2);
2957 	load_dr3(vmxctx->host_dr3);
2958 	load_dr6(vmxctx->host_dr6);
2959 	wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2960 	load_dr7(vmxctx->host_dr7);
2961 	write_rflags(read_rflags() | vmxctx->host_tf);
2962 }
2963 
2964 static __inline void
2965 vmx_pmap_activate(struct vmx *vmx, pmap_t pmap)
2966 {
2967 	long eptgen;
2968 	int cpu;
2969 
2970 	cpu = curcpu;
2971 
2972 	CPU_SET_ATOMIC(cpu, &pmap->pm_active);
2973 	smr_enter(pmap->pm_eptsmr);
2974 	eptgen = atomic_load_long(&pmap->pm_eptgen);
2975 	if (eptgen != vmx->eptgen[cpu]) {
2976 		vmx->eptgen[cpu] = eptgen;
2977 		invept(INVEPT_TYPE_SINGLE_CONTEXT,
2978 		    (struct invept_desc){ .eptp = vmx->eptp, ._res = 0 });
2979 	}
2980 }
2981 
2982 static __inline void
2983 vmx_pmap_deactivate(struct vmx *vmx, pmap_t pmap)
2984 {
2985 	smr_exit(pmap->pm_eptsmr);
2986 	CPU_CLR_ATOMIC(curcpu, &pmap->pm_active);
2987 }
2988 
2989 static int
2990 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2991     struct vm_eventinfo *evinfo)
2992 {
2993 	int rc, handled, launched;
2994 	struct vmx *vmx;
2995 	struct vm *vm;
2996 	struct vmxctx *vmxctx;
2997 	struct vmcs *vmcs;
2998 	struct vm_exit *vmexit;
2999 	struct vlapic *vlapic;
3000 	uint32_t exit_reason;
3001 	struct region_descriptor gdtr, idtr;
3002 	uint16_t ldt_sel;
3003 
3004 	vmx = arg;
3005 	vm = vmx->vm;
3006 	vmcs = &vmx->vmcs[vcpu];
3007 	vmxctx = &vmx->ctx[vcpu];
3008 	vlapic = vm_lapic(vm, vcpu);
3009 	vmexit = vm_exitinfo(vm, vcpu);
3010 	launched = 0;
3011 
3012 	KASSERT(vmxctx->pmap == pmap,
3013 	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
3014 
3015 	vmx_msr_guest_enter(vmx, vcpu);
3016 
3017 	VMPTRLD(vmcs);
3018 
3019 	/*
3020 	 * XXX
3021 	 * We do this every time because we may setup the virtual machine
3022 	 * from a different process than the one that actually runs it.
3023 	 *
3024 	 * If the life of a virtual machine was spent entirely in the context
3025 	 * of a single process we could do this once in vmx_init().
3026 	 */
3027 	vmcs_write(VMCS_HOST_CR3, rcr3());
3028 
3029 	vmcs_write(VMCS_GUEST_RIP, rip);
3030 	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
3031 	do {
3032 		KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
3033 		    "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
3034 
3035 		handled = UNHANDLED;
3036 		/*
3037 		 * Interrupts are disabled from this point on until the
3038 		 * guest starts executing. This is done for the following
3039 		 * reasons:
3040 		 *
3041 		 * If an AST is asserted on this thread after the check below,
3042 		 * then the IPI_AST notification will not be lost, because it
3043 		 * will cause a VM exit due to external interrupt as soon as
3044 		 * the guest state is loaded.
3045 		 *
3046 		 * A posted interrupt after 'vmx_inject_interrupts()' will
3047 		 * not be "lost" because it will be held pending in the host
3048 		 * APIC because interrupts are disabled. The pending interrupt
3049 		 * will be recognized as soon as the guest state is loaded.
3050 		 *
3051 		 * The same reasoning applies to the IPI generated by
3052 		 * pmap_invalidate_ept().
3053 		 */
3054 		disable_intr();
3055 		vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
3056 
3057 		/*
3058 		 * Check for vcpu suspension after injecting events because
3059 		 * vmx_inject_interrupts() can suspend the vcpu due to a
3060 		 * triple fault.
3061 		 */
3062 		if (vcpu_suspended(evinfo)) {
3063 			enable_intr();
3064 			vm_exit_suspended(vmx->vm, vcpu, rip);
3065 			break;
3066 		}
3067 
3068 		if (vcpu_rendezvous_pending(evinfo)) {
3069 			enable_intr();
3070 			vm_exit_rendezvous(vmx->vm, vcpu, rip);
3071 			break;
3072 		}
3073 
3074 		if (vcpu_reqidle(evinfo)) {
3075 			enable_intr();
3076 			vm_exit_reqidle(vmx->vm, vcpu, rip);
3077 			break;
3078 		}
3079 
3080 		if (vcpu_should_yield(vm, vcpu)) {
3081 			enable_intr();
3082 			vm_exit_astpending(vmx->vm, vcpu, rip);
3083 			vmx_astpending_trace(vmx, vcpu, rip);
3084 			handled = HANDLED;
3085 			break;
3086 		}
3087 
3088 		if (vcpu_debugged(vm, vcpu)) {
3089 			enable_intr();
3090 			vm_exit_debug(vmx->vm, vcpu, rip);
3091 			break;
3092 		}
3093 
3094 		/*
3095 		 * If TPR Shadowing is enabled, the TPR Threshold
3096 		 * must be updated right before entering the guest.
3097 		 */
3098 		if (tpr_shadowing && !virtual_interrupt_delivery) {
3099 			if ((vmx->cap[vcpu].proc_ctls & PROCBASED_USE_TPR_SHADOW) != 0) {
3100 				vmcs_write(VMCS_TPR_THRESHOLD, vlapic_get_cr8(vlapic));
3101 			}
3102 		}
3103 
3104 		/*
3105 		 * VM exits restore the base address but not the
3106 		 * limits of GDTR and IDTR.  The VMCS only stores the
3107 		 * base address, so VM exits set the limits to 0xffff.
3108 		 * Save and restore the full GDTR and IDTR to restore
3109 		 * the limits.
3110 		 *
3111 		 * The VMCS does not save the LDTR at all, and VM
3112 		 * exits clear LDTR as if a NULL selector were loaded.
3113 		 * The userspace hypervisor probably doesn't use a
3114 		 * LDT, but save and restore it to be safe.
3115 		 */
3116 		sgdt(&gdtr);
3117 		sidt(&idtr);
3118 		ldt_sel = sldt();
3119 
3120 		/*
3121 		 * The TSC_AUX MSR must be saved/restored while interrupts
3122 		 * are disabled so that it is not possible for the guest
3123 		 * TSC_AUX MSR value to be overwritten by the resume
3124 		 * portion of the IPI_SUSPEND codepath. This is why the
3125 		 * transition of this MSR is handled separately from those
3126 		 * handled by vmx_msr_guest_{enter,exit}(), which are ok to
3127 		 * be transitioned with preemption disabled but interrupts
3128 		 * enabled.
3129 		 *
3130 		 * These vmx_msr_guest_{enter,exit}_tsc_aux() calls can be
3131 		 * anywhere in this loop so long as they happen with
3132 		 * interrupts disabled. This location is chosen for
3133 		 * simplicity.
3134 		 */
3135 		vmx_msr_guest_enter_tsc_aux(vmx, vcpu);
3136 
3137 		vmx_dr_enter_guest(vmxctx);
3138 
3139 		/*
3140 		 * Mark the EPT as active on this host CPU and invalidate
3141 		 * EPTP-tagged TLB entries if required.
3142 		 */
3143 		vmx_pmap_activate(vmx, pmap);
3144 
3145 		vmx_run_trace(vmx, vcpu);
3146 		rc = vmx_enter_guest(vmxctx, vmx, launched);
3147 
3148 		vmx_pmap_deactivate(vmx, pmap);
3149 		vmx_dr_leave_guest(vmxctx);
3150 		vmx_msr_guest_exit_tsc_aux(vmx, vcpu);
3151 
3152 		bare_lgdt(&gdtr);
3153 		lidt(&idtr);
3154 		lldt(ldt_sel);
3155 
3156 		/* Collect some information for VM exit processing */
3157 		vmexit->rip = rip = vmcs_guest_rip();
3158 		vmexit->inst_length = vmexit_instruction_length();
3159 		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
3160 		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
3161 
3162 		/* Update 'nextrip' */
3163 		vmx->state[vcpu].nextrip = rip;
3164 
3165 		if (rc == VMX_GUEST_VMEXIT) {
3166 			vmx_exit_handle_nmi(vmx, vcpu, vmexit);
3167 			enable_intr();
3168 			handled = vmx_exit_process(vmx, vcpu, vmexit);
3169 		} else {
3170 			enable_intr();
3171 			vmx_exit_inst_error(vmxctx, rc, vmexit);
3172 		}
3173 		launched = 1;
3174 		vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
3175 		rip = vmexit->rip;
3176 	} while (handled);
3177 
3178 	/*
3179 	 * If a VM exit has been handled then the exitcode must be BOGUS
3180 	 * If a VM exit is not handled then the exitcode must not be BOGUS
3181 	 */
3182 	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
3183 	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
3184 		panic("Mismatch between handled (%d) and exitcode (%d)",
3185 		      handled, vmexit->exitcode);
3186 	}
3187 
3188 	VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
3189 	    vmexit->exitcode);
3190 
3191 	VMCLEAR(vmcs);
3192 	vmx_msr_guest_exit(vmx, vcpu);
3193 
3194 	return (0);
3195 }
3196 
3197 static void
3198 vmx_cleanup(void *arg)
3199 {
3200 	int i;
3201 	struct vmx *vmx = arg;
3202 	uint16_t maxcpus;
3203 
3204 	if (apic_access_virtualization(vmx, 0))
3205 		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3206 
3207 	maxcpus = vm_get_maxcpus(vmx->vm);
3208 	for (i = 0; i < maxcpus; i++)
3209 		vpid_free(vmx->state[i].vpid);
3210 
3211 	free(vmx, M_VMX);
3212 
3213 	return;
3214 }
3215 
3216 static register_t *
3217 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
3218 {
3219 
3220 	switch (reg) {
3221 	case VM_REG_GUEST_RAX:
3222 		return (&vmxctx->guest_rax);
3223 	case VM_REG_GUEST_RBX:
3224 		return (&vmxctx->guest_rbx);
3225 	case VM_REG_GUEST_RCX:
3226 		return (&vmxctx->guest_rcx);
3227 	case VM_REG_GUEST_RDX:
3228 		return (&vmxctx->guest_rdx);
3229 	case VM_REG_GUEST_RSI:
3230 		return (&vmxctx->guest_rsi);
3231 	case VM_REG_GUEST_RDI:
3232 		return (&vmxctx->guest_rdi);
3233 	case VM_REG_GUEST_RBP:
3234 		return (&vmxctx->guest_rbp);
3235 	case VM_REG_GUEST_R8:
3236 		return (&vmxctx->guest_r8);
3237 	case VM_REG_GUEST_R9:
3238 		return (&vmxctx->guest_r9);
3239 	case VM_REG_GUEST_R10:
3240 		return (&vmxctx->guest_r10);
3241 	case VM_REG_GUEST_R11:
3242 		return (&vmxctx->guest_r11);
3243 	case VM_REG_GUEST_R12:
3244 		return (&vmxctx->guest_r12);
3245 	case VM_REG_GUEST_R13:
3246 		return (&vmxctx->guest_r13);
3247 	case VM_REG_GUEST_R14:
3248 		return (&vmxctx->guest_r14);
3249 	case VM_REG_GUEST_R15:
3250 		return (&vmxctx->guest_r15);
3251 	case VM_REG_GUEST_CR2:
3252 		return (&vmxctx->guest_cr2);
3253 	case VM_REG_GUEST_DR0:
3254 		return (&vmxctx->guest_dr0);
3255 	case VM_REG_GUEST_DR1:
3256 		return (&vmxctx->guest_dr1);
3257 	case VM_REG_GUEST_DR2:
3258 		return (&vmxctx->guest_dr2);
3259 	case VM_REG_GUEST_DR3:
3260 		return (&vmxctx->guest_dr3);
3261 	case VM_REG_GUEST_DR6:
3262 		return (&vmxctx->guest_dr6);
3263 	default:
3264 		break;
3265 	}
3266 	return (NULL);
3267 }
3268 
3269 static int
3270 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
3271 {
3272 	register_t *regp;
3273 
3274 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
3275 		*retval = *regp;
3276 		return (0);
3277 	} else
3278 		return (EINVAL);
3279 }
3280 
3281 static int
3282 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
3283 {
3284 	register_t *regp;
3285 
3286 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
3287 		*regp = val;
3288 		return (0);
3289 	} else
3290 		return (EINVAL);
3291 }
3292 
3293 static int
3294 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
3295 {
3296 	uint64_t gi;
3297 	int error;
3298 
3299 	error = vmcs_getreg(&vmx->vmcs[vcpu], running,
3300 	    VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
3301 	*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
3302 	return (error);
3303 }
3304 
3305 static int
3306 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
3307 {
3308 	struct vmcs *vmcs;
3309 	uint64_t gi;
3310 	int error, ident;
3311 
3312 	/*
3313 	 * Forcing the vcpu into an interrupt shadow is not supported.
3314 	 */
3315 	if (val) {
3316 		error = EINVAL;
3317 		goto done;
3318 	}
3319 
3320 	vmcs = &vmx->vmcs[vcpu];
3321 	ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
3322 	error = vmcs_getreg(vmcs, running, ident, &gi);
3323 	if (error == 0) {
3324 		gi &= ~HWINTR_BLOCKING;
3325 		error = vmcs_setreg(vmcs, running, ident, gi);
3326 	}
3327 done:
3328 	VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
3329 	    error ? "failed" : "succeeded");
3330 	return (error);
3331 }
3332 
3333 static int
3334 vmx_shadow_reg(int reg)
3335 {
3336 	int shreg;
3337 
3338 	shreg = -1;
3339 
3340 	switch (reg) {
3341 	case VM_REG_GUEST_CR0:
3342 		shreg = VMCS_CR0_SHADOW;
3343 		break;
3344 	case VM_REG_GUEST_CR4:
3345 		shreg = VMCS_CR4_SHADOW;
3346 		break;
3347 	default:
3348 		break;
3349 	}
3350 
3351 	return (shreg);
3352 }
3353 
3354 static int
3355 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
3356 {
3357 	int running, hostcpu;
3358 	struct vmx *vmx = arg;
3359 
3360 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3361 	if (running && hostcpu != curcpu)
3362 		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
3363 
3364 	if (reg == VM_REG_GUEST_INTR_SHADOW)
3365 		return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
3366 
3367 	if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
3368 		return (0);
3369 
3370 	return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
3371 }
3372 
3373 static int
3374 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
3375 {
3376 	int error, hostcpu, running, shadow;
3377 	uint64_t ctls;
3378 	pmap_t pmap;
3379 	struct vmx *vmx = arg;
3380 
3381 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3382 	if (running && hostcpu != curcpu)
3383 		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
3384 
3385 	if (reg == VM_REG_GUEST_INTR_SHADOW)
3386 		return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
3387 
3388 	if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
3389 		return (0);
3390 
3391 	/* Do not permit user write access to VMCS fields by offset. */
3392 	if (reg < 0)
3393 		return (EINVAL);
3394 
3395 	error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
3396 
3397 	if (error == 0) {
3398 		/*
3399 		 * If the "load EFER" VM-entry control is 1 then the
3400 		 * value of EFER.LMA must be identical to "IA-32e mode guest"
3401 		 * bit in the VM-entry control.
3402 		 */
3403 		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
3404 		    (reg == VM_REG_GUEST_EFER)) {
3405 			vmcs_getreg(&vmx->vmcs[vcpu], running,
3406 				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
3407 			if (val & EFER_LMA)
3408 				ctls |= VM_ENTRY_GUEST_LMA;
3409 			else
3410 				ctls &= ~VM_ENTRY_GUEST_LMA;
3411 			vmcs_setreg(&vmx->vmcs[vcpu], running,
3412 				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
3413 		}
3414 
3415 		shadow = vmx_shadow_reg(reg);
3416 		if (shadow > 0) {
3417 			/*
3418 			 * Store the unmodified value in the shadow
3419 			 */
3420 			error = vmcs_setreg(&vmx->vmcs[vcpu], running,
3421 				    VMCS_IDENT(shadow), val);
3422 		}
3423 
3424 		if (reg == VM_REG_GUEST_CR3) {
3425 			/*
3426 			 * Invalidate the guest vcpu's TLB mappings to emulate
3427 			 * the behavior of updating %cr3.
3428 			 *
3429 			 * XXX the processor retains global mappings when %cr3
3430 			 * is updated but vmx_invvpid() does not.
3431 			 */
3432 			pmap = vmx->ctx[vcpu].pmap;
3433 			vmx_invvpid(vmx, vcpu, pmap, running);
3434 		}
3435 	}
3436 
3437 	return (error);
3438 }
3439 
3440 static int
3441 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3442 {
3443 	int hostcpu, running;
3444 	struct vmx *vmx = arg;
3445 
3446 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3447 	if (running && hostcpu != curcpu)
3448 		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3449 
3450 	return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
3451 }
3452 
3453 static int
3454 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3455 {
3456 	int hostcpu, running;
3457 	struct vmx *vmx = arg;
3458 
3459 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3460 	if (running && hostcpu != curcpu)
3461 		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3462 
3463 	return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
3464 }
3465 
3466 static int
3467 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3468 {
3469 	struct vmx *vmx = arg;
3470 	int vcap;
3471 	int ret;
3472 
3473 	ret = ENOENT;
3474 
3475 	vcap = vmx->cap[vcpu].set;
3476 
3477 	switch (type) {
3478 	case VM_CAP_HALT_EXIT:
3479 		if (cap_halt_exit)
3480 			ret = 0;
3481 		break;
3482 	case VM_CAP_PAUSE_EXIT:
3483 		if (cap_pause_exit)
3484 			ret = 0;
3485 		break;
3486 	case VM_CAP_MTRAP_EXIT:
3487 		if (cap_monitor_trap)
3488 			ret = 0;
3489 		break;
3490 	case VM_CAP_RDPID:
3491 		if (cap_rdpid)
3492 			ret = 0;
3493 		break;
3494 	case VM_CAP_RDTSCP:
3495 		if (cap_rdtscp)
3496 			ret = 0;
3497 		break;
3498 	case VM_CAP_UNRESTRICTED_GUEST:
3499 		if (cap_unrestricted_guest)
3500 			ret = 0;
3501 		break;
3502 	case VM_CAP_ENABLE_INVPCID:
3503 		if (cap_invpcid)
3504 			ret = 0;
3505 		break;
3506 	case VM_CAP_BPT_EXIT:
3507 		ret = 0;
3508 		break;
3509 	default:
3510 		break;
3511 	}
3512 
3513 	if (ret == 0)
3514 		*retval = (vcap & (1 << type)) ? 1 : 0;
3515 
3516 	return (ret);
3517 }
3518 
3519 static int
3520 vmx_setcap(void *arg, int vcpu, int type, int val)
3521 {
3522 	struct vmx *vmx = arg;
3523 	struct vmcs *vmcs = &vmx->vmcs[vcpu];
3524 	uint32_t baseval;
3525 	uint32_t *pptr;
3526 	int error;
3527 	int flag;
3528 	int reg;
3529 	int retval;
3530 
3531 	retval = ENOENT;
3532 	pptr = NULL;
3533 
3534 	switch (type) {
3535 	case VM_CAP_HALT_EXIT:
3536 		if (cap_halt_exit) {
3537 			retval = 0;
3538 			pptr = &vmx->cap[vcpu].proc_ctls;
3539 			baseval = *pptr;
3540 			flag = PROCBASED_HLT_EXITING;
3541 			reg = VMCS_PRI_PROC_BASED_CTLS;
3542 		}
3543 		break;
3544 	case VM_CAP_MTRAP_EXIT:
3545 		if (cap_monitor_trap) {
3546 			retval = 0;
3547 			pptr = &vmx->cap[vcpu].proc_ctls;
3548 			baseval = *pptr;
3549 			flag = PROCBASED_MTF;
3550 			reg = VMCS_PRI_PROC_BASED_CTLS;
3551 		}
3552 		break;
3553 	case VM_CAP_PAUSE_EXIT:
3554 		if (cap_pause_exit) {
3555 			retval = 0;
3556 			pptr = &vmx->cap[vcpu].proc_ctls;
3557 			baseval = *pptr;
3558 			flag = PROCBASED_PAUSE_EXITING;
3559 			reg = VMCS_PRI_PROC_BASED_CTLS;
3560 		}
3561 		break;
3562 	case VM_CAP_RDPID:
3563 	case VM_CAP_RDTSCP:
3564 		if (cap_rdpid || cap_rdtscp)
3565 			/*
3566 			 * Choose not to support enabling/disabling
3567 			 * RDPID/RDTSCP via libvmmapi since, as per the
3568 			 * discussion in vmx_modinit(), RDPID/RDTSCP are
3569 			 * either always enabled or always disabled.
3570 			 */
3571 			error = EOPNOTSUPP;
3572 		break;
3573 	case VM_CAP_UNRESTRICTED_GUEST:
3574 		if (cap_unrestricted_guest) {
3575 			retval = 0;
3576 			pptr = &vmx->cap[vcpu].proc_ctls2;
3577 			baseval = *pptr;
3578 			flag = PROCBASED2_UNRESTRICTED_GUEST;
3579 			reg = VMCS_SEC_PROC_BASED_CTLS;
3580 		}
3581 		break;
3582 	case VM_CAP_ENABLE_INVPCID:
3583 		if (cap_invpcid) {
3584 			retval = 0;
3585 			pptr = &vmx->cap[vcpu].proc_ctls2;
3586 			baseval = *pptr;
3587 			flag = PROCBASED2_ENABLE_INVPCID;
3588 			reg = VMCS_SEC_PROC_BASED_CTLS;
3589 		}
3590 		break;
3591 	case VM_CAP_BPT_EXIT:
3592 		retval = 0;
3593 
3594 		/* Don't change the bitmap if we are tracing all exceptions. */
3595 		if (vmx->cap[vcpu].exc_bitmap != 0xffffffff) {
3596 			pptr = &vmx->cap[vcpu].exc_bitmap;
3597 			baseval = *pptr;
3598 			flag = (1 << IDT_BP);
3599 			reg = VMCS_EXCEPTION_BITMAP;
3600 		}
3601 		break;
3602 	default:
3603 		break;
3604 	}
3605 
3606 	if (retval)
3607 		return (retval);
3608 
3609 	if (pptr != NULL) {
3610 		if (val) {
3611 			baseval |= flag;
3612 		} else {
3613 			baseval &= ~flag;
3614 		}
3615 		VMPTRLD(vmcs);
3616 		error = vmwrite(reg, baseval);
3617 		VMCLEAR(vmcs);
3618 
3619 		if (error)
3620 			return (error);
3621 
3622 		/*
3623 		 * Update optional stored flags, and record
3624 		 * setting
3625 		 */
3626 		*pptr = baseval;
3627 	}
3628 
3629 	if (val) {
3630 		vmx->cap[vcpu].set |= (1 << type);
3631 	} else {
3632 		vmx->cap[vcpu].set &= ~(1 << type);
3633 	}
3634 
3635 	return (0);
3636 }
3637 
3638 static struct vmspace *
3639 vmx_vmspace_alloc(vm_offset_t min, vm_offset_t max)
3640 {
3641 	return (ept_vmspace_alloc(min, max));
3642 }
3643 
3644 static void
3645 vmx_vmspace_free(struct vmspace *vmspace)
3646 {
3647 	ept_vmspace_free(vmspace);
3648 }
3649 
3650 struct vlapic_vtx {
3651 	struct vlapic	vlapic;
3652 	struct pir_desc	*pir_desc;
3653 	struct vmx	*vmx;
3654 	u_int	pending_prio;
3655 };
3656 
3657 #define VPR_PRIO_BIT(vpr)	(1 << ((vpr) >> 4))
3658 
3659 #define	VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)	\
3660 do {									\
3661 	VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",	\
3662 	    level ? "level" : "edge", vector);				\
3663 	VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3664 	VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3665 	VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3666 	VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3667 	VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3668 } while (0)
3669 
3670 /*
3671  * vlapic->ops handlers that utilize the APICv hardware assist described in
3672  * Chapter 29 of the Intel SDM.
3673  */
3674 static int
3675 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3676 {
3677 	struct vlapic_vtx *vlapic_vtx;
3678 	struct pir_desc *pir_desc;
3679 	uint64_t mask;
3680 	int idx, notify = 0;
3681 
3682 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3683 	pir_desc = vlapic_vtx->pir_desc;
3684 
3685 	/*
3686 	 * Keep track of interrupt requests in the PIR descriptor. This is
3687 	 * because the virtual APIC page pointed to by the VMCS cannot be
3688 	 * modified if the vcpu is running.
3689 	 */
3690 	idx = vector / 64;
3691 	mask = 1UL << (vector % 64);
3692 	atomic_set_long(&pir_desc->pir[idx], mask);
3693 
3694 	/*
3695 	 * A notification is required whenever the 'pending' bit makes a
3696 	 * transition from 0->1.
3697 	 *
3698 	 * Even if the 'pending' bit is already asserted, notification about
3699 	 * the incoming interrupt may still be necessary.  For example, if a
3700 	 * vCPU is HLTed with a high PPR, a low priority interrupt would cause
3701 	 * the 0->1 'pending' transition with a notification, but the vCPU
3702 	 * would ignore the interrupt for the time being.  The same vCPU would
3703 	 * need to then be notified if a high-priority interrupt arrived which
3704 	 * satisfied the PPR.
3705 	 *
3706 	 * The priorities of interrupts injected while 'pending' is asserted
3707 	 * are tracked in a custom bitfield 'pending_prio'.  Should the
3708 	 * to-be-injected interrupt exceed the priorities already present, the
3709 	 * notification is sent.  The priorities recorded in 'pending_prio' are
3710 	 * cleared whenever the 'pending' bit makes another 0->1 transition.
3711 	 */
3712 	if (atomic_cmpset_long(&pir_desc->pending, 0, 1) != 0) {
3713 		notify = 1;
3714 		vlapic_vtx->pending_prio = 0;
3715 	} else {
3716 		const u_int old_prio = vlapic_vtx->pending_prio;
3717 		const u_int prio_bit = VPR_PRIO_BIT(vector & APIC_TPR_INT);
3718 
3719 		if ((old_prio & prio_bit) == 0 && prio_bit > old_prio) {
3720 			atomic_set_int(&vlapic_vtx->pending_prio, prio_bit);
3721 			notify = 1;
3722 		}
3723 	}
3724 
3725 	VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3726 	    level, "vmx_set_intr_ready");
3727 	return (notify);
3728 }
3729 
3730 static int
3731 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3732 {
3733 	struct vlapic_vtx *vlapic_vtx;
3734 	struct pir_desc *pir_desc;
3735 	struct LAPIC *lapic;
3736 	uint64_t pending, pirval;
3737 	uint32_t ppr, vpr;
3738 	int i;
3739 
3740 	/*
3741 	 * This function is only expected to be called from the 'HLT' exit
3742 	 * handler which does not care about the vector that is pending.
3743 	 */
3744 	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3745 
3746 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3747 	pir_desc = vlapic_vtx->pir_desc;
3748 
3749 	pending = atomic_load_acq_long(&pir_desc->pending);
3750 	if (!pending) {
3751 		/*
3752 		 * While a virtual interrupt may have already been
3753 		 * processed the actual delivery maybe pending the
3754 		 * interruptibility of the guest.  Recognize a pending
3755 		 * interrupt by reevaluating virtual interrupts
3756 		 * following Section 29.2.1 in the Intel SDM Volume 3.
3757 		 */
3758 		struct vm_exit *vmexit;
3759 		uint8_t rvi, ppr;
3760 
3761 		vmexit = vm_exitinfo(vlapic->vm, vlapic->vcpuid);
3762 		KASSERT(vmexit->exitcode == VM_EXITCODE_HLT,
3763 		    ("vmx_pending_intr: exitcode not 'HLT'"));
3764 		rvi = vmexit->u.hlt.intr_status & APIC_TPR_INT;
3765 		lapic = vlapic->apic_page;
3766 		ppr = lapic->ppr & APIC_TPR_INT;
3767 		if (rvi > ppr) {
3768 			return (1);
3769 		}
3770 
3771 		return (0);
3772 	}
3773 
3774 	/*
3775 	 * If there is an interrupt pending then it will be recognized only
3776 	 * if its priority is greater than the processor priority.
3777 	 *
3778 	 * Special case: if the processor priority is zero then any pending
3779 	 * interrupt will be recognized.
3780 	 */
3781 	lapic = vlapic->apic_page;
3782 	ppr = lapic->ppr & APIC_TPR_INT;
3783 	if (ppr == 0)
3784 		return (1);
3785 
3786 	VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3787 	    lapic->ppr);
3788 
3789 	vpr = 0;
3790 	for (i = 3; i >= 0; i--) {
3791 		pirval = pir_desc->pir[i];
3792 		if (pirval != 0) {
3793 			vpr = (i * 64 + flsl(pirval) - 1) & APIC_TPR_INT;
3794 			break;
3795 		}
3796 	}
3797 
3798 	/*
3799 	 * If the highest-priority pending interrupt falls short of the
3800 	 * processor priority of this vCPU, ensure that 'pending_prio' does not
3801 	 * have any stale bits which would preclude a higher-priority interrupt
3802 	 * from incurring a notification later.
3803 	 */
3804 	if (vpr <= ppr) {
3805 		const u_int prio_bit = VPR_PRIO_BIT(vpr);
3806 		const u_int old = vlapic_vtx->pending_prio;
3807 
3808 		if (old > prio_bit && (old & prio_bit) == 0) {
3809 			vlapic_vtx->pending_prio = prio_bit;
3810 		}
3811 		return (0);
3812 	}
3813 	return (1);
3814 }
3815 
3816 static void
3817 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3818 {
3819 
3820 	panic("vmx_intr_accepted: not expected to be called");
3821 }
3822 
3823 static void
3824 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3825 {
3826 	struct vlapic_vtx *vlapic_vtx;
3827 	struct vmx *vmx;
3828 	struct vmcs *vmcs;
3829 	uint64_t mask, val;
3830 
3831 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3832 	KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3833 	    ("vmx_set_tmr: vcpu cannot be running"));
3834 
3835 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3836 	vmx = vlapic_vtx->vmx;
3837 	vmcs = &vmx->vmcs[vlapic->vcpuid];
3838 	mask = 1UL << (vector % 64);
3839 
3840 	VMPTRLD(vmcs);
3841 	val = vmcs_read(VMCS_EOI_EXIT(vector));
3842 	if (level)
3843 		val |= mask;
3844 	else
3845 		val &= ~mask;
3846 	vmcs_write(VMCS_EOI_EXIT(vector), val);
3847 	VMCLEAR(vmcs);
3848 }
3849 
3850 static void
3851 vmx_enable_x2apic_mode_ts(struct vlapic *vlapic)
3852 {
3853 	struct vmx *vmx;
3854 	struct vmcs *vmcs;
3855 	uint32_t proc_ctls;
3856 	int vcpuid;
3857 
3858 	vcpuid = vlapic->vcpuid;
3859 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3860 	vmcs = &vmx->vmcs[vcpuid];
3861 
3862 	proc_ctls = vmx->cap[vcpuid].proc_ctls;
3863 	proc_ctls &= ~PROCBASED_USE_TPR_SHADOW;
3864 	proc_ctls |= PROCBASED_CR8_LOAD_EXITING;
3865 	proc_ctls |= PROCBASED_CR8_STORE_EXITING;
3866 	vmx->cap[vcpuid].proc_ctls = proc_ctls;
3867 
3868 	VMPTRLD(vmcs);
3869 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
3870 	VMCLEAR(vmcs);
3871 }
3872 
3873 static void
3874 vmx_enable_x2apic_mode_vid(struct vlapic *vlapic)
3875 {
3876 	struct vmx *vmx;
3877 	struct vmcs *vmcs;
3878 	uint32_t proc_ctls2;
3879 	int vcpuid, error __diagused;
3880 
3881 	vcpuid = vlapic->vcpuid;
3882 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3883 	vmcs = &vmx->vmcs[vcpuid];
3884 
3885 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3886 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3887 	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3888 
3889 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3890 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3891 	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3892 
3893 	VMPTRLD(vmcs);
3894 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3895 	VMCLEAR(vmcs);
3896 
3897 	if (vlapic->vcpuid == 0) {
3898 		/*
3899 		 * The nested page table mappings are shared by all vcpus
3900 		 * so unmap the APIC access page just once.
3901 		 */
3902 		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3903 		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3904 		    __func__, error));
3905 
3906 		/*
3907 		 * The MSR bitmap is shared by all vcpus so modify it only
3908 		 * once in the context of vcpu 0.
3909 		 */
3910 		error = vmx_allow_x2apic_msrs(vmx);
3911 		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3912 		    __func__, error));
3913 	}
3914 }
3915 
3916 static void
3917 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3918 {
3919 
3920 	ipi_cpu(hostcpu, pirvec);
3921 }
3922 
3923 /*
3924  * Transfer the pending interrupts in the PIR descriptor to the IRR
3925  * in the virtual APIC page.
3926  */
3927 static void
3928 vmx_inject_pir(struct vlapic *vlapic)
3929 {
3930 	struct vlapic_vtx *vlapic_vtx;
3931 	struct pir_desc *pir_desc;
3932 	struct LAPIC *lapic;
3933 	uint64_t val, pirval;
3934 	int rvi, pirbase = -1;
3935 	uint16_t intr_status_old, intr_status_new;
3936 
3937 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3938 	pir_desc = vlapic_vtx->pir_desc;
3939 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3940 		VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3941 		    "no posted interrupt pending");
3942 		return;
3943 	}
3944 
3945 	pirval = 0;
3946 	pirbase = -1;
3947 	lapic = vlapic->apic_page;
3948 
3949 	val = atomic_readandclear_long(&pir_desc->pir[0]);
3950 	if (val != 0) {
3951 		lapic->irr0 |= val;
3952 		lapic->irr1 |= val >> 32;
3953 		pirbase = 0;
3954 		pirval = val;
3955 	}
3956 
3957 	val = atomic_readandclear_long(&pir_desc->pir[1]);
3958 	if (val != 0) {
3959 		lapic->irr2 |= val;
3960 		lapic->irr3 |= val >> 32;
3961 		pirbase = 64;
3962 		pirval = val;
3963 	}
3964 
3965 	val = atomic_readandclear_long(&pir_desc->pir[2]);
3966 	if (val != 0) {
3967 		lapic->irr4 |= val;
3968 		lapic->irr5 |= val >> 32;
3969 		pirbase = 128;
3970 		pirval = val;
3971 	}
3972 
3973 	val = atomic_readandclear_long(&pir_desc->pir[3]);
3974 	if (val != 0) {
3975 		lapic->irr6 |= val;
3976 		lapic->irr7 |= val >> 32;
3977 		pirbase = 192;
3978 		pirval = val;
3979 	}
3980 
3981 	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3982 
3983 	/*
3984 	 * Update RVI so the processor can evaluate pending virtual
3985 	 * interrupts on VM-entry.
3986 	 *
3987 	 * It is possible for pirval to be 0 here, even though the
3988 	 * pending bit has been set. The scenario is:
3989 	 * CPU-Y is sending a posted interrupt to CPU-X, which
3990 	 * is running a guest and processing posted interrupts in h/w.
3991 	 * CPU-X will eventually exit and the state seen in s/w is
3992 	 * the pending bit set, but no PIR bits set.
3993 	 *
3994 	 *      CPU-X                      CPU-Y
3995 	 *   (vm running)                (host running)
3996 	 *   rx posted interrupt
3997 	 *   CLEAR pending bit
3998 	 *				 SET PIR bit
3999 	 *   READ/CLEAR PIR bits
4000 	 *				 SET pending bit
4001 	 *   (vm exit)
4002 	 *   pending bit set, PIR 0
4003 	 */
4004 	if (pirval != 0) {
4005 		rvi = pirbase + flsl(pirval) - 1;
4006 		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
4007 		intr_status_new = (intr_status_old & 0xFF00) | rvi;
4008 		if (intr_status_new > intr_status_old) {
4009 			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
4010 			VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
4011 			    "guest_intr_status changed from 0x%04x to 0x%04x",
4012 			    intr_status_old, intr_status_new);
4013 		}
4014 	}
4015 }
4016 
4017 static struct vlapic *
4018 vmx_vlapic_init(void *arg, int vcpuid)
4019 {
4020 	struct vmx *vmx;
4021 	struct vlapic *vlapic;
4022 	struct vlapic_vtx *vlapic_vtx;
4023 
4024 	vmx = arg;
4025 
4026 	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
4027 	vlapic->vm = vmx->vm;
4028 	vlapic->vcpuid = vcpuid;
4029 	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
4030 
4031 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
4032 	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
4033 	vlapic_vtx->vmx = vmx;
4034 
4035 	if (tpr_shadowing) {
4036 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_ts;
4037 	}
4038 
4039 	if (virtual_interrupt_delivery) {
4040 		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
4041 		vlapic->ops.pending_intr = vmx_pending_intr;
4042 		vlapic->ops.intr_accepted = vmx_intr_accepted;
4043 		vlapic->ops.set_tmr = vmx_set_tmr;
4044 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_vid;
4045 	}
4046 
4047 	if (posted_interrupts)
4048 		vlapic->ops.post_intr = vmx_post_intr;
4049 
4050 	vlapic_init(vlapic);
4051 
4052 	return (vlapic);
4053 }
4054 
4055 static void
4056 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
4057 {
4058 
4059 	vlapic_cleanup(vlapic);
4060 	free(vlapic, M_VLAPIC);
4061 }
4062 
4063 #ifdef BHYVE_SNAPSHOT
4064 static int
4065 vmx_snapshot(void *arg, struct vm_snapshot_meta *meta)
4066 {
4067 	struct vmx *vmx;
4068 	struct vmxctx *vmxctx;
4069 	int i;
4070 	int ret;
4071 
4072 	vmx = arg;
4073 
4074 	KASSERT(vmx != NULL, ("%s: arg was NULL", __func__));
4075 
4076 	for (i = 0; i < VM_MAXCPU; i++) {
4077 		SNAPSHOT_BUF_OR_LEAVE(vmx->guest_msrs[i],
4078 		      sizeof(vmx->guest_msrs[i]), meta, ret, done);
4079 
4080 		vmxctx = &vmx->ctx[i];
4081 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdi, meta, ret, done);
4082 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rsi, meta, ret, done);
4083 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdx, meta, ret, done);
4084 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rcx, meta, ret, done);
4085 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r8, meta, ret, done);
4086 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r9, meta, ret, done);
4087 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rax, meta, ret, done);
4088 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbx, meta, ret, done);
4089 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbp, meta, ret, done);
4090 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r10, meta, ret, done);
4091 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r11, meta, ret, done);
4092 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r12, meta, ret, done);
4093 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r13, meta, ret, done);
4094 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r14, meta, ret, done);
4095 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r15, meta, ret, done);
4096 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_cr2, meta, ret, done);
4097 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr0, meta, ret, done);
4098 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr1, meta, ret, done);
4099 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr2, meta, ret, done);
4100 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr3, meta, ret, done);
4101 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr6, meta, ret, done);
4102 	}
4103 
4104 done:
4105 	return (ret);
4106 }
4107 
4108 static int
4109 vmx_vmcx_snapshot(void *arg, struct vm_snapshot_meta *meta, int vcpu)
4110 {
4111 	struct vmcs *vmcs;
4112 	struct vmx *vmx;
4113 	int err, run, hostcpu;
4114 
4115 	vmx = (struct vmx *)arg;
4116 	err = 0;
4117 
4118 	KASSERT(arg != NULL, ("%s: arg was NULL", __func__));
4119 	vmcs = &vmx->vmcs[vcpu];
4120 
4121 	run = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
4122 	if (run && hostcpu != curcpu) {
4123 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm), vcpu);
4124 		return (EINVAL);
4125 	}
4126 
4127 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR0, meta);
4128 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR3, meta);
4129 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR4, meta);
4130 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DR7, meta);
4131 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RSP, meta);
4132 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RIP, meta);
4133 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RFLAGS, meta);
4134 
4135 	/* Guest segments */
4136 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_ES, meta);
4137 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_ES, meta);
4138 
4139 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CS, meta);
4140 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_CS, meta);
4141 
4142 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_SS, meta);
4143 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_SS, meta);
4144 
4145 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DS, meta);
4146 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_DS, meta);
4147 
4148 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_FS, meta);
4149 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_FS, meta);
4150 
4151 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_GS, meta);
4152 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GS, meta);
4153 
4154 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_TR, meta);
4155 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_TR, meta);
4156 
4157 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_LDTR, meta);
4158 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_LDTR, meta);
4159 
4160 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_EFER, meta);
4161 
4162 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_IDTR, meta);
4163 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GDTR, meta);
4164 
4165 	/* Guest page tables */
4166 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE0, meta);
4167 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE1, meta);
4168 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE2, meta);
4169 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE3, meta);
4170 
4171 	/* Other guest state */
4172 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_CS, meta);
4173 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_ESP, meta);
4174 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_EIP, meta);
4175 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_INTERRUPTIBILITY, meta);
4176 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_ACTIVITY, meta);
4177 	err += vmcs_snapshot_any(vmcs, run, VMCS_ENTRY_CTLS, meta);
4178 	err += vmcs_snapshot_any(vmcs, run, VMCS_EXIT_CTLS, meta);
4179 
4180 	return (err);
4181 }
4182 
4183 static int
4184 vmx_restore_tsc(void *arg, int vcpu, uint64_t offset)
4185 {
4186 	struct vmcs *vmcs;
4187 	struct vmx *vmx = (struct vmx *)arg;
4188 	int error, running, hostcpu;
4189 
4190 	KASSERT(arg != NULL, ("%s: arg was NULL", __func__));
4191 	vmcs = &vmx->vmcs[vcpu];
4192 
4193 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
4194 	if (running && hostcpu != curcpu) {
4195 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm), vcpu);
4196 		return (EINVAL);
4197 	}
4198 
4199 	if (!running)
4200 		VMPTRLD(vmcs);
4201 
4202 	error = vmx_set_tsc_offset(vmx, vcpu, offset);
4203 
4204 	if (!running)
4205 		VMCLEAR(vmcs);
4206 	return (error);
4207 }
4208 #endif
4209 
4210 const struct vmm_ops vmm_ops_intel = {
4211 	.modinit	= vmx_modinit,
4212 	.modcleanup	= vmx_modcleanup,
4213 	.modresume	= vmx_modresume,
4214 	.init		= vmx_init,
4215 	.run		= vmx_run,
4216 	.cleanup	= vmx_cleanup,
4217 	.getreg		= vmx_getreg,
4218 	.setreg		= vmx_setreg,
4219 	.getdesc	= vmx_getdesc,
4220 	.setdesc	= vmx_setdesc,
4221 	.getcap		= vmx_getcap,
4222 	.setcap		= vmx_setcap,
4223 	.vmspace_alloc	= vmx_vmspace_alloc,
4224 	.vmspace_free	= vmx_vmspace_free,
4225 	.vlapic_init	= vmx_vlapic_init,
4226 	.vlapic_cleanup	= vmx_vlapic_cleanup,
4227 #ifdef BHYVE_SNAPSHOT
4228 	.snapshot	= vmx_snapshot,
4229 	.vmcx_snapshot	= vmx_vmcx_snapshot,
4230 	.restore_tsc	= vmx_restore_tsc,
4231 #endif
4232 };
4233