vmx.c revision 267330
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: head/sys/amd64/vmm/intel/vmx.c 267330 2014-06-10 16:45:58Z neel $
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/amd64/vmm/intel/vmx.c 267330 2014-06-10 16:45:58Z neel $");
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	} else {
1262		/* Ask the legacy pic for a vector to inject */
1263		vatpic_pending_intr(vmx->vm, &vector);
1264	}
1265
1266	KASSERT(vector >= 32 && vector <= 255, ("invalid vector %d", vector));
1267
1268	/* Check RFLAGS.IF and the interruptibility state of the guest */
1269	rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1270	if ((rflags & PSL_I) == 0) {
1271		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1272		    "rflags %#lx", vector, rflags);
1273		goto cantinject;
1274	}
1275
1276	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1277	if (gi & HWINTR_BLOCKING) {
1278		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1279		    "Guest Interruptibility-state %#x", vector, gi);
1280		goto cantinject;
1281	}
1282
1283	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1284	if (info & VMCS_INTR_VALID) {
1285		/*
1286		 * This is expected and could happen for multiple reasons:
1287		 * - A vectoring VM-entry was aborted due to astpending
1288		 * - A VM-exit happened during event injection.
1289		 * - An exception was injected above.
1290		 * - An NMI was injected above or after "NMI window exiting"
1291		 */
1292		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1293		    "VM-entry intr info %#x", vector, info);
1294		goto cantinject;
1295	}
1296
1297	/* Inject the interrupt */
1298	info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1299	info |= vector;
1300	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1301
1302	if (!extint_pending) {
1303		/* Update the Local APIC ISR */
1304		vlapic_intr_accepted(vlapic, vector);
1305	} else {
1306		vm_extint_clear(vmx->vm, vcpu);
1307		vatpic_intr_accepted(vmx->vm, vector);
1308
1309		/*
1310		 * After we accepted the current ExtINT the PIC may
1311		 * have posted another one.  If that is the case, set
1312		 * the Interrupt Window Exiting execution control so
1313		 * we can inject that one too.
1314		 *
1315		 * Also, interrupt window exiting allows us to inject any
1316		 * pending APIC vector that was preempted by the ExtINT
1317		 * as soon as possible. This applies both for the software
1318		 * emulated vlapic and the hardware assisted virtual APIC.
1319		 */
1320		vmx_set_int_window_exiting(vmx, vcpu);
1321	}
1322
1323	VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1324
1325	return;
1326
1327cantinject:
1328	/*
1329	 * Set the Interrupt Window Exiting execution control so we can inject
1330	 * the interrupt as soon as blocking condition goes away.
1331	 */
1332	vmx_set_int_window_exiting(vmx, vcpu);
1333}
1334
1335/*
1336 * If the Virtual NMIs execution control is '1' then the logical processor
1337 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1338 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1339 * virtual-NMI blocking.
1340 *
1341 * This unblocking occurs even if the IRET causes a fault. In this case the
1342 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1343 */
1344static void
1345vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1346{
1347	uint32_t gi;
1348
1349	VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1350	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1351	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1352	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1353}
1354
1355static void
1356vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1357{
1358	uint32_t gi;
1359
1360	VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1361	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1362	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1363	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1364}
1365
1366static int
1367vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1368{
1369	struct vmxctx *vmxctx;
1370	uint64_t xcrval;
1371	const struct xsave_limits *limits;
1372
1373	vmxctx = &vmx->ctx[vcpu];
1374	limits = vmm_get_xsave_limits();
1375
1376	/*
1377	 * Note that the processor raises a GP# fault on its own if
1378	 * xsetbv is executed for CPL != 0, so we do not have to
1379	 * emulate that fault here.
1380	 */
1381
1382	/* Only xcr0 is supported. */
1383	if (vmxctx->guest_rcx != 0) {
1384		vm_inject_gp(vmx->vm, vcpu);
1385		return (HANDLED);
1386	}
1387
1388	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1389	if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1390		vm_inject_ud(vmx->vm, vcpu);
1391		return (HANDLED);
1392	}
1393
1394	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1395	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1396		vm_inject_gp(vmx->vm, vcpu);
1397		return (HANDLED);
1398	}
1399
1400	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1401		vm_inject_gp(vmx->vm, vcpu);
1402		return (HANDLED);
1403	}
1404
1405	/* AVX (YMM_Hi128) requires SSE. */
1406	if (xcrval & XFEATURE_ENABLED_AVX &&
1407	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1408		vm_inject_gp(vmx->vm, vcpu);
1409		return (HANDLED);
1410	}
1411
1412	/*
1413	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1414	 * ZMM_Hi256, and Hi16_ZMM.
1415	 */
1416	if (xcrval & XFEATURE_AVX512 &&
1417	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1418	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1419		vm_inject_gp(vmx->vm, vcpu);
1420		return (HANDLED);
1421	}
1422
1423	/*
1424	 * Intel MPX requires both bound register state flags to be
1425	 * set.
1426	 */
1427	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1428	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1429		vm_inject_gp(vmx->vm, vcpu);
1430		return (HANDLED);
1431	}
1432
1433	/*
1434	 * This runs "inside" vmrun() with the guest's FPU state, so
1435	 * modifying xcr0 directly modifies the guest's xcr0, not the
1436	 * host's.
1437	 */
1438	load_xcr(0, xcrval);
1439	return (HANDLED);
1440}
1441
1442static uint64_t
1443vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1444{
1445	const struct vmxctx *vmxctx;
1446
1447	vmxctx = &vmx->ctx[vcpu];
1448
1449	switch (ident) {
1450	case 0:
1451		return (vmxctx->guest_rax);
1452	case 1:
1453		return (vmxctx->guest_rcx);
1454	case 2:
1455		return (vmxctx->guest_rdx);
1456	case 3:
1457		return (vmxctx->guest_rbx);
1458	case 4:
1459		return (vmcs_read(VMCS_GUEST_RSP));
1460	case 5:
1461		return (vmxctx->guest_rbp);
1462	case 6:
1463		return (vmxctx->guest_rsi);
1464	case 7:
1465		return (vmxctx->guest_rdi);
1466	case 8:
1467		return (vmxctx->guest_r8);
1468	case 9:
1469		return (vmxctx->guest_r9);
1470	case 10:
1471		return (vmxctx->guest_r10);
1472	case 11:
1473		return (vmxctx->guest_r11);
1474	case 12:
1475		return (vmxctx->guest_r12);
1476	case 13:
1477		return (vmxctx->guest_r13);
1478	case 14:
1479		return (vmxctx->guest_r14);
1480	case 15:
1481		return (vmxctx->guest_r15);
1482	default:
1483		panic("invalid vmx register %d", ident);
1484	}
1485}
1486
1487static void
1488vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1489{
1490	struct vmxctx *vmxctx;
1491
1492	vmxctx = &vmx->ctx[vcpu];
1493
1494	switch (ident) {
1495	case 0:
1496		vmxctx->guest_rax = regval;
1497		break;
1498	case 1:
1499		vmxctx->guest_rcx = regval;
1500		break;
1501	case 2:
1502		vmxctx->guest_rdx = regval;
1503		break;
1504	case 3:
1505		vmxctx->guest_rbx = regval;
1506		break;
1507	case 4:
1508		vmcs_write(VMCS_GUEST_RSP, regval);
1509		break;
1510	case 5:
1511		vmxctx->guest_rbp = regval;
1512		break;
1513	case 6:
1514		vmxctx->guest_rsi = regval;
1515		break;
1516	case 7:
1517		vmxctx->guest_rdi = regval;
1518		break;
1519	case 8:
1520		vmxctx->guest_r8 = regval;
1521		break;
1522	case 9:
1523		vmxctx->guest_r9 = regval;
1524		break;
1525	case 10:
1526		vmxctx->guest_r10 = regval;
1527		break;
1528	case 11:
1529		vmxctx->guest_r11 = regval;
1530		break;
1531	case 12:
1532		vmxctx->guest_r12 = regval;
1533		break;
1534	case 13:
1535		vmxctx->guest_r13 = regval;
1536		break;
1537	case 14:
1538		vmxctx->guest_r14 = regval;
1539		break;
1540	case 15:
1541		vmxctx->guest_r15 = regval;
1542		break;
1543	default:
1544		panic("invalid vmx register %d", ident);
1545	}
1546}
1547
1548static int
1549vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1550{
1551	uint64_t crval, regval;
1552
1553	/* We only handle mov to %cr0 at this time */
1554	if ((exitqual & 0xf0) != 0x00)
1555		return (UNHANDLED);
1556
1557	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1558
1559	vmcs_write(VMCS_CR0_SHADOW, regval);
1560
1561	crval = regval | cr0_ones_mask;
1562	crval &= ~cr0_zeros_mask;
1563	vmcs_write(VMCS_GUEST_CR0, crval);
1564
1565	if (regval & CR0_PG) {
1566		uint64_t efer, entry_ctls;
1567
1568		/*
1569		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1570		 * the "IA-32e mode guest" bit in VM-entry control must be
1571		 * equal.
1572		 */
1573		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1574		if (efer & EFER_LME) {
1575			efer |= EFER_LMA;
1576			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1577			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1578			entry_ctls |= VM_ENTRY_GUEST_LMA;
1579			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1580		}
1581	}
1582
1583	return (HANDLED);
1584}
1585
1586static int
1587vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1588{
1589	uint64_t crval, regval;
1590
1591	/* We only handle mov to %cr4 at this time */
1592	if ((exitqual & 0xf0) != 0x00)
1593		return (UNHANDLED);
1594
1595	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1596
1597	vmcs_write(VMCS_CR4_SHADOW, regval);
1598
1599	crval = regval | cr4_ones_mask;
1600	crval &= ~cr4_zeros_mask;
1601	vmcs_write(VMCS_GUEST_CR4, crval);
1602
1603	return (HANDLED);
1604}
1605
1606static int
1607vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1608{
1609	struct vlapic *vlapic;
1610	uint64_t cr8;
1611	int regnum;
1612
1613	/* We only handle mov %cr8 to/from a register at this time. */
1614	if ((exitqual & 0xe0) != 0x00) {
1615		return (UNHANDLED);
1616	}
1617
1618	vlapic = vm_lapic(vmx->vm, vcpu);
1619	regnum = (exitqual >> 8) & 0xf;
1620	if (exitqual & 0x10) {
1621		cr8 = vlapic_get_cr8(vlapic);
1622		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1623	} else {
1624		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1625		vlapic_set_cr8(vlapic, cr8);
1626	}
1627
1628	return (HANDLED);
1629}
1630
1631/*
1632 * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1633 */
1634static int
1635vmx_cpl(void)
1636{
1637	uint32_t ssar;
1638
1639	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1640	return ((ssar >> 5) & 0x3);
1641}
1642
1643static enum vm_cpu_mode
1644vmx_cpu_mode(void)
1645{
1646
1647	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA)
1648		return (CPU_MODE_64BIT);
1649	else
1650		return (CPU_MODE_COMPATIBILITY);
1651}
1652
1653static enum vm_paging_mode
1654vmx_paging_mode(void)
1655{
1656
1657	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1658		return (PAGING_MODE_FLAT);
1659	if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1660		return (PAGING_MODE_32);
1661	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1662		return (PAGING_MODE_64);
1663	else
1664		return (PAGING_MODE_PAE);
1665}
1666
1667static uint64_t
1668inout_str_index(struct vmx *vmx, int vcpuid, int in)
1669{
1670	uint64_t val;
1671	int error;
1672	enum vm_reg_name reg;
1673
1674	reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1675	error = vmx_getreg(vmx, vcpuid, reg, &val);
1676	KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1677	return (val);
1678}
1679
1680static uint64_t
1681inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1682{
1683	uint64_t val;
1684	int error;
1685
1686	if (rep) {
1687		error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1688		KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1689	} else {
1690		val = 1;
1691	}
1692	return (val);
1693}
1694
1695static int
1696inout_str_addrsize(uint32_t inst_info)
1697{
1698	uint32_t size;
1699
1700	size = (inst_info >> 7) & 0x7;
1701	switch (size) {
1702	case 0:
1703		return (2);	/* 16 bit */
1704	case 1:
1705		return (4);	/* 32 bit */
1706	case 2:
1707		return (8);	/* 64 bit */
1708	default:
1709		panic("%s: invalid size encoding %d", __func__, size);
1710	}
1711}
1712
1713static void
1714inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1715    struct vm_inout_str *vis)
1716{
1717	int error, s;
1718
1719	if (in) {
1720		vis->seg_name = VM_REG_GUEST_ES;
1721	} else {
1722		s = (inst_info >> 15) & 0x7;
1723		vis->seg_name = vm_segment_name(s);
1724	}
1725
1726	error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1727	KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1728
1729	/* XXX modify svm.c to update bit 16 of seg_desc.access (unusable) */
1730}
1731
1732static void
1733vmx_paging_info(struct vm_guest_paging *paging)
1734{
1735	paging->cr3 = vmcs_guest_cr3();
1736	paging->cpl = vmx_cpl();
1737	paging->cpu_mode = vmx_cpu_mode();
1738	paging->paging_mode = vmx_paging_mode();
1739}
1740
1741static void
1742vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1743{
1744	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1745	vmexit->u.inst_emul.gpa = gpa;
1746	vmexit->u.inst_emul.gla = gla;
1747	vmx_paging_info(&vmexit->u.inst_emul.paging);
1748}
1749
1750static int
1751ept_fault_type(uint64_t ept_qual)
1752{
1753	int fault_type;
1754
1755	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1756		fault_type = VM_PROT_WRITE;
1757	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1758		fault_type = VM_PROT_EXECUTE;
1759	else
1760		fault_type= VM_PROT_READ;
1761
1762	return (fault_type);
1763}
1764
1765static boolean_t
1766ept_emulation_fault(uint64_t ept_qual)
1767{
1768	int read, write;
1769
1770	/* EPT fault on an instruction fetch doesn't make sense here */
1771	if (ept_qual & EPT_VIOLATION_INST_FETCH)
1772		return (FALSE);
1773
1774	/* EPT fault must be a read fault or a write fault */
1775	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1776	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1777	if ((read | write) == 0)
1778		return (FALSE);
1779
1780	/*
1781	 * The EPT violation must have been caused by accessing a
1782	 * guest-physical address that is a translation of a guest-linear
1783	 * address.
1784	 */
1785	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1786	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1787		return (FALSE);
1788	}
1789
1790	return (TRUE);
1791}
1792
1793static __inline int
1794apic_access_virtualization(struct vmx *vmx, int vcpuid)
1795{
1796	uint32_t proc_ctls2;
1797
1798	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1799	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1800}
1801
1802static __inline int
1803x2apic_virtualization(struct vmx *vmx, int vcpuid)
1804{
1805	uint32_t proc_ctls2;
1806
1807	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1808	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1809}
1810
1811static int
1812vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1813    uint64_t qual)
1814{
1815	int error, handled, offset;
1816	uint32_t *apic_regs, vector;
1817	bool retu;
1818
1819	handled = HANDLED;
1820	offset = APIC_WRITE_OFFSET(qual);
1821
1822	if (!apic_access_virtualization(vmx, vcpuid)) {
1823		/*
1824		 * In general there should not be any APIC write VM-exits
1825		 * unless APIC-access virtualization is enabled.
1826		 *
1827		 * However self-IPI virtualization can legitimately trigger
1828		 * an APIC-write VM-exit so treat it specially.
1829		 */
1830		if (x2apic_virtualization(vmx, vcpuid) &&
1831		    offset == APIC_OFFSET_SELF_IPI) {
1832			apic_regs = (uint32_t *)(vlapic->apic_page);
1833			vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1834			vlapic_self_ipi_handler(vlapic, vector);
1835			return (HANDLED);
1836		} else
1837			return (UNHANDLED);
1838	}
1839
1840	switch (offset) {
1841	case APIC_OFFSET_ID:
1842		vlapic_id_write_handler(vlapic);
1843		break;
1844	case APIC_OFFSET_LDR:
1845		vlapic_ldr_write_handler(vlapic);
1846		break;
1847	case APIC_OFFSET_DFR:
1848		vlapic_dfr_write_handler(vlapic);
1849		break;
1850	case APIC_OFFSET_SVR:
1851		vlapic_svr_write_handler(vlapic);
1852		break;
1853	case APIC_OFFSET_ESR:
1854		vlapic_esr_write_handler(vlapic);
1855		break;
1856	case APIC_OFFSET_ICR_LOW:
1857		retu = false;
1858		error = vlapic_icrlo_write_handler(vlapic, &retu);
1859		if (error != 0 || retu)
1860			handled = UNHANDLED;
1861		break;
1862	case APIC_OFFSET_CMCI_LVT:
1863	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1864		vlapic_lvt_write_handler(vlapic, offset);
1865		break;
1866	case APIC_OFFSET_TIMER_ICR:
1867		vlapic_icrtmr_write_handler(vlapic);
1868		break;
1869	case APIC_OFFSET_TIMER_DCR:
1870		vlapic_dcr_write_handler(vlapic);
1871		break;
1872	default:
1873		handled = UNHANDLED;
1874		break;
1875	}
1876	return (handled);
1877}
1878
1879static bool
1880apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1881{
1882
1883	if (apic_access_virtualization(vmx, vcpuid) &&
1884	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1885		return (true);
1886	else
1887		return (false);
1888}
1889
1890static int
1891vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1892{
1893	uint64_t qual;
1894	int access_type, offset, allowed;
1895
1896	if (!apic_access_virtualization(vmx, vcpuid))
1897		return (UNHANDLED);
1898
1899	qual = vmexit->u.vmx.exit_qualification;
1900	access_type = APIC_ACCESS_TYPE(qual);
1901	offset = APIC_ACCESS_OFFSET(qual);
1902
1903	allowed = 0;
1904	if (access_type == 0) {
1905		/*
1906		 * Read data access to the following registers is expected.
1907		 */
1908		switch (offset) {
1909		case APIC_OFFSET_APR:
1910		case APIC_OFFSET_PPR:
1911		case APIC_OFFSET_RRR:
1912		case APIC_OFFSET_CMCI_LVT:
1913		case APIC_OFFSET_TIMER_CCR:
1914			allowed = 1;
1915			break;
1916		default:
1917			break;
1918		}
1919	} else if (access_type == 1) {
1920		/*
1921		 * Write data access to the following registers is expected.
1922		 */
1923		switch (offset) {
1924		case APIC_OFFSET_VER:
1925		case APIC_OFFSET_APR:
1926		case APIC_OFFSET_PPR:
1927		case APIC_OFFSET_RRR:
1928		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1929		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1930		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1931		case APIC_OFFSET_CMCI_LVT:
1932		case APIC_OFFSET_TIMER_CCR:
1933			allowed = 1;
1934			break;
1935		default:
1936			break;
1937		}
1938	}
1939
1940	if (allowed) {
1941		vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
1942		    VIE_INVALID_GLA);
1943	}
1944
1945	/*
1946	 * Regardless of whether the APIC-access is allowed this handler
1947	 * always returns UNHANDLED:
1948	 * - if the access is allowed then it is handled by emulating the
1949	 *   instruction that caused the VM-exit (outside the critical section)
1950	 * - if the access is not allowed then it will be converted to an
1951	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
1952	 */
1953	return (UNHANDLED);
1954}
1955
1956static int
1957vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1958{
1959	int error, handled, in;
1960	struct vmxctx *vmxctx;
1961	struct vlapic *vlapic;
1962	struct vm_inout_str *vis;
1963	uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
1964	uint32_t reason;
1965	uint64_t qual, gpa;
1966	bool retu;
1967
1968	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
1969	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
1970
1971	handled = UNHANDLED;
1972	vmxctx = &vmx->ctx[vcpu];
1973
1974	qual = vmexit->u.vmx.exit_qualification;
1975	reason = vmexit->u.vmx.exit_reason;
1976	vmexit->exitcode = VM_EXITCODE_BOGUS;
1977
1978	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
1979
1980	/*
1981	 * VM exits that could be triggered during event injection on the
1982	 * previous VM entry need to be handled specially by re-injecting
1983	 * the event.
1984	 *
1985	 * See "Information for VM Exits During Event Delivery" in Intel SDM
1986	 * for details.
1987	 */
1988	switch (reason) {
1989	case EXIT_REASON_EPT_FAULT:
1990	case EXIT_REASON_EPT_MISCONFIG:
1991	case EXIT_REASON_APIC_ACCESS:
1992	case EXIT_REASON_TASK_SWITCH:
1993	case EXIT_REASON_EXCEPTION:
1994		idtvec_info = vmcs_idt_vectoring_info();
1995		if (idtvec_info & VMCS_IDT_VEC_VALID) {
1996			idtvec_info &= ~(1 << 12); /* clear undefined bit */
1997			vmcs_write(VMCS_ENTRY_INTR_INFO, idtvec_info);
1998			if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
1999				idtvec_err = vmcs_idt_vectoring_err();
2000				vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR,
2001				    idtvec_err);
2002			}
2003			/*
2004			 * If 'virtual NMIs' are being used and the VM-exit
2005			 * happened while injecting an NMI during the previous
2006			 * VM-entry, then clear "blocking by NMI" in the Guest
2007			 * Interruptibility-state.
2008			 */
2009			if ((idtvec_info & VMCS_INTR_T_MASK) ==
2010			    VMCS_INTR_T_NMI) {
2011				 vmx_clear_nmi_blocking(vmx, vcpu);
2012			}
2013			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2014		}
2015	default:
2016		idtvec_info = 0;
2017		break;
2018	}
2019
2020	switch (reason) {
2021	case EXIT_REASON_CR_ACCESS:
2022		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2023		switch (qual & 0xf) {
2024		case 0:
2025			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2026			break;
2027		case 4:
2028			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2029			break;
2030		case 8:
2031			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2032			break;
2033		}
2034		break;
2035	case EXIT_REASON_RDMSR:
2036		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2037		retu = false;
2038		ecx = vmxctx->guest_rcx;
2039		VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2040		error = emulate_rdmsr(vmx->vm, vcpu, ecx, &retu);
2041		if (error) {
2042			vmexit->exitcode = VM_EXITCODE_RDMSR;
2043			vmexit->u.msr.code = ecx;
2044		} else if (!retu) {
2045			handled = HANDLED;
2046		} else {
2047			/* Return to userspace with a valid exitcode */
2048			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2049			    ("emulate_wrmsr retu with bogus exitcode"));
2050		}
2051		break;
2052	case EXIT_REASON_WRMSR:
2053		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2054		retu = false;
2055		eax = vmxctx->guest_rax;
2056		ecx = vmxctx->guest_rcx;
2057		edx = vmxctx->guest_rdx;
2058		VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2059		    ecx, (uint64_t)edx << 32 | eax);
2060		error = emulate_wrmsr(vmx->vm, vcpu, ecx,
2061		    (uint64_t)edx << 32 | eax, &retu);
2062		if (error) {
2063			vmexit->exitcode = VM_EXITCODE_WRMSR;
2064			vmexit->u.msr.code = ecx;
2065			vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2066		} else if (!retu) {
2067			handled = HANDLED;
2068		} else {
2069			/* Return to userspace with a valid exitcode */
2070			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2071			    ("emulate_wrmsr retu with bogus exitcode"));
2072		}
2073		break;
2074	case EXIT_REASON_HLT:
2075		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2076		vmexit->exitcode = VM_EXITCODE_HLT;
2077		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2078		break;
2079	case EXIT_REASON_MTF:
2080		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2081		vmexit->exitcode = VM_EXITCODE_MTRAP;
2082		break;
2083	case EXIT_REASON_PAUSE:
2084		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2085		vmexit->exitcode = VM_EXITCODE_PAUSE;
2086		break;
2087	case EXIT_REASON_INTR_WINDOW:
2088		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2089		vmx_clear_int_window_exiting(vmx, vcpu);
2090		return (1);
2091	case EXIT_REASON_EXT_INTR:
2092		/*
2093		 * External interrupts serve only to cause VM exits and allow
2094		 * the host interrupt handler to run.
2095		 *
2096		 * If this external interrupt triggers a virtual interrupt
2097		 * to a VM, then that state will be recorded by the
2098		 * host interrupt handler in the VM's softc. We will inject
2099		 * this virtual interrupt during the subsequent VM enter.
2100		 */
2101		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2102
2103		/*
2104		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2105		 * This appears to be a bug in VMware Fusion?
2106		 */
2107		if (!(intr_info & VMCS_INTR_VALID))
2108			return (1);
2109		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2110		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2111		    ("VM exit interruption info invalid: %#x", intr_info));
2112		vmx_trigger_hostintr(intr_info & 0xff);
2113
2114		/*
2115		 * This is special. We want to treat this as an 'handled'
2116		 * VM-exit but not increment the instruction pointer.
2117		 */
2118		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2119		return (1);
2120	case EXIT_REASON_NMI_WINDOW:
2121		/* Exit to allow the pending virtual NMI to be injected */
2122		if (vm_nmi_pending(vmx->vm, vcpu))
2123			vmx_inject_nmi(vmx, vcpu);
2124		vmx_clear_nmi_window_exiting(vmx, vcpu);
2125		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2126		return (1);
2127	case EXIT_REASON_INOUT:
2128		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2129		vmexit->exitcode = VM_EXITCODE_INOUT;
2130		vmexit->u.inout.bytes = (qual & 0x7) + 1;
2131		vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2132		vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2133		vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2134		vmexit->u.inout.port = (uint16_t)(qual >> 16);
2135		vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2136		if (vmexit->u.inout.string) {
2137			inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2138			vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2139			vis = &vmexit->u.inout_str;
2140			vmx_paging_info(&vis->paging);
2141			vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2142			vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2143			vis->index = inout_str_index(vmx, vcpu, in);
2144			vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2145			vis->addrsize = inout_str_addrsize(inst_info);
2146			inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2147		}
2148		break;
2149	case EXIT_REASON_CPUID:
2150		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2151		handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2152		break;
2153	case EXIT_REASON_EXCEPTION:
2154		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2155		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2156		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2157		    ("VM exit interruption info invalid: %#x", intr_info));
2158
2159		/*
2160		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2161		 * fault encountered during the execution of IRET then we must
2162		 * restore the state of "virtual-NMI blocking" before resuming
2163		 * the guest.
2164		 *
2165		 * See "Resuming Guest Software after Handling an Exception".
2166		 */
2167		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2168		    (intr_info & 0xff) != IDT_DF &&
2169		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2170			vmx_restore_nmi_blocking(vmx, vcpu);
2171
2172		/*
2173		 * The NMI has already been handled in vmx_exit_handle_nmi().
2174		 */
2175		if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI)
2176			return (1);
2177		break;
2178	case EXIT_REASON_EPT_FAULT:
2179		/*
2180		 * If 'gpa' lies within the address space allocated to
2181		 * memory then this must be a nested page fault otherwise
2182		 * this must be an instruction that accesses MMIO space.
2183		 */
2184		gpa = vmcs_gpa();
2185		if (vm_mem_allocated(vmx->vm, gpa) ||
2186		    apic_access_fault(vmx, vcpu, gpa)) {
2187			vmexit->exitcode = VM_EXITCODE_PAGING;
2188			vmexit->u.paging.gpa = gpa;
2189			vmexit->u.paging.fault_type = ept_fault_type(qual);
2190			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2191		} else if (ept_emulation_fault(qual)) {
2192			vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2193			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2194		}
2195		/*
2196		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2197		 * EPT fault during the execution of IRET then we must restore
2198		 * the state of "virtual-NMI blocking" before resuming.
2199		 *
2200		 * See description of "NMI unblocking due to IRET" in
2201		 * "Exit Qualification for EPT Violations".
2202		 */
2203		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2204		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2205			vmx_restore_nmi_blocking(vmx, vcpu);
2206		break;
2207	case EXIT_REASON_VIRTUALIZED_EOI:
2208		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2209		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2210		vmexit->inst_length = 0;	/* trap-like */
2211		break;
2212	case EXIT_REASON_APIC_ACCESS:
2213		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2214		break;
2215	case EXIT_REASON_APIC_WRITE:
2216		/*
2217		 * APIC-write VM exit is trap-like so the %rip is already
2218		 * pointing to the next instruction.
2219		 */
2220		vmexit->inst_length = 0;
2221		vlapic = vm_lapic(vmx->vm, vcpu);
2222		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2223		break;
2224	case EXIT_REASON_XSETBV:
2225		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2226		break;
2227	default:
2228		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2229		break;
2230	}
2231
2232	if (handled) {
2233		/*
2234		 * It is possible that control is returned to userland
2235		 * even though we were able to handle the VM exit in the
2236		 * kernel.
2237		 *
2238		 * In such a case we want to make sure that the userland
2239		 * restarts guest execution at the instruction *after*
2240		 * the one we just processed. Therefore we update the
2241		 * guest rip in the VMCS and in 'vmexit'.
2242		 */
2243		vmexit->rip += vmexit->inst_length;
2244		vmexit->inst_length = 0;
2245		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2246	} else {
2247		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2248			/*
2249			 * If this VM exit was not claimed by anybody then
2250			 * treat it as a generic VMX exit.
2251			 */
2252			vmexit->exitcode = VM_EXITCODE_VMX;
2253			vmexit->u.vmx.status = VM_SUCCESS;
2254			vmexit->u.vmx.inst_type = 0;
2255			vmexit->u.vmx.inst_error = 0;
2256		} else {
2257			/*
2258			 * The exitcode and collateral have been populated.
2259			 * The VM exit will be processed further in userland.
2260			 */
2261		}
2262	}
2263	return (handled);
2264}
2265
2266static __inline void
2267vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2268{
2269
2270	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2271	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2272	    vmxctx->inst_fail_status));
2273
2274	vmexit->inst_length = 0;
2275	vmexit->exitcode = VM_EXITCODE_VMX;
2276	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2277	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2278	vmexit->u.vmx.exit_reason = ~0;
2279	vmexit->u.vmx.exit_qualification = ~0;
2280
2281	switch (rc) {
2282	case VMX_VMRESUME_ERROR:
2283	case VMX_VMLAUNCH_ERROR:
2284	case VMX_INVEPT_ERROR:
2285		vmexit->u.vmx.inst_type = rc;
2286		break;
2287	default:
2288		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2289	}
2290}
2291
2292/*
2293 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2294 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2295 * sufficient to simply vector to the NMI handler via a software interrupt.
2296 * However, this must be done before maskable interrupts are enabled
2297 * otherwise the "iret" issued by an interrupt handler will incorrectly
2298 * clear NMI blocking.
2299 */
2300static __inline void
2301vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2302{
2303	uint32_t intr_info;
2304
2305	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2306
2307	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2308		return;
2309
2310	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2311	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2312	    ("VM exit interruption info invalid: %#x", intr_info));
2313
2314	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2315		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2316		    "to NMI has invalid vector: %#x", intr_info));
2317		VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2318		__asm __volatile("int $2");
2319	}
2320}
2321
2322static int
2323vmx_run(void *arg, int vcpu, register_t startrip, pmap_t pmap,
2324    void *rendezvous_cookie, void *suspend_cookie)
2325{
2326	int rc, handled, launched;
2327	struct vmx *vmx;
2328	struct vm *vm;
2329	struct vmxctx *vmxctx;
2330	struct vmcs *vmcs;
2331	struct vm_exit *vmexit;
2332	struct vlapic *vlapic;
2333	uint64_t rip;
2334	uint32_t exit_reason;
2335
2336	vmx = arg;
2337	vm = vmx->vm;
2338	vmcs = &vmx->vmcs[vcpu];
2339	vmxctx = &vmx->ctx[vcpu];
2340	vlapic = vm_lapic(vm, vcpu);
2341	vmexit = vm_exitinfo(vm, vcpu);
2342	launched = 0;
2343
2344	KASSERT(vmxctx->pmap == pmap,
2345	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2346
2347	VMPTRLD(vmcs);
2348
2349	/*
2350	 * XXX
2351	 * We do this every time because we may setup the virtual machine
2352	 * from a different process than the one that actually runs it.
2353	 *
2354	 * If the life of a virtual machine was spent entirely in the context
2355	 * of a single process we could do this once in vmx_vminit().
2356	 */
2357	vmcs_write(VMCS_HOST_CR3, rcr3());
2358
2359	vmcs_write(VMCS_GUEST_RIP, startrip);
2360	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2361	do {
2362		handled = UNHANDLED;
2363
2364		/*
2365		 * Interrupts are disabled from this point on until the
2366		 * guest starts executing. This is done for the following
2367		 * reasons:
2368		 *
2369		 * If an AST is asserted on this thread after the check below,
2370		 * then the IPI_AST notification will not be lost, because it
2371		 * will cause a VM exit due to external interrupt as soon as
2372		 * the guest state is loaded.
2373		 *
2374		 * A posted interrupt after 'vmx_inject_interrupts()' will
2375		 * not be "lost" because it will be held pending in the host
2376		 * APIC because interrupts are disabled. The pending interrupt
2377		 * will be recognized as soon as the guest state is loaded.
2378		 *
2379		 * The same reasoning applies to the IPI generated by
2380		 * pmap_invalidate_ept().
2381		 */
2382		disable_intr();
2383		if (vcpu_suspended(suspend_cookie)) {
2384			enable_intr();
2385			vm_exit_suspended(vmx->vm, vcpu, vmcs_guest_rip());
2386			break;
2387		}
2388
2389		if (vcpu_rendezvous_pending(rendezvous_cookie)) {
2390			enable_intr();
2391			vm_exit_rendezvous(vmx->vm, vcpu, vmcs_guest_rip());
2392			break;
2393		}
2394
2395		if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
2396			enable_intr();
2397			vm_exit_astpending(vmx->vm, vcpu, vmcs_guest_rip());
2398			vmx_astpending_trace(vmx, vcpu, vmexit->rip);
2399			handled = HANDLED;
2400			break;
2401		}
2402
2403		vmx_inject_interrupts(vmx, vcpu, vlapic);
2404		vmx_run_trace(vmx, vcpu);
2405		rc = vmx_enter_guest(vmxctx, vmx, launched);
2406
2407		/* Collect some information for VM exit processing */
2408		vmexit->rip = rip = vmcs_guest_rip();
2409		vmexit->inst_length = vmexit_instruction_length();
2410		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2411		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2412
2413		if (rc == VMX_GUEST_VMEXIT) {
2414			vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2415			enable_intr();
2416			handled = vmx_exit_process(vmx, vcpu, vmexit);
2417		} else {
2418			enable_intr();
2419			vmx_exit_inst_error(vmxctx, rc, vmexit);
2420		}
2421		launched = 1;
2422		vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2423	} while (handled);
2424
2425	/*
2426	 * If a VM exit has been handled then the exitcode must be BOGUS
2427	 * If a VM exit is not handled then the exitcode must not be BOGUS
2428	 */
2429	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2430	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2431		panic("Mismatch between handled (%d) and exitcode (%d)",
2432		      handled, vmexit->exitcode);
2433	}
2434
2435	if (!handled)
2436		vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2437
2438	VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2439	    vmexit->exitcode);
2440
2441	VMCLEAR(vmcs);
2442	return (0);
2443}
2444
2445static void
2446vmx_vmcleanup(void *arg)
2447{
2448	int i;
2449	struct vmx *vmx = arg;
2450
2451	if (apic_access_virtualization(vmx, 0))
2452		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2453
2454	for (i = 0; i < VM_MAXCPU; i++)
2455		vpid_free(vmx->state[i].vpid);
2456
2457	free(vmx, M_VMX);
2458
2459	return;
2460}
2461
2462static register_t *
2463vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2464{
2465
2466	switch (reg) {
2467	case VM_REG_GUEST_RAX:
2468		return (&vmxctx->guest_rax);
2469	case VM_REG_GUEST_RBX:
2470		return (&vmxctx->guest_rbx);
2471	case VM_REG_GUEST_RCX:
2472		return (&vmxctx->guest_rcx);
2473	case VM_REG_GUEST_RDX:
2474		return (&vmxctx->guest_rdx);
2475	case VM_REG_GUEST_RSI:
2476		return (&vmxctx->guest_rsi);
2477	case VM_REG_GUEST_RDI:
2478		return (&vmxctx->guest_rdi);
2479	case VM_REG_GUEST_RBP:
2480		return (&vmxctx->guest_rbp);
2481	case VM_REG_GUEST_R8:
2482		return (&vmxctx->guest_r8);
2483	case VM_REG_GUEST_R9:
2484		return (&vmxctx->guest_r9);
2485	case VM_REG_GUEST_R10:
2486		return (&vmxctx->guest_r10);
2487	case VM_REG_GUEST_R11:
2488		return (&vmxctx->guest_r11);
2489	case VM_REG_GUEST_R12:
2490		return (&vmxctx->guest_r12);
2491	case VM_REG_GUEST_R13:
2492		return (&vmxctx->guest_r13);
2493	case VM_REG_GUEST_R14:
2494		return (&vmxctx->guest_r14);
2495	case VM_REG_GUEST_R15:
2496		return (&vmxctx->guest_r15);
2497	case VM_REG_GUEST_CR2:
2498		return (&vmxctx->guest_cr2);
2499	default:
2500		break;
2501	}
2502	return (NULL);
2503}
2504
2505static int
2506vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2507{
2508	register_t *regp;
2509
2510	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2511		*retval = *regp;
2512		return (0);
2513	} else
2514		return (EINVAL);
2515}
2516
2517static int
2518vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2519{
2520	register_t *regp;
2521
2522	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2523		*regp = val;
2524		return (0);
2525	} else
2526		return (EINVAL);
2527}
2528
2529static int
2530vmx_shadow_reg(int reg)
2531{
2532	int shreg;
2533
2534	shreg = -1;
2535
2536	switch (reg) {
2537	case VM_REG_GUEST_CR0:
2538		shreg = VMCS_CR0_SHADOW;
2539                break;
2540        case VM_REG_GUEST_CR4:
2541		shreg = VMCS_CR4_SHADOW;
2542		break;
2543	default:
2544		break;
2545	}
2546
2547	return (shreg);
2548}
2549
2550static int
2551vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2552{
2553	int running, hostcpu;
2554	struct vmx *vmx = arg;
2555
2556	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2557	if (running && hostcpu != curcpu)
2558		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2559
2560	if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2561		return (0);
2562
2563	return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2564}
2565
2566static int
2567vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2568{
2569	int error, hostcpu, running, shadow;
2570	uint64_t ctls;
2571	struct vmx *vmx = arg;
2572
2573	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2574	if (running && hostcpu != curcpu)
2575		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2576
2577	if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2578		return (0);
2579
2580	error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2581
2582	if (error == 0) {
2583		/*
2584		 * If the "load EFER" VM-entry control is 1 then the
2585		 * value of EFER.LMA must be identical to "IA-32e mode guest"
2586		 * bit in the VM-entry control.
2587		 */
2588		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2589		    (reg == VM_REG_GUEST_EFER)) {
2590			vmcs_getreg(&vmx->vmcs[vcpu], running,
2591				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2592			if (val & EFER_LMA)
2593				ctls |= VM_ENTRY_GUEST_LMA;
2594			else
2595				ctls &= ~VM_ENTRY_GUEST_LMA;
2596			vmcs_setreg(&vmx->vmcs[vcpu], running,
2597				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2598		}
2599
2600		shadow = vmx_shadow_reg(reg);
2601		if (shadow > 0) {
2602			/*
2603			 * Store the unmodified value in the shadow
2604			 */
2605			error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2606				    VMCS_IDENT(shadow), val);
2607		}
2608	}
2609
2610	return (error);
2611}
2612
2613static int
2614vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2615{
2616	int hostcpu, running;
2617	struct vmx *vmx = arg;
2618
2619	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2620	if (running && hostcpu != curcpu)
2621		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2622
2623	return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
2624}
2625
2626static int
2627vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2628{
2629	int hostcpu, running;
2630	struct vmx *vmx = arg;
2631
2632	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2633	if (running && hostcpu != curcpu)
2634		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2635
2636	return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
2637}
2638
2639static int
2640vmx_getcap(void *arg, int vcpu, int type, int *retval)
2641{
2642	struct vmx *vmx = arg;
2643	int vcap;
2644	int ret;
2645
2646	ret = ENOENT;
2647
2648	vcap = vmx->cap[vcpu].set;
2649
2650	switch (type) {
2651	case VM_CAP_HALT_EXIT:
2652		if (cap_halt_exit)
2653			ret = 0;
2654		break;
2655	case VM_CAP_PAUSE_EXIT:
2656		if (cap_pause_exit)
2657			ret = 0;
2658		break;
2659	case VM_CAP_MTRAP_EXIT:
2660		if (cap_monitor_trap)
2661			ret = 0;
2662		break;
2663	case VM_CAP_UNRESTRICTED_GUEST:
2664		if (cap_unrestricted_guest)
2665			ret = 0;
2666		break;
2667	case VM_CAP_ENABLE_INVPCID:
2668		if (cap_invpcid)
2669			ret = 0;
2670		break;
2671	default:
2672		break;
2673	}
2674
2675	if (ret == 0)
2676		*retval = (vcap & (1 << type)) ? 1 : 0;
2677
2678	return (ret);
2679}
2680
2681static int
2682vmx_setcap(void *arg, int vcpu, int type, int val)
2683{
2684	struct vmx *vmx = arg;
2685	struct vmcs *vmcs = &vmx->vmcs[vcpu];
2686	uint32_t baseval;
2687	uint32_t *pptr;
2688	int error;
2689	int flag;
2690	int reg;
2691	int retval;
2692
2693	retval = ENOENT;
2694	pptr = NULL;
2695
2696	switch (type) {
2697	case VM_CAP_HALT_EXIT:
2698		if (cap_halt_exit) {
2699			retval = 0;
2700			pptr = &vmx->cap[vcpu].proc_ctls;
2701			baseval = *pptr;
2702			flag = PROCBASED_HLT_EXITING;
2703			reg = VMCS_PRI_PROC_BASED_CTLS;
2704		}
2705		break;
2706	case VM_CAP_MTRAP_EXIT:
2707		if (cap_monitor_trap) {
2708			retval = 0;
2709			pptr = &vmx->cap[vcpu].proc_ctls;
2710			baseval = *pptr;
2711			flag = PROCBASED_MTF;
2712			reg = VMCS_PRI_PROC_BASED_CTLS;
2713		}
2714		break;
2715	case VM_CAP_PAUSE_EXIT:
2716		if (cap_pause_exit) {
2717			retval = 0;
2718			pptr = &vmx->cap[vcpu].proc_ctls;
2719			baseval = *pptr;
2720			flag = PROCBASED_PAUSE_EXITING;
2721			reg = VMCS_PRI_PROC_BASED_CTLS;
2722		}
2723		break;
2724	case VM_CAP_UNRESTRICTED_GUEST:
2725		if (cap_unrestricted_guest) {
2726			retval = 0;
2727			pptr = &vmx->cap[vcpu].proc_ctls2;
2728			baseval = *pptr;
2729			flag = PROCBASED2_UNRESTRICTED_GUEST;
2730			reg = VMCS_SEC_PROC_BASED_CTLS;
2731		}
2732		break;
2733	case VM_CAP_ENABLE_INVPCID:
2734		if (cap_invpcid) {
2735			retval = 0;
2736			pptr = &vmx->cap[vcpu].proc_ctls2;
2737			baseval = *pptr;
2738			flag = PROCBASED2_ENABLE_INVPCID;
2739			reg = VMCS_SEC_PROC_BASED_CTLS;
2740		}
2741		break;
2742	default:
2743		break;
2744	}
2745
2746	if (retval == 0) {
2747		if (val) {
2748			baseval |= flag;
2749		} else {
2750			baseval &= ~flag;
2751		}
2752		VMPTRLD(vmcs);
2753		error = vmwrite(reg, baseval);
2754		VMCLEAR(vmcs);
2755
2756		if (error) {
2757			retval = error;
2758		} else {
2759			/*
2760			 * Update optional stored flags, and record
2761			 * setting
2762			 */
2763			if (pptr != NULL) {
2764				*pptr = baseval;
2765			}
2766
2767			if (val) {
2768				vmx->cap[vcpu].set |= (1 << type);
2769			} else {
2770				vmx->cap[vcpu].set &= ~(1 << type);
2771			}
2772		}
2773	}
2774
2775        return (retval);
2776}
2777
2778struct vlapic_vtx {
2779	struct vlapic	vlapic;
2780	struct pir_desc	*pir_desc;
2781	struct vmx	*vmx;
2782};
2783
2784#define	VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)	\
2785do {									\
2786	VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",	\
2787	    level ? "level" : "edge", vector);				\
2788	VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
2789	VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
2790	VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
2791	VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
2792	VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
2793} while (0)
2794
2795/*
2796 * vlapic->ops handlers that utilize the APICv hardware assist described in
2797 * Chapter 29 of the Intel SDM.
2798 */
2799static int
2800vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
2801{
2802	struct vlapic_vtx *vlapic_vtx;
2803	struct pir_desc *pir_desc;
2804	uint64_t mask;
2805	int idx, notify;
2806
2807	vlapic_vtx = (struct vlapic_vtx *)vlapic;
2808	pir_desc = vlapic_vtx->pir_desc;
2809
2810	/*
2811	 * Keep track of interrupt requests in the PIR descriptor. This is
2812	 * because the virtual APIC page pointed to by the VMCS cannot be
2813	 * modified if the vcpu is running.
2814	 */
2815	idx = vector / 64;
2816	mask = 1UL << (vector % 64);
2817	atomic_set_long(&pir_desc->pir[idx], mask);
2818	notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
2819
2820	VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
2821	    level, "vmx_set_intr_ready");
2822	return (notify);
2823}
2824
2825static int
2826vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
2827{
2828	struct vlapic_vtx *vlapic_vtx;
2829	struct pir_desc *pir_desc;
2830	struct LAPIC *lapic;
2831	uint64_t pending, pirval;
2832	uint32_t ppr, vpr;
2833	int i;
2834
2835	/*
2836	 * This function is only expected to be called from the 'HLT' exit
2837	 * handler which does not care about the vector that is pending.
2838	 */
2839	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
2840
2841	vlapic_vtx = (struct vlapic_vtx *)vlapic;
2842	pir_desc = vlapic_vtx->pir_desc;
2843
2844	pending = atomic_load_acq_long(&pir_desc->pending);
2845	if (!pending)
2846		return (0);	/* common case */
2847
2848	/*
2849	 * If there is an interrupt pending then it will be recognized only
2850	 * if its priority is greater than the processor priority.
2851	 *
2852	 * Special case: if the processor priority is zero then any pending
2853	 * interrupt will be recognized.
2854	 */
2855	lapic = vlapic->apic_page;
2856	ppr = lapic->ppr & 0xf0;
2857	if (ppr == 0)
2858		return (1);
2859
2860	VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
2861	    lapic->ppr);
2862
2863	for (i = 3; i >= 0; i--) {
2864		pirval = pir_desc->pir[i];
2865		if (pirval != 0) {
2866			vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
2867			return (vpr > ppr);
2868		}
2869	}
2870	return (0);
2871}
2872
2873static void
2874vmx_intr_accepted(struct vlapic *vlapic, int vector)
2875{
2876
2877	panic("vmx_intr_accepted: not expected to be called");
2878}
2879
2880static void
2881vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
2882{
2883	struct vlapic_vtx *vlapic_vtx;
2884	struct vmx *vmx;
2885	struct vmcs *vmcs;
2886	uint64_t mask, val;
2887
2888	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
2889	KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
2890	    ("vmx_set_tmr: vcpu cannot be running"));
2891
2892	vlapic_vtx = (struct vlapic_vtx *)vlapic;
2893	vmx = vlapic_vtx->vmx;
2894	vmcs = &vmx->vmcs[vlapic->vcpuid];
2895	mask = 1UL << (vector % 64);
2896
2897	VMPTRLD(vmcs);
2898	val = vmcs_read(VMCS_EOI_EXIT(vector));
2899	if (level)
2900		val |= mask;
2901	else
2902		val &= ~mask;
2903	vmcs_write(VMCS_EOI_EXIT(vector), val);
2904	VMCLEAR(vmcs);
2905}
2906
2907static void
2908vmx_enable_x2apic_mode(struct vlapic *vlapic)
2909{
2910	struct vmx *vmx;
2911	struct vmcs *vmcs;
2912	uint32_t proc_ctls2;
2913	int vcpuid, error;
2914
2915	vcpuid = vlapic->vcpuid;
2916	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
2917	vmcs = &vmx->vmcs[vcpuid];
2918
2919	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
2920	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
2921	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
2922
2923	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
2924	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
2925	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
2926
2927	VMPTRLD(vmcs);
2928	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
2929	VMCLEAR(vmcs);
2930
2931	if (vlapic->vcpuid == 0) {
2932		/*
2933		 * The nested page table mappings are shared by all vcpus
2934		 * so unmap the APIC access page just once.
2935		 */
2936		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2937		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
2938		    __func__, error));
2939
2940		/*
2941		 * The MSR bitmap is shared by all vcpus so modify it only
2942		 * once in the context of vcpu 0.
2943		 */
2944		error = vmx_allow_x2apic_msrs(vmx);
2945		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
2946		    __func__, error));
2947	}
2948}
2949
2950static void
2951vmx_post_intr(struct vlapic *vlapic, int hostcpu)
2952{
2953
2954	ipi_cpu(hostcpu, pirvec);
2955}
2956
2957/*
2958 * Transfer the pending interrupts in the PIR descriptor to the IRR
2959 * in the virtual APIC page.
2960 */
2961static void
2962vmx_inject_pir(struct vlapic *vlapic)
2963{
2964	struct vlapic_vtx *vlapic_vtx;
2965	struct pir_desc *pir_desc;
2966	struct LAPIC *lapic;
2967	uint64_t val, pirval;
2968	int rvi, pirbase = -1;
2969	uint16_t intr_status_old, intr_status_new;
2970
2971	vlapic_vtx = (struct vlapic_vtx *)vlapic;
2972	pir_desc = vlapic_vtx->pir_desc;
2973	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
2974		VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
2975		    "no posted interrupt pending");
2976		return;
2977	}
2978
2979	pirval = 0;
2980	pirbase = -1;
2981	lapic = vlapic->apic_page;
2982
2983	val = atomic_readandclear_long(&pir_desc->pir[0]);
2984	if (val != 0) {
2985		lapic->irr0 |= val;
2986		lapic->irr1 |= val >> 32;
2987		pirbase = 0;
2988		pirval = val;
2989	}
2990
2991	val = atomic_readandclear_long(&pir_desc->pir[1]);
2992	if (val != 0) {
2993		lapic->irr2 |= val;
2994		lapic->irr3 |= val >> 32;
2995		pirbase = 64;
2996		pirval = val;
2997	}
2998
2999	val = atomic_readandclear_long(&pir_desc->pir[2]);
3000	if (val != 0) {
3001		lapic->irr4 |= val;
3002		lapic->irr5 |= val >> 32;
3003		pirbase = 128;
3004		pirval = val;
3005	}
3006
3007	val = atomic_readandclear_long(&pir_desc->pir[3]);
3008	if (val != 0) {
3009		lapic->irr6 |= val;
3010		lapic->irr7 |= val >> 32;
3011		pirbase = 192;
3012		pirval = val;
3013	}
3014
3015	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3016
3017	/*
3018	 * Update RVI so the processor can evaluate pending virtual
3019	 * interrupts on VM-entry.
3020	 *
3021	 * It is possible for pirval to be 0 here, even though the
3022	 * pending bit has been set. The scenario is:
3023	 * CPU-Y is sending a posted interrupt to CPU-X, which
3024	 * is running a guest and processing posted interrupts in h/w.
3025	 * CPU-X will eventually exit and the state seen in s/w is
3026	 * the pending bit set, but no PIR bits set.
3027	 *
3028	 *      CPU-X                      CPU-Y
3029	 *   (vm running)                (host running)
3030	 *   rx posted interrupt
3031	 *   CLEAR pending bit
3032	 *				 SET PIR bit
3033	 *   READ/CLEAR PIR bits
3034	 *				 SET pending bit
3035	 *   (vm exit)
3036	 *   pending bit set, PIR 0
3037	 */
3038	if (pirval != 0) {
3039		rvi = pirbase + flsl(pirval) - 1;
3040		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3041		intr_status_new = (intr_status_old & 0xFF00) | rvi;
3042		if (intr_status_new > intr_status_old) {
3043			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3044			VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3045			    "guest_intr_status changed from 0x%04x to 0x%04x",
3046			    intr_status_old, intr_status_new);
3047		}
3048	}
3049}
3050
3051static struct vlapic *
3052vmx_vlapic_init(void *arg, int vcpuid)
3053{
3054	struct vmx *vmx;
3055	struct vlapic *vlapic;
3056	struct vlapic_vtx *vlapic_vtx;
3057
3058	vmx = arg;
3059
3060	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3061	vlapic->vm = vmx->vm;
3062	vlapic->vcpuid = vcpuid;
3063	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3064
3065	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3066	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3067	vlapic_vtx->vmx = vmx;
3068
3069	if (virtual_interrupt_delivery) {
3070		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3071		vlapic->ops.pending_intr = vmx_pending_intr;
3072		vlapic->ops.intr_accepted = vmx_intr_accepted;
3073		vlapic->ops.set_tmr = vmx_set_tmr;
3074		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3075	}
3076
3077	if (posted_interrupts)
3078		vlapic->ops.post_intr = vmx_post_intr;
3079
3080	vlapic_init(vlapic);
3081
3082	return (vlapic);
3083}
3084
3085static void
3086vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3087{
3088
3089	vlapic_cleanup(vlapic);
3090	free(vlapic, M_VLAPIC);
3091}
3092
3093struct vmm_ops vmm_ops_intel = {
3094	vmx_init,
3095	vmx_cleanup,
3096	vmx_restore,
3097	vmx_vminit,
3098	vmx_run,
3099	vmx_vmcleanup,
3100	vmx_getreg,
3101	vmx_setreg,
3102	vmx_getdesc,
3103	vmx_setdesc,
3104	vmx_getcap,
3105	vmx_setcap,
3106	ept_vmspace_alloc,
3107	ept_vmspace_free,
3108	vmx_vlapic_init,
3109	vmx_vlapic_cleanup,
3110};
3111