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