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