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