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