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