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