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