xref: /freebsd/sys/amd64/vmm/intel/vmx.c (revision 96474d2a3fa895fb9636183403fc8ca7ccf60216)
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, func;
1197 
1198 	func = vmxctx->guest_rax;
1199 
1200 	handled = x86_emulate_cpuid(vm, vcpu,
1201 				    (uint32_t*)(&vmxctx->guest_rax),
1202 				    (uint32_t*)(&vmxctx->guest_rbx),
1203 				    (uint32_t*)(&vmxctx->guest_rcx),
1204 				    (uint32_t*)(&vmxctx->guest_rdx));
1205 	return (handled);
1206 }
1207 
1208 static __inline void
1209 vmx_run_trace(struct vmx *vmx, int vcpu)
1210 {
1211 #ifdef KTR
1212 	VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
1213 #endif
1214 }
1215 
1216 static __inline void
1217 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
1218 	       int handled)
1219 {
1220 #ifdef KTR
1221 	VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
1222 		 handled ? "handled" : "unhandled",
1223 		 exit_reason_to_str(exit_reason), rip);
1224 #endif
1225 }
1226 
1227 static __inline void
1228 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1229 {
1230 #ifdef KTR
1231 	VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1232 #endif
1233 }
1234 
1235 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1236 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1237 
1238 /*
1239  * Invalidate guest mappings identified by its vpid from the TLB.
1240  */
1241 static __inline void
1242 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1243 {
1244 	struct vmxstate *vmxstate;
1245 	struct invvpid_desc invvpid_desc;
1246 
1247 	vmxstate = &vmx->state[vcpu];
1248 	if (vmxstate->vpid == 0)
1249 		return;
1250 
1251 	if (!running) {
1252 		/*
1253 		 * Set the 'lastcpu' to an invalid host cpu.
1254 		 *
1255 		 * This will invalidate TLB entries tagged with the vcpu's
1256 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
1257 		 */
1258 		vmxstate->lastcpu = NOCPU;
1259 		return;
1260 	}
1261 
1262 	KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1263 	    "critical section", __func__, vcpu));
1264 
1265 	/*
1266 	 * Invalidate all mappings tagged with 'vpid'
1267 	 *
1268 	 * We do this because this vcpu was executing on a different host
1269 	 * cpu when it last ran. We do not track whether it invalidated
1270 	 * mappings associated with its 'vpid' during that run. So we must
1271 	 * assume that the mappings associated with 'vpid' on 'curcpu' are
1272 	 * stale and invalidate them.
1273 	 *
1274 	 * Note that we incur this penalty only when the scheduler chooses to
1275 	 * move the thread associated with this vcpu between host cpus.
1276 	 *
1277 	 * Note also that this will invalidate mappings tagged with 'vpid'
1278 	 * for "all" EP4TAs.
1279 	 */
1280 	if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1281 		invvpid_desc._res1 = 0;
1282 		invvpid_desc._res2 = 0;
1283 		invvpid_desc.vpid = vmxstate->vpid;
1284 		invvpid_desc.linear_addr = 0;
1285 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1286 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1287 	} else {
1288 		/*
1289 		 * The invvpid can be skipped if an invept is going to
1290 		 * be performed before entering the guest. The invept
1291 		 * will invalidate combined mappings tagged with
1292 		 * 'vmx->eptp' for all vpids.
1293 		 */
1294 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1295 	}
1296 }
1297 
1298 static void
1299 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1300 {
1301 	struct vmxstate *vmxstate;
1302 
1303 	vmxstate = &vmx->state[vcpu];
1304 	if (vmxstate->lastcpu == curcpu)
1305 		return;
1306 
1307 	vmxstate->lastcpu = curcpu;
1308 
1309 	vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1310 
1311 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1312 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1313 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1314 	vmx_invvpid(vmx, vcpu, pmap, 1);
1315 }
1316 
1317 /*
1318  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1319  */
1320 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1321 
1322 static void __inline
1323 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1324 {
1325 
1326 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1327 		vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1328 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1329 		VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1330 	}
1331 }
1332 
1333 static void __inline
1334 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1335 {
1336 
1337 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1338 	    ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1339 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1340 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1341 	VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1342 }
1343 
1344 static void __inline
1345 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1346 {
1347 
1348 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1349 		vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1350 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1351 		VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1352 	}
1353 }
1354 
1355 static void __inline
1356 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1357 {
1358 
1359 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1360 	    ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1361 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1362 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1363 	VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1364 }
1365 
1366 int
1367 vmx_set_tsc_offset(struct vmx *vmx, int vcpu, uint64_t offset)
1368 {
1369 	int error;
1370 
1371 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1372 		vmx->cap[vcpu].proc_ctls |= PROCBASED_TSC_OFFSET;
1373 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1374 		VCPU_CTR0(vmx->vm, vcpu, "Enabling TSC offsetting");
1375 	}
1376 
1377 	error = vmwrite(VMCS_TSC_OFFSET, offset);
1378 #ifdef BHYVE_SNAPSHOT
1379 	if (error == 0)
1380 		error = vm_set_tsc_offset(vmx->vm, vcpu, offset);
1381 #endif
1382 	return (error);
1383 }
1384 
1385 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1386 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1387 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1388 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1389 
1390 static void
1391 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1392 {
1393 	uint32_t gi, info;
1394 
1395 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1396 	KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1397 	    "interruptibility-state %#x", gi));
1398 
1399 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1400 	KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1401 	    "VM-entry interruption information %#x", info));
1402 
1403 	/*
1404 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1405 	 * or the VMCS entry check will fail.
1406 	 */
1407 	info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1408 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1409 
1410 	VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1411 
1412 	/* Clear the request */
1413 	vm_nmi_clear(vmx->vm, vcpu);
1414 }
1415 
1416 static void
1417 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1418     uint64_t guestrip)
1419 {
1420 	int vector, need_nmi_exiting, extint_pending;
1421 	uint64_t rflags, entryinfo;
1422 	uint32_t gi, info;
1423 
1424 	if (vmx->state[vcpu].nextrip != guestrip) {
1425 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1426 		if (gi & HWINTR_BLOCKING) {
1427 			VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1428 			    "cleared due to rip change: %#lx/%#lx",
1429 			    vmx->state[vcpu].nextrip, guestrip);
1430 			gi &= ~HWINTR_BLOCKING;
1431 			vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1432 		}
1433 	}
1434 
1435 	if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1436 		KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1437 		    "intinfo is not valid: %#lx", __func__, entryinfo));
1438 
1439 		info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1440 		KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1441 		     "pending exception: %#lx/%#x", __func__, entryinfo, info));
1442 
1443 		info = entryinfo;
1444 		vector = info & 0xff;
1445 		if (vector == IDT_BP || vector == IDT_OF) {
1446 			/*
1447 			 * VT-x requires #BP and #OF to be injected as software
1448 			 * exceptions.
1449 			 */
1450 			info &= ~VMCS_INTR_T_MASK;
1451 			info |= VMCS_INTR_T_SWEXCEPTION;
1452 		}
1453 
1454 		if (info & VMCS_INTR_DEL_ERRCODE)
1455 			vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1456 
1457 		vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1458 	}
1459 
1460 	if (vm_nmi_pending(vmx->vm, vcpu)) {
1461 		/*
1462 		 * If there are no conditions blocking NMI injection then
1463 		 * inject it directly here otherwise enable "NMI window
1464 		 * exiting" to inject it as soon as we can.
1465 		 *
1466 		 * We also check for STI_BLOCKING because some implementations
1467 		 * don't allow NMI injection in this case. If we are running
1468 		 * on a processor that doesn't have this restriction it will
1469 		 * immediately exit and the NMI will be injected in the
1470 		 * "NMI window exiting" handler.
1471 		 */
1472 		need_nmi_exiting = 1;
1473 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1474 		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1475 			info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1476 			if ((info & VMCS_INTR_VALID) == 0) {
1477 				vmx_inject_nmi(vmx, vcpu);
1478 				need_nmi_exiting = 0;
1479 			} else {
1480 				VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1481 				    "due to VM-entry intr info %#x", info);
1482 			}
1483 		} else {
1484 			VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1485 			    "Guest Interruptibility-state %#x", gi);
1486 		}
1487 
1488 		if (need_nmi_exiting)
1489 			vmx_set_nmi_window_exiting(vmx, vcpu);
1490 	}
1491 
1492 	extint_pending = vm_extint_pending(vmx->vm, vcpu);
1493 
1494 	if (!extint_pending && virtual_interrupt_delivery) {
1495 		vmx_inject_pir(vlapic);
1496 		return;
1497 	}
1498 
1499 	/*
1500 	 * If interrupt-window exiting is already in effect then don't bother
1501 	 * checking for pending interrupts. This is just an optimization and
1502 	 * not needed for correctness.
1503 	 */
1504 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1505 		VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1506 		    "pending int_window_exiting");
1507 		return;
1508 	}
1509 
1510 	if (!extint_pending) {
1511 		/* Ask the local apic for a vector to inject */
1512 		if (!vlapic_pending_intr(vlapic, &vector))
1513 			return;
1514 
1515 		/*
1516 		 * From the Intel SDM, Volume 3, Section "Maskable
1517 		 * Hardware Interrupts":
1518 		 * - maskable interrupt vectors [16,255] can be delivered
1519 		 *   through the local APIC.
1520 		*/
1521 		KASSERT(vector >= 16 && vector <= 255,
1522 		    ("invalid vector %d from local APIC", vector));
1523 	} else {
1524 		/* Ask the legacy pic for a vector to inject */
1525 		vatpic_pending_intr(vmx->vm, &vector);
1526 
1527 		/*
1528 		 * From the Intel SDM, Volume 3, Section "Maskable
1529 		 * Hardware Interrupts":
1530 		 * - maskable interrupt vectors [0,255] can be delivered
1531 		 *   through the INTR pin.
1532 		 */
1533 		KASSERT(vector >= 0 && vector <= 255,
1534 		    ("invalid vector %d from INTR", vector));
1535 	}
1536 
1537 	/* Check RFLAGS.IF and the interruptibility state of the guest */
1538 	rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1539 	if ((rflags & PSL_I) == 0) {
1540 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1541 		    "rflags %#lx", vector, rflags);
1542 		goto cantinject;
1543 	}
1544 
1545 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1546 	if (gi & HWINTR_BLOCKING) {
1547 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1548 		    "Guest Interruptibility-state %#x", vector, gi);
1549 		goto cantinject;
1550 	}
1551 
1552 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1553 	if (info & VMCS_INTR_VALID) {
1554 		/*
1555 		 * This is expected and could happen for multiple reasons:
1556 		 * - A vectoring VM-entry was aborted due to astpending
1557 		 * - A VM-exit happened during event injection.
1558 		 * - An exception was injected above.
1559 		 * - An NMI was injected above or after "NMI window exiting"
1560 		 */
1561 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1562 		    "VM-entry intr info %#x", vector, info);
1563 		goto cantinject;
1564 	}
1565 
1566 	/* Inject the interrupt */
1567 	info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1568 	info |= vector;
1569 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1570 
1571 	if (!extint_pending) {
1572 		/* Update the Local APIC ISR */
1573 		vlapic_intr_accepted(vlapic, vector);
1574 	} else {
1575 		vm_extint_clear(vmx->vm, vcpu);
1576 		vatpic_intr_accepted(vmx->vm, vector);
1577 
1578 		/*
1579 		 * After we accepted the current ExtINT the PIC may
1580 		 * have posted another one.  If that is the case, set
1581 		 * the Interrupt Window Exiting execution control so
1582 		 * we can inject that one too.
1583 		 *
1584 		 * Also, interrupt window exiting allows us to inject any
1585 		 * pending APIC vector that was preempted by the ExtINT
1586 		 * as soon as possible. This applies both for the software
1587 		 * emulated vlapic and the hardware assisted virtual APIC.
1588 		 */
1589 		vmx_set_int_window_exiting(vmx, vcpu);
1590 	}
1591 
1592 	VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1593 
1594 	return;
1595 
1596 cantinject:
1597 	/*
1598 	 * Set the Interrupt Window Exiting execution control so we can inject
1599 	 * the interrupt as soon as blocking condition goes away.
1600 	 */
1601 	vmx_set_int_window_exiting(vmx, vcpu);
1602 }
1603 
1604 /*
1605  * If the Virtual NMIs execution control is '1' then the logical processor
1606  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1607  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1608  * virtual-NMI blocking.
1609  *
1610  * This unblocking occurs even if the IRET causes a fault. In this case the
1611  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1612  */
1613 static void
1614 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1615 {
1616 	uint32_t gi;
1617 
1618 	VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1619 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1620 	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1621 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1622 }
1623 
1624 static void
1625 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1626 {
1627 	uint32_t gi;
1628 
1629 	VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1630 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1631 	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1632 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1633 }
1634 
1635 static void
1636 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1637 {
1638 	uint32_t gi;
1639 
1640 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1641 	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1642 	    ("NMI blocking is not in effect %#x", gi));
1643 }
1644 
1645 static int
1646 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1647 {
1648 	struct vmxctx *vmxctx;
1649 	uint64_t xcrval;
1650 	const struct xsave_limits *limits;
1651 
1652 	vmxctx = &vmx->ctx[vcpu];
1653 	limits = vmm_get_xsave_limits();
1654 
1655 	/*
1656 	 * Note that the processor raises a GP# fault on its own if
1657 	 * xsetbv is executed for CPL != 0, so we do not have to
1658 	 * emulate that fault here.
1659 	 */
1660 
1661 	/* Only xcr0 is supported. */
1662 	if (vmxctx->guest_rcx != 0) {
1663 		vm_inject_gp(vmx->vm, vcpu);
1664 		return (HANDLED);
1665 	}
1666 
1667 	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1668 	if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1669 		vm_inject_ud(vmx->vm, vcpu);
1670 		return (HANDLED);
1671 	}
1672 
1673 	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1674 	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1675 		vm_inject_gp(vmx->vm, vcpu);
1676 		return (HANDLED);
1677 	}
1678 
1679 	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1680 		vm_inject_gp(vmx->vm, vcpu);
1681 		return (HANDLED);
1682 	}
1683 
1684 	/* AVX (YMM_Hi128) requires SSE. */
1685 	if (xcrval & XFEATURE_ENABLED_AVX &&
1686 	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1687 		vm_inject_gp(vmx->vm, vcpu);
1688 		return (HANDLED);
1689 	}
1690 
1691 	/*
1692 	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1693 	 * ZMM_Hi256, and Hi16_ZMM.
1694 	 */
1695 	if (xcrval & XFEATURE_AVX512 &&
1696 	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1697 	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1698 		vm_inject_gp(vmx->vm, vcpu);
1699 		return (HANDLED);
1700 	}
1701 
1702 	/*
1703 	 * Intel MPX requires both bound register state flags to be
1704 	 * set.
1705 	 */
1706 	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1707 	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1708 		vm_inject_gp(vmx->vm, vcpu);
1709 		return (HANDLED);
1710 	}
1711 
1712 	/*
1713 	 * This runs "inside" vmrun() with the guest's FPU state, so
1714 	 * modifying xcr0 directly modifies the guest's xcr0, not the
1715 	 * host's.
1716 	 */
1717 	load_xcr(0, xcrval);
1718 	return (HANDLED);
1719 }
1720 
1721 static uint64_t
1722 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1723 {
1724 	const struct vmxctx *vmxctx;
1725 
1726 	vmxctx = &vmx->ctx[vcpu];
1727 
1728 	switch (ident) {
1729 	case 0:
1730 		return (vmxctx->guest_rax);
1731 	case 1:
1732 		return (vmxctx->guest_rcx);
1733 	case 2:
1734 		return (vmxctx->guest_rdx);
1735 	case 3:
1736 		return (vmxctx->guest_rbx);
1737 	case 4:
1738 		return (vmcs_read(VMCS_GUEST_RSP));
1739 	case 5:
1740 		return (vmxctx->guest_rbp);
1741 	case 6:
1742 		return (vmxctx->guest_rsi);
1743 	case 7:
1744 		return (vmxctx->guest_rdi);
1745 	case 8:
1746 		return (vmxctx->guest_r8);
1747 	case 9:
1748 		return (vmxctx->guest_r9);
1749 	case 10:
1750 		return (vmxctx->guest_r10);
1751 	case 11:
1752 		return (vmxctx->guest_r11);
1753 	case 12:
1754 		return (vmxctx->guest_r12);
1755 	case 13:
1756 		return (vmxctx->guest_r13);
1757 	case 14:
1758 		return (vmxctx->guest_r14);
1759 	case 15:
1760 		return (vmxctx->guest_r15);
1761 	default:
1762 		panic("invalid vmx register %d", ident);
1763 	}
1764 }
1765 
1766 static void
1767 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1768 {
1769 	struct vmxctx *vmxctx;
1770 
1771 	vmxctx = &vmx->ctx[vcpu];
1772 
1773 	switch (ident) {
1774 	case 0:
1775 		vmxctx->guest_rax = regval;
1776 		break;
1777 	case 1:
1778 		vmxctx->guest_rcx = regval;
1779 		break;
1780 	case 2:
1781 		vmxctx->guest_rdx = regval;
1782 		break;
1783 	case 3:
1784 		vmxctx->guest_rbx = regval;
1785 		break;
1786 	case 4:
1787 		vmcs_write(VMCS_GUEST_RSP, regval);
1788 		break;
1789 	case 5:
1790 		vmxctx->guest_rbp = regval;
1791 		break;
1792 	case 6:
1793 		vmxctx->guest_rsi = regval;
1794 		break;
1795 	case 7:
1796 		vmxctx->guest_rdi = regval;
1797 		break;
1798 	case 8:
1799 		vmxctx->guest_r8 = regval;
1800 		break;
1801 	case 9:
1802 		vmxctx->guest_r9 = regval;
1803 		break;
1804 	case 10:
1805 		vmxctx->guest_r10 = regval;
1806 		break;
1807 	case 11:
1808 		vmxctx->guest_r11 = regval;
1809 		break;
1810 	case 12:
1811 		vmxctx->guest_r12 = regval;
1812 		break;
1813 	case 13:
1814 		vmxctx->guest_r13 = regval;
1815 		break;
1816 	case 14:
1817 		vmxctx->guest_r14 = regval;
1818 		break;
1819 	case 15:
1820 		vmxctx->guest_r15 = regval;
1821 		break;
1822 	default:
1823 		panic("invalid vmx register %d", ident);
1824 	}
1825 }
1826 
1827 static int
1828 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1829 {
1830 	uint64_t crval, regval;
1831 
1832 	/* We only handle mov to %cr0 at this time */
1833 	if ((exitqual & 0xf0) != 0x00)
1834 		return (UNHANDLED);
1835 
1836 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1837 
1838 	vmcs_write(VMCS_CR0_SHADOW, regval);
1839 
1840 	crval = regval | cr0_ones_mask;
1841 	crval &= ~cr0_zeros_mask;
1842 	vmcs_write(VMCS_GUEST_CR0, crval);
1843 
1844 	if (regval & CR0_PG) {
1845 		uint64_t efer, entry_ctls;
1846 
1847 		/*
1848 		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1849 		 * the "IA-32e mode guest" bit in VM-entry control must be
1850 		 * equal.
1851 		 */
1852 		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1853 		if (efer & EFER_LME) {
1854 			efer |= EFER_LMA;
1855 			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1856 			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1857 			entry_ctls |= VM_ENTRY_GUEST_LMA;
1858 			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1859 		}
1860 	}
1861 
1862 	return (HANDLED);
1863 }
1864 
1865 static int
1866 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1867 {
1868 	uint64_t crval, regval;
1869 
1870 	/* We only handle mov to %cr4 at this time */
1871 	if ((exitqual & 0xf0) != 0x00)
1872 		return (UNHANDLED);
1873 
1874 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1875 
1876 	vmcs_write(VMCS_CR4_SHADOW, regval);
1877 
1878 	crval = regval | cr4_ones_mask;
1879 	crval &= ~cr4_zeros_mask;
1880 	vmcs_write(VMCS_GUEST_CR4, crval);
1881 
1882 	return (HANDLED);
1883 }
1884 
1885 static int
1886 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1887 {
1888 	struct vlapic *vlapic;
1889 	uint64_t cr8;
1890 	int regnum;
1891 
1892 	/* We only handle mov %cr8 to/from a register at this time. */
1893 	if ((exitqual & 0xe0) != 0x00) {
1894 		return (UNHANDLED);
1895 	}
1896 
1897 	vlapic = vm_lapic(vmx->vm, vcpu);
1898 	regnum = (exitqual >> 8) & 0xf;
1899 	if (exitqual & 0x10) {
1900 		cr8 = vlapic_get_cr8(vlapic);
1901 		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1902 	} else {
1903 		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1904 		vlapic_set_cr8(vlapic, cr8);
1905 	}
1906 
1907 	return (HANDLED);
1908 }
1909 
1910 /*
1911  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1912  */
1913 static int
1914 vmx_cpl(void)
1915 {
1916 	uint32_t ssar;
1917 
1918 	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1919 	return ((ssar >> 5) & 0x3);
1920 }
1921 
1922 static enum vm_cpu_mode
1923 vmx_cpu_mode(void)
1924 {
1925 	uint32_t csar;
1926 
1927 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1928 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1929 		if (csar & 0x2000)
1930 			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1931 		else
1932 			return (CPU_MODE_COMPATIBILITY);
1933 	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1934 		return (CPU_MODE_PROTECTED);
1935 	} else {
1936 		return (CPU_MODE_REAL);
1937 	}
1938 }
1939 
1940 static enum vm_paging_mode
1941 vmx_paging_mode(void)
1942 {
1943 	uint64_t cr4;
1944 
1945 	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1946 		return (PAGING_MODE_FLAT);
1947 	cr4 = vmcs_read(VMCS_GUEST_CR4);
1948 	if (!(cr4 & CR4_PAE))
1949 		return (PAGING_MODE_32);
1950 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME) {
1951 		if (!(cr4 & CR4_LA57))
1952 			return (PAGING_MODE_64);
1953 		return (PAGING_MODE_64_LA57);
1954 	} else
1955 		return (PAGING_MODE_PAE);
1956 }
1957 
1958 static uint64_t
1959 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1960 {
1961 	uint64_t val;
1962 	int error;
1963 	enum vm_reg_name reg;
1964 
1965 	reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1966 	error = vmx_getreg(vmx, vcpuid, reg, &val);
1967 	KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1968 	return (val);
1969 }
1970 
1971 static uint64_t
1972 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1973 {
1974 	uint64_t val;
1975 	int error;
1976 
1977 	if (rep) {
1978 		error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1979 		KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1980 	} else {
1981 		val = 1;
1982 	}
1983 	return (val);
1984 }
1985 
1986 static int
1987 inout_str_addrsize(uint32_t inst_info)
1988 {
1989 	uint32_t size;
1990 
1991 	size = (inst_info >> 7) & 0x7;
1992 	switch (size) {
1993 	case 0:
1994 		return (2);	/* 16 bit */
1995 	case 1:
1996 		return (4);	/* 32 bit */
1997 	case 2:
1998 		return (8);	/* 64 bit */
1999 	default:
2000 		panic("%s: invalid size encoding %d", __func__, size);
2001 	}
2002 }
2003 
2004 static void
2005 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
2006     struct vm_inout_str *vis)
2007 {
2008 	int error, s;
2009 
2010 	if (in) {
2011 		vis->seg_name = VM_REG_GUEST_ES;
2012 	} else {
2013 		s = (inst_info >> 15) & 0x7;
2014 		vis->seg_name = vm_segment_name(s);
2015 	}
2016 
2017 	error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
2018 	KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
2019 }
2020 
2021 static void
2022 vmx_paging_info(struct vm_guest_paging *paging)
2023 {
2024 	paging->cr3 = vmcs_guest_cr3();
2025 	paging->cpl = vmx_cpl();
2026 	paging->cpu_mode = vmx_cpu_mode();
2027 	paging->paging_mode = vmx_paging_mode();
2028 }
2029 
2030 static void
2031 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
2032 {
2033 	struct vm_guest_paging *paging;
2034 	uint32_t csar;
2035 
2036 	paging = &vmexit->u.inst_emul.paging;
2037 
2038 	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
2039 	vmexit->inst_length = 0;
2040 	vmexit->u.inst_emul.gpa = gpa;
2041 	vmexit->u.inst_emul.gla = gla;
2042 	vmx_paging_info(paging);
2043 	switch (paging->cpu_mode) {
2044 	case CPU_MODE_REAL:
2045 		vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
2046 		vmexit->u.inst_emul.cs_d = 0;
2047 		break;
2048 	case CPU_MODE_PROTECTED:
2049 	case CPU_MODE_COMPATIBILITY:
2050 		vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
2051 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
2052 		vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
2053 		break;
2054 	default:
2055 		vmexit->u.inst_emul.cs_base = 0;
2056 		vmexit->u.inst_emul.cs_d = 0;
2057 		break;
2058 	}
2059 	vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
2060 }
2061 
2062 static int
2063 ept_fault_type(uint64_t ept_qual)
2064 {
2065 	int fault_type;
2066 
2067 	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
2068 		fault_type = VM_PROT_WRITE;
2069 	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
2070 		fault_type = VM_PROT_EXECUTE;
2071 	else
2072 		fault_type= VM_PROT_READ;
2073 
2074 	return (fault_type);
2075 }
2076 
2077 static bool
2078 ept_emulation_fault(uint64_t ept_qual)
2079 {
2080 	int read, write;
2081 
2082 	/* EPT fault on an instruction fetch doesn't make sense here */
2083 	if (ept_qual & EPT_VIOLATION_INST_FETCH)
2084 		return (false);
2085 
2086 	/* EPT fault must be a read fault or a write fault */
2087 	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
2088 	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
2089 	if ((read | write) == 0)
2090 		return (false);
2091 
2092 	/*
2093 	 * The EPT violation must have been caused by accessing a
2094 	 * guest-physical address that is a translation of a guest-linear
2095 	 * address.
2096 	 */
2097 	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
2098 	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
2099 		return (false);
2100 	}
2101 
2102 	return (true);
2103 }
2104 
2105 static __inline int
2106 apic_access_virtualization(struct vmx *vmx, int vcpuid)
2107 {
2108 	uint32_t proc_ctls2;
2109 
2110 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
2111 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
2112 }
2113 
2114 static __inline int
2115 x2apic_virtualization(struct vmx *vmx, int vcpuid)
2116 {
2117 	uint32_t proc_ctls2;
2118 
2119 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
2120 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
2121 }
2122 
2123 static int
2124 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
2125     uint64_t qual)
2126 {
2127 	int error, handled, offset;
2128 	uint32_t *apic_regs, vector;
2129 	bool retu;
2130 
2131 	handled = HANDLED;
2132 	offset = APIC_WRITE_OFFSET(qual);
2133 
2134 	if (!apic_access_virtualization(vmx, vcpuid)) {
2135 		/*
2136 		 * In general there should not be any APIC write VM-exits
2137 		 * unless APIC-access virtualization is enabled.
2138 		 *
2139 		 * However self-IPI virtualization can legitimately trigger
2140 		 * an APIC-write VM-exit so treat it specially.
2141 		 */
2142 		if (x2apic_virtualization(vmx, vcpuid) &&
2143 		    offset == APIC_OFFSET_SELF_IPI) {
2144 			apic_regs = (uint32_t *)(vlapic->apic_page);
2145 			vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
2146 			vlapic_self_ipi_handler(vlapic, vector);
2147 			return (HANDLED);
2148 		} else
2149 			return (UNHANDLED);
2150 	}
2151 
2152 	switch (offset) {
2153 	case APIC_OFFSET_ID:
2154 		vlapic_id_write_handler(vlapic);
2155 		break;
2156 	case APIC_OFFSET_LDR:
2157 		vlapic_ldr_write_handler(vlapic);
2158 		break;
2159 	case APIC_OFFSET_DFR:
2160 		vlapic_dfr_write_handler(vlapic);
2161 		break;
2162 	case APIC_OFFSET_SVR:
2163 		vlapic_svr_write_handler(vlapic);
2164 		break;
2165 	case APIC_OFFSET_ESR:
2166 		vlapic_esr_write_handler(vlapic);
2167 		break;
2168 	case APIC_OFFSET_ICR_LOW:
2169 		retu = false;
2170 		error = vlapic_icrlo_write_handler(vlapic, &retu);
2171 		if (error != 0 || retu)
2172 			handled = UNHANDLED;
2173 		break;
2174 	case APIC_OFFSET_CMCI_LVT:
2175 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
2176 		vlapic_lvt_write_handler(vlapic, offset);
2177 		break;
2178 	case APIC_OFFSET_TIMER_ICR:
2179 		vlapic_icrtmr_write_handler(vlapic);
2180 		break;
2181 	case APIC_OFFSET_TIMER_DCR:
2182 		vlapic_dcr_write_handler(vlapic);
2183 		break;
2184 	default:
2185 		handled = UNHANDLED;
2186 		break;
2187 	}
2188 	return (handled);
2189 }
2190 
2191 static bool
2192 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
2193 {
2194 
2195 	if (apic_access_virtualization(vmx, vcpuid) &&
2196 	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
2197 		return (true);
2198 	else
2199 		return (false);
2200 }
2201 
2202 static int
2203 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2204 {
2205 	uint64_t qual;
2206 	int access_type, offset, allowed;
2207 
2208 	if (!apic_access_virtualization(vmx, vcpuid))
2209 		return (UNHANDLED);
2210 
2211 	qual = vmexit->u.vmx.exit_qualification;
2212 	access_type = APIC_ACCESS_TYPE(qual);
2213 	offset = APIC_ACCESS_OFFSET(qual);
2214 
2215 	allowed = 0;
2216 	if (access_type == 0) {
2217 		/*
2218 		 * Read data access to the following registers is expected.
2219 		 */
2220 		switch (offset) {
2221 		case APIC_OFFSET_APR:
2222 		case APIC_OFFSET_PPR:
2223 		case APIC_OFFSET_RRR:
2224 		case APIC_OFFSET_CMCI_LVT:
2225 		case APIC_OFFSET_TIMER_CCR:
2226 			allowed = 1;
2227 			break;
2228 		default:
2229 			break;
2230 		}
2231 	} else if (access_type == 1) {
2232 		/*
2233 		 * Write data access to the following registers is expected.
2234 		 */
2235 		switch (offset) {
2236 		case APIC_OFFSET_VER:
2237 		case APIC_OFFSET_APR:
2238 		case APIC_OFFSET_PPR:
2239 		case APIC_OFFSET_RRR:
2240 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2241 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2242 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2243 		case APIC_OFFSET_CMCI_LVT:
2244 		case APIC_OFFSET_TIMER_CCR:
2245 			allowed = 1;
2246 			break;
2247 		default:
2248 			break;
2249 		}
2250 	}
2251 
2252 	if (allowed) {
2253 		vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2254 		    VIE_INVALID_GLA);
2255 	}
2256 
2257 	/*
2258 	 * Regardless of whether the APIC-access is allowed this handler
2259 	 * always returns UNHANDLED:
2260 	 * - if the access is allowed then it is handled by emulating the
2261 	 *   instruction that caused the VM-exit (outside the critical section)
2262 	 * - if the access is not allowed then it will be converted to an
2263 	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2264 	 */
2265 	return (UNHANDLED);
2266 }
2267 
2268 static enum task_switch_reason
2269 vmx_task_switch_reason(uint64_t qual)
2270 {
2271 	int reason;
2272 
2273 	reason = (qual >> 30) & 0x3;
2274 	switch (reason) {
2275 	case 0:
2276 		return (TSR_CALL);
2277 	case 1:
2278 		return (TSR_IRET);
2279 	case 2:
2280 		return (TSR_JMP);
2281 	case 3:
2282 		return (TSR_IDT_GATE);
2283 	default:
2284 		panic("%s: invalid reason %d", __func__, reason);
2285 	}
2286 }
2287 
2288 static int
2289 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2290 {
2291 	int error;
2292 
2293 	if (lapic_msr(num))
2294 		error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2295 	else
2296 		error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2297 
2298 	return (error);
2299 }
2300 
2301 static int
2302 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2303 {
2304 	struct vmxctx *vmxctx;
2305 	uint64_t result;
2306 	uint32_t eax, edx;
2307 	int error;
2308 
2309 	if (lapic_msr(num))
2310 		error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2311 	else
2312 		error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2313 
2314 	if (error == 0) {
2315 		eax = result;
2316 		vmxctx = &vmx->ctx[vcpuid];
2317 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2318 		KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2319 
2320 		edx = result >> 32;
2321 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2322 		KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2323 	}
2324 
2325 	return (error);
2326 }
2327 
2328 static int
2329 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2330 {
2331 	int error, errcode, errcode_valid, handled, in;
2332 	struct vmxctx *vmxctx;
2333 	struct vlapic *vlapic;
2334 	struct vm_inout_str *vis;
2335 	struct vm_task_switch *ts;
2336 	uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2337 	uint32_t intr_type, intr_vec, reason;
2338 	uint64_t exitintinfo, qual, gpa;
2339 	bool retu;
2340 
2341 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2342 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2343 
2344 	handled = UNHANDLED;
2345 	vmxctx = &vmx->ctx[vcpu];
2346 
2347 	qual = vmexit->u.vmx.exit_qualification;
2348 	reason = vmexit->u.vmx.exit_reason;
2349 	vmexit->exitcode = VM_EXITCODE_BOGUS;
2350 
2351 	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2352 	SDT_PROBE3(vmm, vmx, exit, entry, vmx, vcpu, vmexit);
2353 
2354 	/*
2355 	 * VM-entry failures during or after loading guest state.
2356 	 *
2357 	 * These VM-exits are uncommon but must be handled specially
2358 	 * as most VM-exit fields are not populated as usual.
2359 	 */
2360 	if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2361 		VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2362 		__asm __volatile("int $18");
2363 		return (1);
2364 	}
2365 
2366 	/*
2367 	 * VM exits that can be triggered during event delivery need to
2368 	 * be handled specially by re-injecting the event if the IDT
2369 	 * vectoring information field's valid bit is set.
2370 	 *
2371 	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2372 	 * for details.
2373 	 */
2374 	idtvec_info = vmcs_idt_vectoring_info();
2375 	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2376 		idtvec_info &= ~(1 << 12); /* clear undefined bit */
2377 		exitintinfo = idtvec_info;
2378 		if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2379 			idtvec_err = vmcs_idt_vectoring_err();
2380 			exitintinfo |= (uint64_t)idtvec_err << 32;
2381 		}
2382 		error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2383 		KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2384 		    __func__, error));
2385 
2386 		/*
2387 		 * If 'virtual NMIs' are being used and the VM-exit
2388 		 * happened while injecting an NMI during the previous
2389 		 * VM-entry, then clear "blocking by NMI" in the
2390 		 * Guest Interruptibility-State so the NMI can be
2391 		 * reinjected on the subsequent VM-entry.
2392 		 *
2393 		 * However, if the NMI was being delivered through a task
2394 		 * gate, then the new task must start execution with NMIs
2395 		 * blocked so don't clear NMI blocking in this case.
2396 		 */
2397 		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2398 		if (intr_type == VMCS_INTR_T_NMI) {
2399 			if (reason != EXIT_REASON_TASK_SWITCH)
2400 				vmx_clear_nmi_blocking(vmx, vcpu);
2401 			else
2402 				vmx_assert_nmi_blocking(vmx, vcpu);
2403 		}
2404 
2405 		/*
2406 		 * Update VM-entry instruction length if the event being
2407 		 * delivered was a software interrupt or software exception.
2408 		 */
2409 		if (intr_type == VMCS_INTR_T_SWINTR ||
2410 		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2411 		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2412 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2413 		}
2414 	}
2415 
2416 	switch (reason) {
2417 	case EXIT_REASON_TASK_SWITCH:
2418 		ts = &vmexit->u.task_switch;
2419 		ts->tsssel = qual & 0xffff;
2420 		ts->reason = vmx_task_switch_reason(qual);
2421 		ts->ext = 0;
2422 		ts->errcode_valid = 0;
2423 		vmx_paging_info(&ts->paging);
2424 		/*
2425 		 * If the task switch was due to a CALL, JMP, IRET, software
2426 		 * interrupt (INT n) or software exception (INT3, INTO),
2427 		 * then the saved %rip references the instruction that caused
2428 		 * the task switch. The instruction length field in the VMCS
2429 		 * is valid in this case.
2430 		 *
2431 		 * In all other cases (e.g., NMI, hardware exception) the
2432 		 * saved %rip is one that would have been saved in the old TSS
2433 		 * had the task switch completed normally so the instruction
2434 		 * length field is not needed in this case and is explicitly
2435 		 * set to 0.
2436 		 */
2437 		if (ts->reason == TSR_IDT_GATE) {
2438 			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2439 			    ("invalid idtvec_info %#x for IDT task switch",
2440 			    idtvec_info));
2441 			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2442 			if (intr_type != VMCS_INTR_T_SWINTR &&
2443 			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2444 			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2445 				/* Task switch triggered by external event */
2446 				ts->ext = 1;
2447 				vmexit->inst_length = 0;
2448 				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2449 					ts->errcode_valid = 1;
2450 					ts->errcode = vmcs_idt_vectoring_err();
2451 				}
2452 			}
2453 		}
2454 		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2455 		SDT_PROBE4(vmm, vmx, exit, taskswitch, vmx, vcpu, vmexit, ts);
2456 		VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2457 		    "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2458 		    ts->ext ? "external" : "internal",
2459 		    ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2460 		break;
2461 	case EXIT_REASON_CR_ACCESS:
2462 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2463 		SDT_PROBE4(vmm, vmx, exit, craccess, vmx, vcpu, vmexit, qual);
2464 		switch (qual & 0xf) {
2465 		case 0:
2466 			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2467 			break;
2468 		case 4:
2469 			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2470 			break;
2471 		case 8:
2472 			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2473 			break;
2474 		}
2475 		break;
2476 	case EXIT_REASON_RDMSR:
2477 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2478 		retu = false;
2479 		ecx = vmxctx->guest_rcx;
2480 		VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2481 		SDT_PROBE4(vmm, vmx, exit, rdmsr, vmx, vcpu, vmexit, ecx);
2482 		error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2483 		if (error) {
2484 			vmexit->exitcode = VM_EXITCODE_RDMSR;
2485 			vmexit->u.msr.code = ecx;
2486 		} else if (!retu) {
2487 			handled = HANDLED;
2488 		} else {
2489 			/* Return to userspace with a valid exitcode */
2490 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2491 			    ("emulate_rdmsr retu with bogus exitcode"));
2492 		}
2493 		break;
2494 	case EXIT_REASON_WRMSR:
2495 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2496 		retu = false;
2497 		eax = vmxctx->guest_rax;
2498 		ecx = vmxctx->guest_rcx;
2499 		edx = vmxctx->guest_rdx;
2500 		VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2501 		    ecx, (uint64_t)edx << 32 | eax);
2502 		SDT_PROBE5(vmm, vmx, exit, wrmsr, vmx, vmexit, vcpu, ecx,
2503 		    (uint64_t)edx << 32 | eax);
2504 		error = emulate_wrmsr(vmx, vcpu, ecx,
2505 		    (uint64_t)edx << 32 | eax, &retu);
2506 		if (error) {
2507 			vmexit->exitcode = VM_EXITCODE_WRMSR;
2508 			vmexit->u.msr.code = ecx;
2509 			vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2510 		} else if (!retu) {
2511 			handled = HANDLED;
2512 		} else {
2513 			/* Return to userspace with a valid exitcode */
2514 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2515 			    ("emulate_wrmsr retu with bogus exitcode"));
2516 		}
2517 		break;
2518 	case EXIT_REASON_HLT:
2519 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2520 		SDT_PROBE3(vmm, vmx, exit, halt, vmx, vcpu, vmexit);
2521 		vmexit->exitcode = VM_EXITCODE_HLT;
2522 		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2523 		if (virtual_interrupt_delivery)
2524 			vmexit->u.hlt.intr_status =
2525 			    vmcs_read(VMCS_GUEST_INTR_STATUS);
2526 		else
2527 			vmexit->u.hlt.intr_status = 0;
2528 		break;
2529 	case EXIT_REASON_MTF:
2530 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2531 		SDT_PROBE3(vmm, vmx, exit, mtrap, vmx, vcpu, vmexit);
2532 		vmexit->exitcode = VM_EXITCODE_MTRAP;
2533 		vmexit->inst_length = 0;
2534 		break;
2535 	case EXIT_REASON_PAUSE:
2536 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2537 		SDT_PROBE3(vmm, vmx, exit, pause, vmx, vcpu, vmexit);
2538 		vmexit->exitcode = VM_EXITCODE_PAUSE;
2539 		break;
2540 	case EXIT_REASON_INTR_WINDOW:
2541 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2542 		SDT_PROBE3(vmm, vmx, exit, intrwindow, vmx, vcpu, vmexit);
2543 		vmx_clear_int_window_exiting(vmx, vcpu);
2544 		return (1);
2545 	case EXIT_REASON_EXT_INTR:
2546 		/*
2547 		 * External interrupts serve only to cause VM exits and allow
2548 		 * the host interrupt handler to run.
2549 		 *
2550 		 * If this external interrupt triggers a virtual interrupt
2551 		 * to a VM, then that state will be recorded by the
2552 		 * host interrupt handler in the VM's softc. We will inject
2553 		 * this virtual interrupt during the subsequent VM enter.
2554 		 */
2555 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2556 		SDT_PROBE4(vmm, vmx, exit, interrupt,
2557 		    vmx, vcpu, vmexit, intr_info);
2558 
2559 		/*
2560 		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2561 		 * This appears to be a bug in VMware Fusion?
2562 		 */
2563 		if (!(intr_info & VMCS_INTR_VALID))
2564 			return (1);
2565 		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2566 		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2567 		    ("VM exit interruption info invalid: %#x", intr_info));
2568 		vmx_trigger_hostintr(intr_info & 0xff);
2569 
2570 		/*
2571 		 * This is special. We want to treat this as an 'handled'
2572 		 * VM-exit but not increment the instruction pointer.
2573 		 */
2574 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2575 		return (1);
2576 	case EXIT_REASON_NMI_WINDOW:
2577 		SDT_PROBE3(vmm, vmx, exit, nmiwindow, vmx, vcpu, vmexit);
2578 		/* Exit to allow the pending virtual NMI to be injected */
2579 		if (vm_nmi_pending(vmx->vm, vcpu))
2580 			vmx_inject_nmi(vmx, vcpu);
2581 		vmx_clear_nmi_window_exiting(vmx, vcpu);
2582 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2583 		return (1);
2584 	case EXIT_REASON_INOUT:
2585 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2586 		vmexit->exitcode = VM_EXITCODE_INOUT;
2587 		vmexit->u.inout.bytes = (qual & 0x7) + 1;
2588 		vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2589 		vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2590 		vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2591 		vmexit->u.inout.port = (uint16_t)(qual >> 16);
2592 		vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2593 		if (vmexit->u.inout.string) {
2594 			inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2595 			vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2596 			vis = &vmexit->u.inout_str;
2597 			vmx_paging_info(&vis->paging);
2598 			vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2599 			vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2600 			vis->index = inout_str_index(vmx, vcpu, in);
2601 			vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2602 			vis->addrsize = inout_str_addrsize(inst_info);
2603 			inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2604 		}
2605 		SDT_PROBE3(vmm, vmx, exit, inout, vmx, vcpu, vmexit);
2606 		break;
2607 	case EXIT_REASON_CPUID:
2608 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2609 		SDT_PROBE3(vmm, vmx, exit, cpuid, vmx, vcpu, vmexit);
2610 		handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2611 		break;
2612 	case EXIT_REASON_EXCEPTION:
2613 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2614 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2615 		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2616 		    ("VM exit interruption info invalid: %#x", intr_info));
2617 
2618 		intr_vec = intr_info & 0xff;
2619 		intr_type = intr_info & VMCS_INTR_T_MASK;
2620 
2621 		/*
2622 		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2623 		 * fault encountered during the execution of IRET then we must
2624 		 * restore the state of "virtual-NMI blocking" before resuming
2625 		 * the guest.
2626 		 *
2627 		 * See "Resuming Guest Software after Handling an Exception".
2628 		 * See "Information for VM Exits Due to Vectored Events".
2629 		 */
2630 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2631 		    (intr_vec != IDT_DF) &&
2632 		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2633 			vmx_restore_nmi_blocking(vmx, vcpu);
2634 
2635 		/*
2636 		 * The NMI has already been handled in vmx_exit_handle_nmi().
2637 		 */
2638 		if (intr_type == VMCS_INTR_T_NMI)
2639 			return (1);
2640 
2641 		/*
2642 		 * Call the machine check handler by hand. Also don't reflect
2643 		 * the machine check back into the guest.
2644 		 */
2645 		if (intr_vec == IDT_MC) {
2646 			VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2647 			__asm __volatile("int $18");
2648 			return (1);
2649 		}
2650 
2651 		/*
2652 		 * If the hypervisor has requested user exits for
2653 		 * debug exceptions, bounce them out to userland.
2654 		 */
2655 		if (intr_type == VMCS_INTR_T_SWEXCEPTION && intr_vec == IDT_BP &&
2656 		    (vmx->cap[vcpu].set & (1 << VM_CAP_BPT_EXIT))) {
2657 			vmexit->exitcode = VM_EXITCODE_BPT;
2658 			vmexit->u.bpt.inst_length = vmexit->inst_length;
2659 			vmexit->inst_length = 0;
2660 			break;
2661 		}
2662 
2663 		if (intr_vec == IDT_PF) {
2664 			error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2665 			KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2666 			    __func__, error));
2667 		}
2668 
2669 		/*
2670 		 * Software exceptions exhibit trap-like behavior. This in
2671 		 * turn requires populating the VM-entry instruction length
2672 		 * so that the %rip in the trap frame is past the INT3/INTO
2673 		 * instruction.
2674 		 */
2675 		if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2676 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2677 
2678 		/* Reflect all other exceptions back into the guest */
2679 		errcode_valid = errcode = 0;
2680 		if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2681 			errcode_valid = 1;
2682 			errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2683 		}
2684 		VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2685 		    "the guest", intr_vec, errcode);
2686 		SDT_PROBE5(vmm, vmx, exit, exception,
2687 		    vmx, vcpu, vmexit, intr_vec, errcode);
2688 		error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2689 		    errcode_valid, errcode, 0);
2690 		KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2691 		    __func__, error));
2692 		return (1);
2693 
2694 	case EXIT_REASON_EPT_FAULT:
2695 		/*
2696 		 * If 'gpa' lies within the address space allocated to
2697 		 * memory then this must be a nested page fault otherwise
2698 		 * this must be an instruction that accesses MMIO space.
2699 		 */
2700 		gpa = vmcs_gpa();
2701 		if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2702 		    apic_access_fault(vmx, vcpu, gpa)) {
2703 			vmexit->exitcode = VM_EXITCODE_PAGING;
2704 			vmexit->inst_length = 0;
2705 			vmexit->u.paging.gpa = gpa;
2706 			vmexit->u.paging.fault_type = ept_fault_type(qual);
2707 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2708 			SDT_PROBE5(vmm, vmx, exit, nestedfault,
2709 			    vmx, vcpu, vmexit, gpa, qual);
2710 		} else if (ept_emulation_fault(qual)) {
2711 			vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2712 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2713 			SDT_PROBE4(vmm, vmx, exit, mmiofault,
2714 			    vmx, vcpu, vmexit, gpa);
2715 		}
2716 		/*
2717 		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2718 		 * EPT fault during the execution of IRET then we must restore
2719 		 * the state of "virtual-NMI blocking" before resuming.
2720 		 *
2721 		 * See description of "NMI unblocking due to IRET" in
2722 		 * "Exit Qualification for EPT Violations".
2723 		 */
2724 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2725 		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2726 			vmx_restore_nmi_blocking(vmx, vcpu);
2727 		break;
2728 	case EXIT_REASON_VIRTUALIZED_EOI:
2729 		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2730 		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2731 		SDT_PROBE3(vmm, vmx, exit, eoi, vmx, vcpu, vmexit);
2732 		vmexit->inst_length = 0;	/* trap-like */
2733 		break;
2734 	case EXIT_REASON_APIC_ACCESS:
2735 		SDT_PROBE3(vmm, vmx, exit, apicaccess, vmx, vcpu, vmexit);
2736 		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2737 		break;
2738 	case EXIT_REASON_APIC_WRITE:
2739 		/*
2740 		 * APIC-write VM exit is trap-like so the %rip is already
2741 		 * pointing to the next instruction.
2742 		 */
2743 		vmexit->inst_length = 0;
2744 		vlapic = vm_lapic(vmx->vm, vcpu);
2745 		SDT_PROBE4(vmm, vmx, exit, apicwrite,
2746 		    vmx, vcpu, vmexit, vlapic);
2747 		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2748 		break;
2749 	case EXIT_REASON_XSETBV:
2750 		SDT_PROBE3(vmm, vmx, exit, xsetbv, vmx, vcpu, vmexit);
2751 		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2752 		break;
2753 	case EXIT_REASON_MONITOR:
2754 		SDT_PROBE3(vmm, vmx, exit, monitor, vmx, vcpu, vmexit);
2755 		vmexit->exitcode = VM_EXITCODE_MONITOR;
2756 		break;
2757 	case EXIT_REASON_MWAIT:
2758 		SDT_PROBE3(vmm, vmx, exit, mwait, vmx, vcpu, vmexit);
2759 		vmexit->exitcode = VM_EXITCODE_MWAIT;
2760 		break;
2761 	case EXIT_REASON_TPR:
2762 		vlapic = vm_lapic(vmx->vm, vcpu);
2763 		vlapic_sync_tpr(vlapic);
2764 		vmexit->inst_length = 0;
2765 		handled = HANDLED;
2766 		break;
2767 	case EXIT_REASON_VMCALL:
2768 	case EXIT_REASON_VMCLEAR:
2769 	case EXIT_REASON_VMLAUNCH:
2770 	case EXIT_REASON_VMPTRLD:
2771 	case EXIT_REASON_VMPTRST:
2772 	case EXIT_REASON_VMREAD:
2773 	case EXIT_REASON_VMRESUME:
2774 	case EXIT_REASON_VMWRITE:
2775 	case EXIT_REASON_VMXOFF:
2776 	case EXIT_REASON_VMXON:
2777 		SDT_PROBE3(vmm, vmx, exit, vminsn, vmx, vcpu, vmexit);
2778 		vmexit->exitcode = VM_EXITCODE_VMINSN;
2779 		break;
2780 	default:
2781 		SDT_PROBE4(vmm, vmx, exit, unknown,
2782 		    vmx, vcpu, vmexit, reason);
2783 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2784 		break;
2785 	}
2786 
2787 	if (handled) {
2788 		/*
2789 		 * It is possible that control is returned to userland
2790 		 * even though we were able to handle the VM exit in the
2791 		 * kernel.
2792 		 *
2793 		 * In such a case we want to make sure that the userland
2794 		 * restarts guest execution at the instruction *after*
2795 		 * the one we just processed. Therefore we update the
2796 		 * guest rip in the VMCS and in 'vmexit'.
2797 		 */
2798 		vmexit->rip += vmexit->inst_length;
2799 		vmexit->inst_length = 0;
2800 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2801 	} else {
2802 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2803 			/*
2804 			 * If this VM exit was not claimed by anybody then
2805 			 * treat it as a generic VMX exit.
2806 			 */
2807 			vmexit->exitcode = VM_EXITCODE_VMX;
2808 			vmexit->u.vmx.status = VM_SUCCESS;
2809 			vmexit->u.vmx.inst_type = 0;
2810 			vmexit->u.vmx.inst_error = 0;
2811 		} else {
2812 			/*
2813 			 * The exitcode and collateral have been populated.
2814 			 * The VM exit will be processed further in userland.
2815 			 */
2816 		}
2817 	}
2818 
2819 	SDT_PROBE4(vmm, vmx, exit, return,
2820 	    vmx, vcpu, vmexit, handled);
2821 	return (handled);
2822 }
2823 
2824 static __inline void
2825 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2826 {
2827 
2828 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2829 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2830 	    vmxctx->inst_fail_status));
2831 
2832 	vmexit->inst_length = 0;
2833 	vmexit->exitcode = VM_EXITCODE_VMX;
2834 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2835 	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2836 	vmexit->u.vmx.exit_reason = ~0;
2837 	vmexit->u.vmx.exit_qualification = ~0;
2838 
2839 	switch (rc) {
2840 	case VMX_VMRESUME_ERROR:
2841 	case VMX_VMLAUNCH_ERROR:
2842 	case VMX_INVEPT_ERROR:
2843 		vmexit->u.vmx.inst_type = rc;
2844 		break;
2845 	default:
2846 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2847 	}
2848 }
2849 
2850 /*
2851  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2852  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2853  * sufficient to simply vector to the NMI handler via a software interrupt.
2854  * However, this must be done before maskable interrupts are enabled
2855  * otherwise the "iret" issued by an interrupt handler will incorrectly
2856  * clear NMI blocking.
2857  */
2858 static __inline void
2859 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2860 {
2861 	uint32_t intr_info;
2862 
2863 	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2864 
2865 	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2866 		return;
2867 
2868 	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2869 	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2870 	    ("VM exit interruption info invalid: %#x", intr_info));
2871 
2872 	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2873 		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2874 		    "to NMI has invalid vector: %#x", intr_info));
2875 		VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2876 		__asm __volatile("int $2");
2877 	}
2878 }
2879 
2880 static __inline void
2881 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2882 {
2883 	register_t rflags;
2884 
2885 	/* Save host control debug registers. */
2886 	vmxctx->host_dr7 = rdr7();
2887 	vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2888 
2889 	/*
2890 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2891 	 * exceptions in the host based on the guest DRx values.  The
2892 	 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2893 	 */
2894 	load_dr7(0);
2895 	wrmsr(MSR_DEBUGCTLMSR, 0);
2896 
2897 	/*
2898 	 * Disable single stepping the kernel to avoid corrupting the
2899 	 * guest DR6.  A debugger might still be able to corrupt the
2900 	 * guest DR6 by setting a breakpoint after this point and then
2901 	 * single stepping.
2902 	 */
2903 	rflags = read_rflags();
2904 	vmxctx->host_tf = rflags & PSL_T;
2905 	write_rflags(rflags & ~PSL_T);
2906 
2907 	/* Save host debug registers. */
2908 	vmxctx->host_dr0 = rdr0();
2909 	vmxctx->host_dr1 = rdr1();
2910 	vmxctx->host_dr2 = rdr2();
2911 	vmxctx->host_dr3 = rdr3();
2912 	vmxctx->host_dr6 = rdr6();
2913 
2914 	/* Restore guest debug registers. */
2915 	load_dr0(vmxctx->guest_dr0);
2916 	load_dr1(vmxctx->guest_dr1);
2917 	load_dr2(vmxctx->guest_dr2);
2918 	load_dr3(vmxctx->guest_dr3);
2919 	load_dr6(vmxctx->guest_dr6);
2920 }
2921 
2922 static __inline void
2923 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2924 {
2925 
2926 	/* Save guest debug registers. */
2927 	vmxctx->guest_dr0 = rdr0();
2928 	vmxctx->guest_dr1 = rdr1();
2929 	vmxctx->guest_dr2 = rdr2();
2930 	vmxctx->guest_dr3 = rdr3();
2931 	vmxctx->guest_dr6 = rdr6();
2932 
2933 	/*
2934 	 * Restore host debug registers.  Restore DR7, DEBUGCTL, and
2935 	 * PSL_T last.
2936 	 */
2937 	load_dr0(vmxctx->host_dr0);
2938 	load_dr1(vmxctx->host_dr1);
2939 	load_dr2(vmxctx->host_dr2);
2940 	load_dr3(vmxctx->host_dr3);
2941 	load_dr6(vmxctx->host_dr6);
2942 	wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2943 	load_dr7(vmxctx->host_dr7);
2944 	write_rflags(read_rflags() | vmxctx->host_tf);
2945 }
2946 
2947 static int
2948 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2949     struct vm_eventinfo *evinfo)
2950 {
2951 	int rc, handled, launched;
2952 	struct vmx *vmx;
2953 	struct vm *vm;
2954 	struct vmxctx *vmxctx;
2955 	struct vmcs *vmcs;
2956 	struct vm_exit *vmexit;
2957 	struct vlapic *vlapic;
2958 	uint32_t exit_reason;
2959 	struct region_descriptor gdtr, idtr;
2960 	uint16_t ldt_sel;
2961 
2962 	vmx = arg;
2963 	vm = vmx->vm;
2964 	vmcs = &vmx->vmcs[vcpu];
2965 	vmxctx = &vmx->ctx[vcpu];
2966 	vlapic = vm_lapic(vm, vcpu);
2967 	vmexit = vm_exitinfo(vm, vcpu);
2968 	launched = 0;
2969 
2970 	KASSERT(vmxctx->pmap == pmap,
2971 	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2972 
2973 	vmx_msr_guest_enter(vmx, vcpu);
2974 
2975 	VMPTRLD(vmcs);
2976 
2977 	/*
2978 	 * XXX
2979 	 * We do this every time because we may setup the virtual machine
2980 	 * from a different process than the one that actually runs it.
2981 	 *
2982 	 * If the life of a virtual machine was spent entirely in the context
2983 	 * of a single process we could do this once in vmx_vminit().
2984 	 */
2985 	vmcs_write(VMCS_HOST_CR3, rcr3());
2986 
2987 	vmcs_write(VMCS_GUEST_RIP, rip);
2988 	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2989 	do {
2990 		KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2991 		    "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2992 
2993 		handled = UNHANDLED;
2994 		/*
2995 		 * Interrupts are disabled from this point on until the
2996 		 * guest starts executing. This is done for the following
2997 		 * reasons:
2998 		 *
2999 		 * If an AST is asserted on this thread after the check below,
3000 		 * then the IPI_AST notification will not be lost, because it
3001 		 * will cause a VM exit due to external interrupt as soon as
3002 		 * the guest state is loaded.
3003 		 *
3004 		 * A posted interrupt after 'vmx_inject_interrupts()' will
3005 		 * not be "lost" because it will be held pending in the host
3006 		 * APIC because interrupts are disabled. The pending interrupt
3007 		 * will be recognized as soon as the guest state is loaded.
3008 		 *
3009 		 * The same reasoning applies to the IPI generated by
3010 		 * pmap_invalidate_ept().
3011 		 */
3012 		disable_intr();
3013 		vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
3014 
3015 		/*
3016 		 * Check for vcpu suspension after injecting events because
3017 		 * vmx_inject_interrupts() can suspend the vcpu due to a
3018 		 * triple fault.
3019 		 */
3020 		if (vcpu_suspended(evinfo)) {
3021 			enable_intr();
3022 			vm_exit_suspended(vmx->vm, vcpu, rip);
3023 			break;
3024 		}
3025 
3026 		if (vcpu_rendezvous_pending(evinfo)) {
3027 			enable_intr();
3028 			vm_exit_rendezvous(vmx->vm, vcpu, rip);
3029 			break;
3030 		}
3031 
3032 		if (vcpu_reqidle(evinfo)) {
3033 			enable_intr();
3034 			vm_exit_reqidle(vmx->vm, vcpu, rip);
3035 			break;
3036 		}
3037 
3038 		if (vcpu_should_yield(vm, vcpu)) {
3039 			enable_intr();
3040 			vm_exit_astpending(vmx->vm, vcpu, rip);
3041 			vmx_astpending_trace(vmx, vcpu, rip);
3042 			handled = HANDLED;
3043 			break;
3044 		}
3045 
3046 		if (vcpu_debugged(vm, vcpu)) {
3047 			enable_intr();
3048 			vm_exit_debug(vmx->vm, vcpu, rip);
3049 			break;
3050 		}
3051 
3052 		/*
3053 		 * If TPR Shadowing is enabled, the TPR Threshold
3054 		 * must be updated right before entering the guest.
3055 		 */
3056 		if (tpr_shadowing && !virtual_interrupt_delivery) {
3057 			if ((vmx->cap[vcpu].proc_ctls & PROCBASED_USE_TPR_SHADOW) != 0) {
3058 				vmcs_write(VMCS_TPR_THRESHOLD, vlapic_get_cr8(vlapic));
3059 			}
3060 		}
3061 
3062 		/*
3063 		 * VM exits restore the base address but not the
3064 		 * limits of GDTR and IDTR.  The VMCS only stores the
3065 		 * base address, so VM exits set the limits to 0xffff.
3066 		 * Save and restore the full GDTR and IDTR to restore
3067 		 * the limits.
3068 		 *
3069 		 * The VMCS does not save the LDTR at all, and VM
3070 		 * exits clear LDTR as if a NULL selector were loaded.
3071 		 * The userspace hypervisor probably doesn't use a
3072 		 * LDT, but save and restore it to be safe.
3073 		 */
3074 		sgdt(&gdtr);
3075 		sidt(&idtr);
3076 		ldt_sel = sldt();
3077 
3078 		/*
3079 		 * The TSC_AUX MSR must be saved/restored while interrupts
3080 		 * are disabled so that it is not possible for the guest
3081 		 * TSC_AUX MSR value to be overwritten by the resume
3082 		 * portion of the IPI_SUSPEND codepath. This is why the
3083 		 * transition of this MSR is handled separately from those
3084 		 * handled by vmx_msr_guest_{enter,exit}(), which are ok to
3085 		 * be transitioned with preemption disabled but interrupts
3086 		 * enabled.
3087 		 *
3088 		 * These vmx_msr_guest_{enter,exit}_tsc_aux() calls can be
3089 		 * anywhere in this loop so long as they happen with
3090 		 * interrupts disabled. This location is chosen for
3091 		 * simplicity.
3092 		 */
3093 		vmx_msr_guest_enter_tsc_aux(vmx, vcpu);
3094 
3095 		vmx_run_trace(vmx, vcpu);
3096 		vmx_dr_enter_guest(vmxctx);
3097 		rc = vmx_enter_guest(vmxctx, vmx, launched);
3098 		vmx_dr_leave_guest(vmxctx);
3099 
3100 		vmx_msr_guest_exit_tsc_aux(vmx, vcpu);
3101 
3102 		bare_lgdt(&gdtr);
3103 		lidt(&idtr);
3104 		lldt(ldt_sel);
3105 
3106 		/* Collect some information for VM exit processing */
3107 		vmexit->rip = rip = vmcs_guest_rip();
3108 		vmexit->inst_length = vmexit_instruction_length();
3109 		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
3110 		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
3111 
3112 		/* Update 'nextrip' */
3113 		vmx->state[vcpu].nextrip = rip;
3114 
3115 		if (rc == VMX_GUEST_VMEXIT) {
3116 			vmx_exit_handle_nmi(vmx, vcpu, vmexit);
3117 			enable_intr();
3118 			handled = vmx_exit_process(vmx, vcpu, vmexit);
3119 		} else {
3120 			enable_intr();
3121 			vmx_exit_inst_error(vmxctx, rc, vmexit);
3122 		}
3123 		launched = 1;
3124 		vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
3125 		rip = vmexit->rip;
3126 	} while (handled);
3127 
3128 	/*
3129 	 * If a VM exit has been handled then the exitcode must be BOGUS
3130 	 * If a VM exit is not handled then the exitcode must not be BOGUS
3131 	 */
3132 	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
3133 	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
3134 		panic("Mismatch between handled (%d) and exitcode (%d)",
3135 		      handled, vmexit->exitcode);
3136 	}
3137 
3138 	if (!handled)
3139 		vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
3140 
3141 	VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
3142 	    vmexit->exitcode);
3143 
3144 	VMCLEAR(vmcs);
3145 	vmx_msr_guest_exit(vmx, vcpu);
3146 
3147 	return (0);
3148 }
3149 
3150 static void
3151 vmx_vmcleanup(void *arg)
3152 {
3153 	int i;
3154 	struct vmx *vmx = arg;
3155 	uint16_t maxcpus;
3156 
3157 	if (apic_access_virtualization(vmx, 0))
3158 		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3159 
3160 	maxcpus = vm_get_maxcpus(vmx->vm);
3161 	for (i = 0; i < maxcpus; i++)
3162 		vpid_free(vmx->state[i].vpid);
3163 
3164 	free(vmx, M_VMX);
3165 
3166 	return;
3167 }
3168 
3169 static register_t *
3170 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
3171 {
3172 
3173 	switch (reg) {
3174 	case VM_REG_GUEST_RAX:
3175 		return (&vmxctx->guest_rax);
3176 	case VM_REG_GUEST_RBX:
3177 		return (&vmxctx->guest_rbx);
3178 	case VM_REG_GUEST_RCX:
3179 		return (&vmxctx->guest_rcx);
3180 	case VM_REG_GUEST_RDX:
3181 		return (&vmxctx->guest_rdx);
3182 	case VM_REG_GUEST_RSI:
3183 		return (&vmxctx->guest_rsi);
3184 	case VM_REG_GUEST_RDI:
3185 		return (&vmxctx->guest_rdi);
3186 	case VM_REG_GUEST_RBP:
3187 		return (&vmxctx->guest_rbp);
3188 	case VM_REG_GUEST_R8:
3189 		return (&vmxctx->guest_r8);
3190 	case VM_REG_GUEST_R9:
3191 		return (&vmxctx->guest_r9);
3192 	case VM_REG_GUEST_R10:
3193 		return (&vmxctx->guest_r10);
3194 	case VM_REG_GUEST_R11:
3195 		return (&vmxctx->guest_r11);
3196 	case VM_REG_GUEST_R12:
3197 		return (&vmxctx->guest_r12);
3198 	case VM_REG_GUEST_R13:
3199 		return (&vmxctx->guest_r13);
3200 	case VM_REG_GUEST_R14:
3201 		return (&vmxctx->guest_r14);
3202 	case VM_REG_GUEST_R15:
3203 		return (&vmxctx->guest_r15);
3204 	case VM_REG_GUEST_CR2:
3205 		return (&vmxctx->guest_cr2);
3206 	case VM_REG_GUEST_DR0:
3207 		return (&vmxctx->guest_dr0);
3208 	case VM_REG_GUEST_DR1:
3209 		return (&vmxctx->guest_dr1);
3210 	case VM_REG_GUEST_DR2:
3211 		return (&vmxctx->guest_dr2);
3212 	case VM_REG_GUEST_DR3:
3213 		return (&vmxctx->guest_dr3);
3214 	case VM_REG_GUEST_DR6:
3215 		return (&vmxctx->guest_dr6);
3216 	default:
3217 		break;
3218 	}
3219 	return (NULL);
3220 }
3221 
3222 static int
3223 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
3224 {
3225 	register_t *regp;
3226 
3227 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
3228 		*retval = *regp;
3229 		return (0);
3230 	} else
3231 		return (EINVAL);
3232 }
3233 
3234 static int
3235 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
3236 {
3237 	register_t *regp;
3238 
3239 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
3240 		*regp = val;
3241 		return (0);
3242 	} else
3243 		return (EINVAL);
3244 }
3245 
3246 static int
3247 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
3248 {
3249 	uint64_t gi;
3250 	int error;
3251 
3252 	error = vmcs_getreg(&vmx->vmcs[vcpu], running,
3253 	    VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
3254 	*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
3255 	return (error);
3256 }
3257 
3258 static int
3259 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
3260 {
3261 	struct vmcs *vmcs;
3262 	uint64_t gi;
3263 	int error, ident;
3264 
3265 	/*
3266 	 * Forcing the vcpu into an interrupt shadow is not supported.
3267 	 */
3268 	if (val) {
3269 		error = EINVAL;
3270 		goto done;
3271 	}
3272 
3273 	vmcs = &vmx->vmcs[vcpu];
3274 	ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
3275 	error = vmcs_getreg(vmcs, running, ident, &gi);
3276 	if (error == 0) {
3277 		gi &= ~HWINTR_BLOCKING;
3278 		error = vmcs_setreg(vmcs, running, ident, gi);
3279 	}
3280 done:
3281 	VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
3282 	    error ? "failed" : "succeeded");
3283 	return (error);
3284 }
3285 
3286 static int
3287 vmx_shadow_reg(int reg)
3288 {
3289 	int shreg;
3290 
3291 	shreg = -1;
3292 
3293 	switch (reg) {
3294 	case VM_REG_GUEST_CR0:
3295 		shreg = VMCS_CR0_SHADOW;
3296 		break;
3297 	case VM_REG_GUEST_CR4:
3298 		shreg = VMCS_CR4_SHADOW;
3299 		break;
3300 	default:
3301 		break;
3302 	}
3303 
3304 	return (shreg);
3305 }
3306 
3307 static int
3308 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
3309 {
3310 	int running, hostcpu;
3311 	struct vmx *vmx = arg;
3312 
3313 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3314 	if (running && hostcpu != curcpu)
3315 		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
3316 
3317 	if (reg == VM_REG_GUEST_INTR_SHADOW)
3318 		return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
3319 
3320 	if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
3321 		return (0);
3322 
3323 	return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
3324 }
3325 
3326 static int
3327 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
3328 {
3329 	int error, hostcpu, running, shadow;
3330 	uint64_t ctls;
3331 	pmap_t pmap;
3332 	struct vmx *vmx = arg;
3333 
3334 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3335 	if (running && hostcpu != curcpu)
3336 		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
3337 
3338 	if (reg == VM_REG_GUEST_INTR_SHADOW)
3339 		return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
3340 
3341 	if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
3342 		return (0);
3343 
3344 	/* Do not permit user write access to VMCS fields by offset. */
3345 	if (reg < 0)
3346 		return (EINVAL);
3347 
3348 	error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
3349 
3350 	if (error == 0) {
3351 		/*
3352 		 * If the "load EFER" VM-entry control is 1 then the
3353 		 * value of EFER.LMA must be identical to "IA-32e mode guest"
3354 		 * bit in the VM-entry control.
3355 		 */
3356 		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
3357 		    (reg == VM_REG_GUEST_EFER)) {
3358 			vmcs_getreg(&vmx->vmcs[vcpu], running,
3359 				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
3360 			if (val & EFER_LMA)
3361 				ctls |= VM_ENTRY_GUEST_LMA;
3362 			else
3363 				ctls &= ~VM_ENTRY_GUEST_LMA;
3364 			vmcs_setreg(&vmx->vmcs[vcpu], running,
3365 				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
3366 		}
3367 
3368 		shadow = vmx_shadow_reg(reg);
3369 		if (shadow > 0) {
3370 			/*
3371 			 * Store the unmodified value in the shadow
3372 			 */
3373 			error = vmcs_setreg(&vmx->vmcs[vcpu], running,
3374 				    VMCS_IDENT(shadow), val);
3375 		}
3376 
3377 		if (reg == VM_REG_GUEST_CR3) {
3378 			/*
3379 			 * Invalidate the guest vcpu's TLB mappings to emulate
3380 			 * the behavior of updating %cr3.
3381 			 *
3382 			 * XXX the processor retains global mappings when %cr3
3383 			 * is updated but vmx_invvpid() does not.
3384 			 */
3385 			pmap = vmx->ctx[vcpu].pmap;
3386 			vmx_invvpid(vmx, vcpu, pmap, running);
3387 		}
3388 	}
3389 
3390 	return (error);
3391 }
3392 
3393 static int
3394 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3395 {
3396 	int hostcpu, running;
3397 	struct vmx *vmx = arg;
3398 
3399 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3400 	if (running && hostcpu != curcpu)
3401 		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3402 
3403 	return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
3404 }
3405 
3406 static int
3407 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
3408 {
3409 	int hostcpu, running;
3410 	struct vmx *vmx = arg;
3411 
3412 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3413 	if (running && hostcpu != curcpu)
3414 		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
3415 
3416 	return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
3417 }
3418 
3419 static int
3420 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3421 {
3422 	struct vmx *vmx = arg;
3423 	int vcap;
3424 	int ret;
3425 
3426 	ret = ENOENT;
3427 
3428 	vcap = vmx->cap[vcpu].set;
3429 
3430 	switch (type) {
3431 	case VM_CAP_HALT_EXIT:
3432 		if (cap_halt_exit)
3433 			ret = 0;
3434 		break;
3435 	case VM_CAP_PAUSE_EXIT:
3436 		if (cap_pause_exit)
3437 			ret = 0;
3438 		break;
3439 	case VM_CAP_MTRAP_EXIT:
3440 		if (cap_monitor_trap)
3441 			ret = 0;
3442 		break;
3443 	case VM_CAP_RDPID:
3444 		if (cap_rdpid)
3445 			ret = 0;
3446 		break;
3447 	case VM_CAP_RDTSCP:
3448 		if (cap_rdtscp)
3449 			ret = 0;
3450 		break;
3451 	case VM_CAP_UNRESTRICTED_GUEST:
3452 		if (cap_unrestricted_guest)
3453 			ret = 0;
3454 		break;
3455 	case VM_CAP_ENABLE_INVPCID:
3456 		if (cap_invpcid)
3457 			ret = 0;
3458 		break;
3459 	case VM_CAP_BPT_EXIT:
3460 		ret = 0;
3461 		break;
3462 	default:
3463 		break;
3464 	}
3465 
3466 	if (ret == 0)
3467 		*retval = (vcap & (1 << type)) ? 1 : 0;
3468 
3469 	return (ret);
3470 }
3471 
3472 static int
3473 vmx_setcap(void *arg, int vcpu, int type, int val)
3474 {
3475 	struct vmx *vmx = arg;
3476 	struct vmcs *vmcs = &vmx->vmcs[vcpu];
3477 	uint32_t baseval;
3478 	uint32_t *pptr;
3479 	int error;
3480 	int flag;
3481 	int reg;
3482 	int retval;
3483 
3484 	retval = ENOENT;
3485 	pptr = NULL;
3486 
3487 	switch (type) {
3488 	case VM_CAP_HALT_EXIT:
3489 		if (cap_halt_exit) {
3490 			retval = 0;
3491 			pptr = &vmx->cap[vcpu].proc_ctls;
3492 			baseval = *pptr;
3493 			flag = PROCBASED_HLT_EXITING;
3494 			reg = VMCS_PRI_PROC_BASED_CTLS;
3495 		}
3496 		break;
3497 	case VM_CAP_MTRAP_EXIT:
3498 		if (cap_monitor_trap) {
3499 			retval = 0;
3500 			pptr = &vmx->cap[vcpu].proc_ctls;
3501 			baseval = *pptr;
3502 			flag = PROCBASED_MTF;
3503 			reg = VMCS_PRI_PROC_BASED_CTLS;
3504 		}
3505 		break;
3506 	case VM_CAP_PAUSE_EXIT:
3507 		if (cap_pause_exit) {
3508 			retval = 0;
3509 			pptr = &vmx->cap[vcpu].proc_ctls;
3510 			baseval = *pptr;
3511 			flag = PROCBASED_PAUSE_EXITING;
3512 			reg = VMCS_PRI_PROC_BASED_CTLS;
3513 		}
3514 		break;
3515 	case VM_CAP_RDPID:
3516 	case VM_CAP_RDTSCP:
3517 		if (cap_rdpid || cap_rdtscp)
3518 			/*
3519 			 * Choose not to support enabling/disabling
3520 			 * RDPID/RDTSCP via libvmmapi since, as per the
3521 			 * discussion in vmx_init(), RDPID/RDTSCP are
3522 			 * either always enabled or always disabled.
3523 			 */
3524 			error = EOPNOTSUPP;
3525 		break;
3526 	case VM_CAP_UNRESTRICTED_GUEST:
3527 		if (cap_unrestricted_guest) {
3528 			retval = 0;
3529 			pptr = &vmx->cap[vcpu].proc_ctls2;
3530 			baseval = *pptr;
3531 			flag = PROCBASED2_UNRESTRICTED_GUEST;
3532 			reg = VMCS_SEC_PROC_BASED_CTLS;
3533 		}
3534 		break;
3535 	case VM_CAP_ENABLE_INVPCID:
3536 		if (cap_invpcid) {
3537 			retval = 0;
3538 			pptr = &vmx->cap[vcpu].proc_ctls2;
3539 			baseval = *pptr;
3540 			flag = PROCBASED2_ENABLE_INVPCID;
3541 			reg = VMCS_SEC_PROC_BASED_CTLS;
3542 		}
3543 		break;
3544 	case VM_CAP_BPT_EXIT:
3545 		retval = 0;
3546 
3547 		/* Don't change the bitmap if we are tracing all exceptions. */
3548 		if (vmx->cap[vcpu].exc_bitmap != 0xffffffff) {
3549 			pptr = &vmx->cap[vcpu].exc_bitmap;
3550 			baseval = *pptr;
3551 			flag = (1 << IDT_BP);
3552 			reg = VMCS_EXCEPTION_BITMAP;
3553 		}
3554 		break;
3555 	default:
3556 		break;
3557 	}
3558 
3559 	if (retval)
3560 		return (retval);
3561 
3562 	if (pptr != NULL) {
3563 		if (val) {
3564 			baseval |= flag;
3565 		} else {
3566 			baseval &= ~flag;
3567 		}
3568 		VMPTRLD(vmcs);
3569 		error = vmwrite(reg, baseval);
3570 		VMCLEAR(vmcs);
3571 
3572 		if (error)
3573 			return (error);
3574 
3575 		/*
3576 		 * Update optional stored flags, and record
3577 		 * setting
3578 		 */
3579 		*pptr = baseval;
3580 	}
3581 
3582 	if (val) {
3583 		vmx->cap[vcpu].set |= (1 << type);
3584 	} else {
3585 		vmx->cap[vcpu].set &= ~(1 << type);
3586 	}
3587 
3588 	return (0);
3589 }
3590 
3591 struct vlapic_vtx {
3592 	struct vlapic	vlapic;
3593 	struct pir_desc	*pir_desc;
3594 	struct vmx	*vmx;
3595 	u_int	pending_prio;
3596 };
3597 
3598 #define VPR_PRIO_BIT(vpr)	(1 << ((vpr) >> 4))
3599 
3600 #define	VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)	\
3601 do {									\
3602 	VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",	\
3603 	    level ? "level" : "edge", vector);				\
3604 	VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3605 	VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3606 	VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3607 	VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3608 	VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3609 } while (0)
3610 
3611 /*
3612  * vlapic->ops handlers that utilize the APICv hardware assist described in
3613  * Chapter 29 of the Intel SDM.
3614  */
3615 static int
3616 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3617 {
3618 	struct vlapic_vtx *vlapic_vtx;
3619 	struct pir_desc *pir_desc;
3620 	uint64_t mask;
3621 	int idx, notify = 0;
3622 
3623 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3624 	pir_desc = vlapic_vtx->pir_desc;
3625 
3626 	/*
3627 	 * Keep track of interrupt requests in the PIR descriptor. This is
3628 	 * because the virtual APIC page pointed to by the VMCS cannot be
3629 	 * modified if the vcpu is running.
3630 	 */
3631 	idx = vector / 64;
3632 	mask = 1UL << (vector % 64);
3633 	atomic_set_long(&pir_desc->pir[idx], mask);
3634 
3635 	/*
3636 	 * A notification is required whenever the 'pending' bit makes a
3637 	 * transition from 0->1.
3638 	 *
3639 	 * Even if the 'pending' bit is already asserted, notification about
3640 	 * the incoming interrupt may still be necessary.  For example, if a
3641 	 * vCPU is HLTed with a high PPR, a low priority interrupt would cause
3642 	 * the 0->1 'pending' transition with a notification, but the vCPU
3643 	 * would ignore the interrupt for the time being.  The same vCPU would
3644 	 * need to then be notified if a high-priority interrupt arrived which
3645 	 * satisfied the PPR.
3646 	 *
3647 	 * The priorities of interrupts injected while 'pending' is asserted
3648 	 * are tracked in a custom bitfield 'pending_prio'.  Should the
3649 	 * to-be-injected interrupt exceed the priorities already present, the
3650 	 * notification is sent.  The priorities recorded in 'pending_prio' are
3651 	 * cleared whenever the 'pending' bit makes another 0->1 transition.
3652 	 */
3653 	if (atomic_cmpset_long(&pir_desc->pending, 0, 1) != 0) {
3654 		notify = 1;
3655 		vlapic_vtx->pending_prio = 0;
3656 	} else {
3657 		const u_int old_prio = vlapic_vtx->pending_prio;
3658 		const u_int prio_bit = VPR_PRIO_BIT(vector & APIC_TPR_INT);
3659 
3660 		if ((old_prio & prio_bit) == 0 && prio_bit > old_prio) {
3661 			atomic_set_int(&vlapic_vtx->pending_prio, prio_bit);
3662 			notify = 1;
3663 		}
3664 	}
3665 
3666 	VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3667 	    level, "vmx_set_intr_ready");
3668 	return (notify);
3669 }
3670 
3671 static int
3672 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3673 {
3674 	struct vlapic_vtx *vlapic_vtx;
3675 	struct pir_desc *pir_desc;
3676 	struct LAPIC *lapic;
3677 	uint64_t pending, pirval;
3678 	uint32_t ppr, vpr;
3679 	int i;
3680 
3681 	/*
3682 	 * This function is only expected to be called from the 'HLT' exit
3683 	 * handler which does not care about the vector that is pending.
3684 	 */
3685 	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3686 
3687 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3688 	pir_desc = vlapic_vtx->pir_desc;
3689 
3690 	pending = atomic_load_acq_long(&pir_desc->pending);
3691 	if (!pending) {
3692 		/*
3693 		 * While a virtual interrupt may have already been
3694 		 * processed the actual delivery maybe pending the
3695 		 * interruptibility of the guest.  Recognize a pending
3696 		 * interrupt by reevaluating virtual interrupts
3697 		 * following Section 29.2.1 in the Intel SDM Volume 3.
3698 		 */
3699 		struct vm_exit *vmexit;
3700 		uint8_t rvi, ppr;
3701 
3702 		vmexit = vm_exitinfo(vlapic->vm, vlapic->vcpuid);
3703 		KASSERT(vmexit->exitcode == VM_EXITCODE_HLT,
3704 		    ("vmx_pending_intr: exitcode not 'HLT'"));
3705 		rvi = vmexit->u.hlt.intr_status & APIC_TPR_INT;
3706 		lapic = vlapic->apic_page;
3707 		ppr = lapic->ppr & APIC_TPR_INT;
3708 		if (rvi > ppr) {
3709 			return (1);
3710 		}
3711 
3712 		return (0);
3713 	}
3714 
3715 	/*
3716 	 * If there is an interrupt pending then it will be recognized only
3717 	 * if its priority is greater than the processor priority.
3718 	 *
3719 	 * Special case: if the processor priority is zero then any pending
3720 	 * interrupt will be recognized.
3721 	 */
3722 	lapic = vlapic->apic_page;
3723 	ppr = lapic->ppr & APIC_TPR_INT;
3724 	if (ppr == 0)
3725 		return (1);
3726 
3727 	VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3728 	    lapic->ppr);
3729 
3730 	vpr = 0;
3731 	for (i = 3; i >= 0; i--) {
3732 		pirval = pir_desc->pir[i];
3733 		if (pirval != 0) {
3734 			vpr = (i * 64 + flsl(pirval) - 1) & APIC_TPR_INT;
3735 			break;
3736 		}
3737 	}
3738 
3739 	/*
3740 	 * If the highest-priority pending interrupt falls short of the
3741 	 * processor priority of this vCPU, ensure that 'pending_prio' does not
3742 	 * have any stale bits which would preclude a higher-priority interrupt
3743 	 * from incurring a notification later.
3744 	 */
3745 	if (vpr <= ppr) {
3746 		const u_int prio_bit = VPR_PRIO_BIT(vpr);
3747 		const u_int old = vlapic_vtx->pending_prio;
3748 
3749 		if (old > prio_bit && (old & prio_bit) == 0) {
3750 			vlapic_vtx->pending_prio = prio_bit;
3751 		}
3752 		return (0);
3753 	}
3754 	return (1);
3755 }
3756 
3757 static void
3758 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3759 {
3760 
3761 	panic("vmx_intr_accepted: not expected to be called");
3762 }
3763 
3764 static void
3765 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3766 {
3767 	struct vlapic_vtx *vlapic_vtx;
3768 	struct vmx *vmx;
3769 	struct vmcs *vmcs;
3770 	uint64_t mask, val;
3771 
3772 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3773 	KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3774 	    ("vmx_set_tmr: vcpu cannot be running"));
3775 
3776 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3777 	vmx = vlapic_vtx->vmx;
3778 	vmcs = &vmx->vmcs[vlapic->vcpuid];
3779 	mask = 1UL << (vector % 64);
3780 
3781 	VMPTRLD(vmcs);
3782 	val = vmcs_read(VMCS_EOI_EXIT(vector));
3783 	if (level)
3784 		val |= mask;
3785 	else
3786 		val &= ~mask;
3787 	vmcs_write(VMCS_EOI_EXIT(vector), val);
3788 	VMCLEAR(vmcs);
3789 }
3790 
3791 static void
3792 vmx_enable_x2apic_mode_ts(struct vlapic *vlapic)
3793 {
3794 	struct vmx *vmx;
3795 	struct vmcs *vmcs;
3796 	uint32_t proc_ctls;
3797 	int vcpuid;
3798 
3799 	vcpuid = vlapic->vcpuid;
3800 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3801 	vmcs = &vmx->vmcs[vcpuid];
3802 
3803 	proc_ctls = vmx->cap[vcpuid].proc_ctls;
3804 	proc_ctls &= ~PROCBASED_USE_TPR_SHADOW;
3805 	proc_ctls |= PROCBASED_CR8_LOAD_EXITING;
3806 	proc_ctls |= PROCBASED_CR8_STORE_EXITING;
3807 	vmx->cap[vcpuid].proc_ctls = proc_ctls;
3808 
3809 	VMPTRLD(vmcs);
3810 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
3811 	VMCLEAR(vmcs);
3812 }
3813 
3814 static void
3815 vmx_enable_x2apic_mode_vid(struct vlapic *vlapic)
3816 {
3817 	struct vmx *vmx;
3818 	struct vmcs *vmcs;
3819 	uint32_t proc_ctls2;
3820 	int vcpuid, error;
3821 
3822 	vcpuid = vlapic->vcpuid;
3823 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3824 	vmcs = &vmx->vmcs[vcpuid];
3825 
3826 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3827 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3828 	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3829 
3830 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3831 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3832 	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3833 
3834 	VMPTRLD(vmcs);
3835 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3836 	VMCLEAR(vmcs);
3837 
3838 	if (vlapic->vcpuid == 0) {
3839 		/*
3840 		 * The nested page table mappings are shared by all vcpus
3841 		 * so unmap the APIC access page just once.
3842 		 */
3843 		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3844 		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3845 		    __func__, error));
3846 
3847 		/*
3848 		 * The MSR bitmap is shared by all vcpus so modify it only
3849 		 * once in the context of vcpu 0.
3850 		 */
3851 		error = vmx_allow_x2apic_msrs(vmx);
3852 		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3853 		    __func__, error));
3854 	}
3855 }
3856 
3857 static void
3858 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3859 {
3860 
3861 	ipi_cpu(hostcpu, pirvec);
3862 }
3863 
3864 /*
3865  * Transfer the pending interrupts in the PIR descriptor to the IRR
3866  * in the virtual APIC page.
3867  */
3868 static void
3869 vmx_inject_pir(struct vlapic *vlapic)
3870 {
3871 	struct vlapic_vtx *vlapic_vtx;
3872 	struct pir_desc *pir_desc;
3873 	struct LAPIC *lapic;
3874 	uint64_t val, pirval;
3875 	int rvi, pirbase = -1;
3876 	uint16_t intr_status_old, intr_status_new;
3877 
3878 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3879 	pir_desc = vlapic_vtx->pir_desc;
3880 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3881 		VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3882 		    "no posted interrupt pending");
3883 		return;
3884 	}
3885 
3886 	pirval = 0;
3887 	pirbase = -1;
3888 	lapic = vlapic->apic_page;
3889 
3890 	val = atomic_readandclear_long(&pir_desc->pir[0]);
3891 	if (val != 0) {
3892 		lapic->irr0 |= val;
3893 		lapic->irr1 |= val >> 32;
3894 		pirbase = 0;
3895 		pirval = val;
3896 	}
3897 
3898 	val = atomic_readandclear_long(&pir_desc->pir[1]);
3899 	if (val != 0) {
3900 		lapic->irr2 |= val;
3901 		lapic->irr3 |= val >> 32;
3902 		pirbase = 64;
3903 		pirval = val;
3904 	}
3905 
3906 	val = atomic_readandclear_long(&pir_desc->pir[2]);
3907 	if (val != 0) {
3908 		lapic->irr4 |= val;
3909 		lapic->irr5 |= val >> 32;
3910 		pirbase = 128;
3911 		pirval = val;
3912 	}
3913 
3914 	val = atomic_readandclear_long(&pir_desc->pir[3]);
3915 	if (val != 0) {
3916 		lapic->irr6 |= val;
3917 		lapic->irr7 |= val >> 32;
3918 		pirbase = 192;
3919 		pirval = val;
3920 	}
3921 
3922 	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3923 
3924 	/*
3925 	 * Update RVI so the processor can evaluate pending virtual
3926 	 * interrupts on VM-entry.
3927 	 *
3928 	 * It is possible for pirval to be 0 here, even though the
3929 	 * pending bit has been set. The scenario is:
3930 	 * CPU-Y is sending a posted interrupt to CPU-X, which
3931 	 * is running a guest and processing posted interrupts in h/w.
3932 	 * CPU-X will eventually exit and the state seen in s/w is
3933 	 * the pending bit set, but no PIR bits set.
3934 	 *
3935 	 *      CPU-X                      CPU-Y
3936 	 *   (vm running)                (host running)
3937 	 *   rx posted interrupt
3938 	 *   CLEAR pending bit
3939 	 *				 SET PIR bit
3940 	 *   READ/CLEAR PIR bits
3941 	 *				 SET pending bit
3942 	 *   (vm exit)
3943 	 *   pending bit set, PIR 0
3944 	 */
3945 	if (pirval != 0) {
3946 		rvi = pirbase + flsl(pirval) - 1;
3947 		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3948 		intr_status_new = (intr_status_old & 0xFF00) | rvi;
3949 		if (intr_status_new > intr_status_old) {
3950 			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3951 			VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3952 			    "guest_intr_status changed from 0x%04x to 0x%04x",
3953 			    intr_status_old, intr_status_new);
3954 		}
3955 	}
3956 }
3957 
3958 static struct vlapic *
3959 vmx_vlapic_init(void *arg, int vcpuid)
3960 {
3961 	struct vmx *vmx;
3962 	struct vlapic *vlapic;
3963 	struct vlapic_vtx *vlapic_vtx;
3964 
3965 	vmx = arg;
3966 
3967 	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3968 	vlapic->vm = vmx->vm;
3969 	vlapic->vcpuid = vcpuid;
3970 	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3971 
3972 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3973 	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3974 	vlapic_vtx->vmx = vmx;
3975 
3976 	if (tpr_shadowing) {
3977 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_ts;
3978 	}
3979 
3980 	if (virtual_interrupt_delivery) {
3981 		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3982 		vlapic->ops.pending_intr = vmx_pending_intr;
3983 		vlapic->ops.intr_accepted = vmx_intr_accepted;
3984 		vlapic->ops.set_tmr = vmx_set_tmr;
3985 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode_vid;
3986 	}
3987 
3988 	if (posted_interrupts)
3989 		vlapic->ops.post_intr = vmx_post_intr;
3990 
3991 	vlapic_init(vlapic);
3992 
3993 	return (vlapic);
3994 }
3995 
3996 static void
3997 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3998 {
3999 
4000 	vlapic_cleanup(vlapic);
4001 	free(vlapic, M_VLAPIC);
4002 }
4003 
4004 #ifdef BHYVE_SNAPSHOT
4005 static int
4006 vmx_snapshot_vmi(void *arg, struct vm_snapshot_meta *meta)
4007 {
4008 	struct vmx *vmx;
4009 	struct vmxctx *vmxctx;
4010 	int i;
4011 	int ret;
4012 
4013 	vmx = arg;
4014 
4015 	KASSERT(vmx != NULL, ("%s: arg was NULL", __func__));
4016 
4017 	for (i = 0; i < VM_MAXCPU; i++) {
4018 		SNAPSHOT_BUF_OR_LEAVE(vmx->guest_msrs[i],
4019 		      sizeof(vmx->guest_msrs[i]), meta, ret, done);
4020 
4021 		vmxctx = &vmx->ctx[i];
4022 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdi, meta, ret, done);
4023 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rsi, meta, ret, done);
4024 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rdx, meta, ret, done);
4025 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rcx, meta, ret, done);
4026 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r8, meta, ret, done);
4027 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r9, meta, ret, done);
4028 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rax, meta, ret, done);
4029 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbx, meta, ret, done);
4030 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_rbp, meta, ret, done);
4031 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r10, meta, ret, done);
4032 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r11, meta, ret, done);
4033 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r12, meta, ret, done);
4034 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r13, meta, ret, done);
4035 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r14, meta, ret, done);
4036 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_r15, meta, ret, done);
4037 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_cr2, meta, ret, done);
4038 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr0, meta, ret, done);
4039 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr1, meta, ret, done);
4040 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr2, meta, ret, done);
4041 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr3, meta, ret, done);
4042 		SNAPSHOT_VAR_OR_LEAVE(vmxctx->guest_dr6, meta, ret, done);
4043 	}
4044 
4045 done:
4046 	return (ret);
4047 }
4048 
4049 static int
4050 vmx_snapshot_vmcx(void *arg, struct vm_snapshot_meta *meta, int vcpu)
4051 {
4052 	struct vmcs *vmcs;
4053 	struct vmx *vmx;
4054 	int err, run, hostcpu;
4055 
4056 	vmx = (struct vmx *)arg;
4057 	err = 0;
4058 
4059 	KASSERT(arg != NULL, ("%s: arg was NULL", __func__));
4060 	vmcs = &vmx->vmcs[vcpu];
4061 
4062 	run = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
4063 	if (run && hostcpu != curcpu) {
4064 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm), vcpu);
4065 		return (EINVAL);
4066 	}
4067 
4068 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR0, meta);
4069 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR3, meta);
4070 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CR4, meta);
4071 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DR7, meta);
4072 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RSP, meta);
4073 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RIP, meta);
4074 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_RFLAGS, meta);
4075 
4076 	/* Guest segments */
4077 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_ES, meta);
4078 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_ES, meta);
4079 
4080 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_CS, meta);
4081 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_CS, meta);
4082 
4083 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_SS, meta);
4084 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_SS, meta);
4085 
4086 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_DS, meta);
4087 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_DS, meta);
4088 
4089 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_FS, meta);
4090 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_FS, meta);
4091 
4092 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_GS, meta);
4093 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GS, meta);
4094 
4095 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_TR, meta);
4096 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_TR, meta);
4097 
4098 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_LDTR, meta);
4099 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_LDTR, meta);
4100 
4101 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_EFER, meta);
4102 
4103 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_IDTR, meta);
4104 	err += vmcs_snapshot_desc(vmcs, run, VM_REG_GUEST_GDTR, meta);
4105 
4106 	/* Guest page tables */
4107 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE0, meta);
4108 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE1, meta);
4109 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE2, meta);
4110 	err += vmcs_snapshot_reg(vmcs, run, VM_REG_GUEST_PDPTE3, meta);
4111 
4112 	/* Other guest state */
4113 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_CS, meta);
4114 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_ESP, meta);
4115 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_IA32_SYSENTER_EIP, meta);
4116 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_INTERRUPTIBILITY, meta);
4117 	err += vmcs_snapshot_any(vmcs, run, VMCS_GUEST_ACTIVITY, meta);
4118 	err += vmcs_snapshot_any(vmcs, run, VMCS_ENTRY_CTLS, meta);
4119 	err += vmcs_snapshot_any(vmcs, run, VMCS_EXIT_CTLS, meta);
4120 
4121 	return (err);
4122 }
4123 
4124 static int
4125 vmx_restore_tsc(void *arg, int vcpu, uint64_t offset)
4126 {
4127 	struct vmcs *vmcs;
4128 	struct vmx *vmx = (struct vmx *)arg;
4129 	int error, running, hostcpu;
4130 
4131 	KASSERT(arg != NULL, ("%s: arg was NULL", __func__));
4132 	vmcs = &vmx->vmcs[vcpu];
4133 
4134 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
4135 	if (running && hostcpu != curcpu) {
4136 		printf("%s: %s%d is running", __func__, vm_name(vmx->vm), vcpu);
4137 		return (EINVAL);
4138 	}
4139 
4140 	if (!running)
4141 		VMPTRLD(vmcs);
4142 
4143 	error = vmx_set_tsc_offset(vmx, vcpu, offset);
4144 
4145 	if (!running)
4146 		VMCLEAR(vmcs);
4147 	return (error);
4148 }
4149 #endif
4150 
4151 struct vmm_ops vmm_ops_intel = {
4152 	.init		= vmx_init,
4153 	.cleanup	= vmx_cleanup,
4154 	.resume		= vmx_restore,
4155 	.vminit		= vmx_vminit,
4156 	.vmrun		= vmx_run,
4157 	.vmcleanup	= vmx_vmcleanup,
4158 	.vmgetreg	= vmx_getreg,
4159 	.vmsetreg	= vmx_setreg,
4160 	.vmgetdesc	= vmx_getdesc,
4161 	.vmsetdesc	= vmx_setdesc,
4162 	.vmgetcap	= vmx_getcap,
4163 	.vmsetcap	= vmx_setcap,
4164 	.vmspace_alloc	= ept_vmspace_alloc,
4165 	.vmspace_free	= ept_vmspace_free,
4166 	.vlapic_init	= vmx_vlapic_init,
4167 	.vlapic_cleanup	= vmx_vlapic_cleanup,
4168 #ifdef BHYVE_SNAPSHOT
4169 	.vmsnapshot	= vmx_snapshot_vmi,
4170 	.vmcx_snapshot	= vmx_snapshot_vmcx,
4171 	.vm_restore_tsc	= vmx_restore_tsc,
4172 #endif
4173 };
4174