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