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