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