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