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