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