]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/vmm/intel/vmx.c
PTI for amd64.
[FreeBSD/FreeBSD.git] / sys / amd64 / vmm / intel / vmx.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/smp.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/pcpu.h>
40 #include <sys/proc.h>
41 #include <sys/sysctl.h>
42
43 #include <vm/vm.h>
44 #include <vm/pmap.h>
45
46 #include <machine/psl.h>
47 #include <machine/cpufunc.h>
48 #include <machine/md_var.h>
49 #include <machine/segments.h>
50 #include <machine/smp.h>
51 #include <machine/specialreg.h>
52 #include <machine/vmparam.h>
53
54 #include <machine/vmm.h>
55 #include <machine/vmm_dev.h>
56 #include <machine/vmm_instruction_emul.h>
57 #include "vmm_lapic.h"
58 #include "vmm_host.h"
59 #include "vmm_ioport.h"
60 #include "vmm_ktr.h"
61 #include "vmm_stat.h"
62 #include "vatpic.h"
63 #include "vlapic.h"
64 #include "vlapic_priv.h"
65
66 #include "ept.h"
67 #include "vmx_cpufunc.h"
68 #include "vmx.h"
69 #include "vmx_msr.h"
70 #include "x86.h"
71 #include "vmx_controls.h"
72
73 #define PINBASED_CTLS_ONE_SETTING                                       \
74         (PINBASED_EXTINT_EXITING        |                               \
75          PINBASED_NMI_EXITING           |                               \
76          PINBASED_VIRTUAL_NMI)
77 #define PINBASED_CTLS_ZERO_SETTING      0
78
79 #define PROCBASED_CTLS_WINDOW_SETTING                                   \
80         (PROCBASED_INT_WINDOW_EXITING   |                               \
81          PROCBASED_NMI_WINDOW_EXITING)
82
83 #define PROCBASED_CTLS_ONE_SETTING                                      \
84         (PROCBASED_SECONDARY_CONTROLS   |                               \
85          PROCBASED_MWAIT_EXITING        |                               \
86          PROCBASED_MONITOR_EXITING      |                               \
87          PROCBASED_IO_EXITING           |                               \
88          PROCBASED_MSR_BITMAPS          |                               \
89          PROCBASED_CTLS_WINDOW_SETTING  |                               \
90          PROCBASED_CR8_LOAD_EXITING     |                               \
91          PROCBASED_CR8_STORE_EXITING)
92 #define PROCBASED_CTLS_ZERO_SETTING     \
93         (PROCBASED_CR3_LOAD_EXITING |   \
94         PROCBASED_CR3_STORE_EXITING |   \
95         PROCBASED_IO_BITMAPS)
96
97 #define PROCBASED_CTLS2_ONE_SETTING     PROCBASED2_ENABLE_EPT
98 #define PROCBASED_CTLS2_ZERO_SETTING    0
99
100 #define VM_EXIT_CTLS_ONE_SETTING                                        \
101         (VM_EXIT_HOST_LMA                       |                       \
102         VM_EXIT_SAVE_EFER                       |                       \
103         VM_EXIT_LOAD_EFER                       |                       \
104         VM_EXIT_ACKNOWLEDGE_INTERRUPT)
105
106 #define VM_EXIT_CTLS_ZERO_SETTING       VM_EXIT_SAVE_DEBUG_CONTROLS
107
108 #define VM_ENTRY_CTLS_ONE_SETTING       (VM_ENTRY_LOAD_EFER)
109
110 #define VM_ENTRY_CTLS_ZERO_SETTING                                      \
111         (VM_ENTRY_LOAD_DEBUG_CONTROLS           |                       \
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                 if (virtual_interrupt_delivery) {
920                         error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
921                         error += vmwrite(VMCS_VIRTUAL_APIC,
922                             vtophys(&vmx->apic_page[i]));
923                         error += vmwrite(VMCS_EOI_EXIT0, 0);
924                         error += vmwrite(VMCS_EOI_EXIT1, 0);
925                         error += vmwrite(VMCS_EOI_EXIT2, 0);
926                         error += vmwrite(VMCS_EOI_EXIT3, 0);
927                 }
928                 if (posted_interrupts) {
929                         error += vmwrite(VMCS_PIR_VECTOR, pirvec);
930                         error += vmwrite(VMCS_PIR_DESC,
931                             vtophys(&vmx->pir_desc[i]));
932                 }
933                 VMCLEAR(vmcs);
934                 KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
935
936                 vmx->cap[i].set = 0;
937                 vmx->cap[i].proc_ctls = procbased_ctls;
938                 vmx->cap[i].proc_ctls2 = procbased_ctls2;
939
940                 vmx->state[i].nextrip = ~0;
941                 vmx->state[i].lastcpu = NOCPU;
942                 vmx->state[i].vpid = vpid[i];
943
944                 /*
945                  * Set up the CR0/4 shadows, and init the read shadow
946                  * to the power-on register value from the Intel Sys Arch.
947                  *  CR0 - 0x60000010
948                  *  CR4 - 0
949                  */
950                 error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
951                 if (error != 0)
952                         panic("vmx_setup_cr0_shadow %d", error);
953
954                 error = vmx_setup_cr4_shadow(vmcs, 0);
955                 if (error != 0)
956                         panic("vmx_setup_cr4_shadow %d", error);
957
958                 vmx->ctx[i].pmap = pmap;
959         }
960
961         return (vmx);
962 }
963
964 static int
965 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
966 {
967         int handled, func;
968         
969         func = vmxctx->guest_rax;
970
971         handled = x86_emulate_cpuid(vm, vcpu,
972                                     (uint32_t*)(&vmxctx->guest_rax),
973                                     (uint32_t*)(&vmxctx->guest_rbx),
974                                     (uint32_t*)(&vmxctx->guest_rcx),
975                                     (uint32_t*)(&vmxctx->guest_rdx));
976         return (handled);
977 }
978
979 static __inline void
980 vmx_run_trace(struct vmx *vmx, int vcpu)
981 {
982 #ifdef KTR
983         VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
984 #endif
985 }
986
987 static __inline void
988 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
989                int handled)
990 {
991 #ifdef KTR
992         VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
993                  handled ? "handled" : "unhandled",
994                  exit_reason_to_str(exit_reason), rip);
995 #endif
996 }
997
998 static __inline void
999 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1000 {
1001 #ifdef KTR
1002         VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1003 #endif
1004 }
1005
1006 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1007 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1008
1009 /*
1010  * Invalidate guest mappings identified by its vpid from the TLB.
1011  */
1012 static __inline void
1013 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1014 {
1015         struct vmxstate *vmxstate;
1016         struct invvpid_desc invvpid_desc;
1017
1018         vmxstate = &vmx->state[vcpu];
1019         if (vmxstate->vpid == 0)
1020                 return;
1021
1022         if (!running) {
1023                 /*
1024                  * Set the 'lastcpu' to an invalid host cpu.
1025                  *
1026                  * This will invalidate TLB entries tagged with the vcpu's
1027                  * vpid the next time it runs via vmx_set_pcpu_defaults().
1028                  */
1029                 vmxstate->lastcpu = NOCPU;
1030                 return;
1031         }
1032
1033         KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1034             "critical section", __func__, vcpu));
1035
1036         /*
1037          * Invalidate all mappings tagged with 'vpid'
1038          *
1039          * We do this because this vcpu was executing on a different host
1040          * cpu when it last ran. We do not track whether it invalidated
1041          * mappings associated with its 'vpid' during that run. So we must
1042          * assume that the mappings associated with 'vpid' on 'curcpu' are
1043          * stale and invalidate them.
1044          *
1045          * Note that we incur this penalty only when the scheduler chooses to
1046          * move the thread associated with this vcpu between host cpus.
1047          *
1048          * Note also that this will invalidate mappings tagged with 'vpid'
1049          * for "all" EP4TAs.
1050          */
1051         if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1052                 invvpid_desc._res1 = 0;
1053                 invvpid_desc._res2 = 0;
1054                 invvpid_desc.vpid = vmxstate->vpid;
1055                 invvpid_desc.linear_addr = 0;
1056                 invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1057                 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1058         } else {
1059                 /*
1060                  * The invvpid can be skipped if an invept is going to
1061                  * be performed before entering the guest. The invept
1062                  * will invalidate combined mappings tagged with
1063                  * 'vmx->eptp' for all vpids.
1064                  */
1065                 vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1066         }
1067 }
1068
1069 static void
1070 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1071 {
1072         struct vmxstate *vmxstate;
1073
1074         vmxstate = &vmx->state[vcpu];
1075         if (vmxstate->lastcpu == curcpu)
1076                 return;
1077
1078         vmxstate->lastcpu = curcpu;
1079
1080         vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1081
1082         vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1083         vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1084         vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1085         vmx_invvpid(vmx, vcpu, pmap, 1);
1086 }
1087
1088 /*
1089  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1090  */
1091 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1092
1093 static void __inline
1094 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1095 {
1096
1097         if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1098                 vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1099                 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1100                 VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1101         }
1102 }
1103
1104 static void __inline
1105 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1106 {
1107
1108         KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1109             ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1110         vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1111         vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1112         VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1113 }
1114
1115 static void __inline
1116 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1117 {
1118
1119         if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1120                 vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1121                 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1122                 VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1123         }
1124 }
1125
1126 static void __inline
1127 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1128 {
1129
1130         KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1131             ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1132         vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1133         vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1134         VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1135 }
1136
1137 int
1138 vmx_set_tsc_offset(struct vmx *vmx, int vcpu, uint64_t offset)
1139 {
1140         int error;
1141
1142         if ((vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET) == 0) {
1143                 vmx->cap[vcpu].proc_ctls |= PROCBASED_TSC_OFFSET;
1144                 vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1145                 VCPU_CTR0(vmx->vm, vcpu, "Enabling TSC offsetting");
1146         }
1147
1148         error = vmwrite(VMCS_TSC_OFFSET, offset);
1149
1150         return (error);
1151 }
1152
1153 #define NMI_BLOCKING    (VMCS_INTERRUPTIBILITY_NMI_BLOCKING |           \
1154                          VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1155 #define HWINTR_BLOCKING (VMCS_INTERRUPTIBILITY_STI_BLOCKING |           \
1156                          VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1157
1158 static void
1159 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1160 {
1161         uint32_t gi, info;
1162
1163         gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1164         KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1165             "interruptibility-state %#x", gi));
1166
1167         info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1168         KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1169             "VM-entry interruption information %#x", info));
1170
1171         /*
1172          * Inject the virtual NMI. The vector must be the NMI IDT entry
1173          * or the VMCS entry check will fail.
1174          */
1175         info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1176         vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1177
1178         VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1179
1180         /* Clear the request */
1181         vm_nmi_clear(vmx->vm, vcpu);
1182 }
1183
1184 static void
1185 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1186     uint64_t guestrip)
1187 {
1188         int vector, need_nmi_exiting, extint_pending;
1189         uint64_t rflags, entryinfo;
1190         uint32_t gi, info;
1191
1192         if (vmx->state[vcpu].nextrip != guestrip) {
1193                 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1194                 if (gi & HWINTR_BLOCKING) {
1195                         VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1196                             "cleared due to rip change: %#lx/%#lx",
1197                             vmx->state[vcpu].nextrip, guestrip);
1198                         gi &= ~HWINTR_BLOCKING;
1199                         vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1200                 }
1201         }
1202
1203         if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1204                 KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1205                     "intinfo is not valid: %#lx", __func__, entryinfo));
1206
1207                 info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1208                 KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1209                      "pending exception: %#lx/%#x", __func__, entryinfo, info));
1210
1211                 info = entryinfo;
1212                 vector = info & 0xff;
1213                 if (vector == IDT_BP || vector == IDT_OF) {
1214                         /*
1215                          * VT-x requires #BP and #OF to be injected as software
1216                          * exceptions.
1217                          */
1218                         info &= ~VMCS_INTR_T_MASK;
1219                         info |= VMCS_INTR_T_SWEXCEPTION;
1220                 }
1221
1222                 if (info & VMCS_INTR_DEL_ERRCODE)
1223                         vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1224
1225                 vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1226         }
1227
1228         if (vm_nmi_pending(vmx->vm, vcpu)) {
1229                 /*
1230                  * If there are no conditions blocking NMI injection then
1231                  * inject it directly here otherwise enable "NMI window
1232                  * exiting" to inject it as soon as we can.
1233                  *
1234                  * We also check for STI_BLOCKING because some implementations
1235                  * don't allow NMI injection in this case. If we are running
1236                  * on a processor that doesn't have this restriction it will
1237                  * immediately exit and the NMI will be injected in the
1238                  * "NMI window exiting" handler.
1239                  */
1240                 need_nmi_exiting = 1;
1241                 gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1242                 if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1243                         info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1244                         if ((info & VMCS_INTR_VALID) == 0) {
1245                                 vmx_inject_nmi(vmx, vcpu);
1246                                 need_nmi_exiting = 0;
1247                         } else {
1248                                 VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1249                                     "due to VM-entry intr info %#x", info);
1250                         }
1251                 } else {
1252                         VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1253                             "Guest Interruptibility-state %#x", gi);
1254                 }
1255
1256                 if (need_nmi_exiting)
1257                         vmx_set_nmi_window_exiting(vmx, vcpu);
1258         }
1259
1260         extint_pending = vm_extint_pending(vmx->vm, vcpu);
1261
1262         if (!extint_pending && virtual_interrupt_delivery) {
1263                 vmx_inject_pir(vlapic);
1264                 return;
1265         }
1266
1267         /*
1268          * If interrupt-window exiting is already in effect then don't bother
1269          * checking for pending interrupts. This is just an optimization and
1270          * not needed for correctness.
1271          */
1272         if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1273                 VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1274                     "pending int_window_exiting");
1275                 return;
1276         }
1277
1278         if (!extint_pending) {
1279                 /* Ask the local apic for a vector to inject */
1280                 if (!vlapic_pending_intr(vlapic, &vector))
1281                         return;
1282
1283                 /*
1284                  * From the Intel SDM, Volume 3, Section "Maskable
1285                  * Hardware Interrupts":
1286                  * - maskable interrupt vectors [16,255] can be delivered
1287                  *   through the local APIC.
1288                 */
1289                 KASSERT(vector >= 16 && vector <= 255,
1290                     ("invalid vector %d from local APIC", vector));
1291         } else {
1292                 /* Ask the legacy pic for a vector to inject */
1293                 vatpic_pending_intr(vmx->vm, &vector);
1294
1295                 /*
1296                  * From the Intel SDM, Volume 3, Section "Maskable
1297                  * Hardware Interrupts":
1298                  * - maskable interrupt vectors [0,255] can be delivered
1299                  *   through the INTR pin.
1300                  */
1301                 KASSERT(vector >= 0 && vector <= 255,
1302                     ("invalid vector %d from INTR", vector));
1303         }
1304
1305         /* Check RFLAGS.IF and the interruptibility state of the guest */
1306         rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1307         if ((rflags & PSL_I) == 0) {
1308                 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1309                     "rflags %#lx", vector, rflags);
1310                 goto cantinject;
1311         }
1312
1313         gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1314         if (gi & HWINTR_BLOCKING) {
1315                 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1316                     "Guest Interruptibility-state %#x", vector, gi);
1317                 goto cantinject;
1318         }
1319
1320         info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1321         if (info & VMCS_INTR_VALID) {
1322                 /*
1323                  * This is expected and could happen for multiple reasons:
1324                  * - A vectoring VM-entry was aborted due to astpending
1325                  * - A VM-exit happened during event injection.
1326                  * - An exception was injected above.
1327                  * - An NMI was injected above or after "NMI window exiting"
1328                  */
1329                 VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1330                     "VM-entry intr info %#x", vector, info);
1331                 goto cantinject;
1332         }
1333
1334         /* Inject the interrupt */
1335         info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1336         info |= vector;
1337         vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1338
1339         if (!extint_pending) {
1340                 /* Update the Local APIC ISR */
1341                 vlapic_intr_accepted(vlapic, vector);
1342         } else {
1343                 vm_extint_clear(vmx->vm, vcpu);
1344                 vatpic_intr_accepted(vmx->vm, vector);
1345
1346                 /*
1347                  * After we accepted the current ExtINT the PIC may
1348                  * have posted another one.  If that is the case, set
1349                  * the Interrupt Window Exiting execution control so
1350                  * we can inject that one too.
1351                  *
1352                  * Also, interrupt window exiting allows us to inject any
1353                  * pending APIC vector that was preempted by the ExtINT
1354                  * as soon as possible. This applies both for the software
1355                  * emulated vlapic and the hardware assisted virtual APIC.
1356                  */
1357                 vmx_set_int_window_exiting(vmx, vcpu);
1358         }
1359
1360         VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1361
1362         return;
1363
1364 cantinject:
1365         /*
1366          * Set the Interrupt Window Exiting execution control so we can inject
1367          * the interrupt as soon as blocking condition goes away.
1368          */
1369         vmx_set_int_window_exiting(vmx, vcpu);
1370 }
1371
1372 /*
1373  * If the Virtual NMIs execution control is '1' then the logical processor
1374  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1375  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1376  * virtual-NMI blocking.
1377  *
1378  * This unblocking occurs even if the IRET causes a fault. In this case the
1379  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1380  */
1381 static void
1382 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1383 {
1384         uint32_t gi;
1385
1386         VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1387         gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1388         gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1389         vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1390 }
1391
1392 static void
1393 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1394 {
1395         uint32_t gi;
1396
1397         VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1398         gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1399         gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1400         vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1401 }
1402
1403 static void
1404 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1405 {
1406         uint32_t gi;
1407
1408         gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1409         KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1410             ("NMI blocking is not in effect %#x", gi));
1411 }
1412
1413 static int
1414 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1415 {
1416         struct vmxctx *vmxctx;
1417         uint64_t xcrval;
1418         const struct xsave_limits *limits;
1419
1420         vmxctx = &vmx->ctx[vcpu];
1421         limits = vmm_get_xsave_limits();
1422
1423         /*
1424          * Note that the processor raises a GP# fault on its own if
1425          * xsetbv is executed for CPL != 0, so we do not have to
1426          * emulate that fault here.
1427          */
1428
1429         /* Only xcr0 is supported. */
1430         if (vmxctx->guest_rcx != 0) {
1431                 vm_inject_gp(vmx->vm, vcpu);
1432                 return (HANDLED);
1433         }
1434
1435         /* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1436         if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1437                 vm_inject_ud(vmx->vm, vcpu);
1438                 return (HANDLED);
1439         }
1440
1441         xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1442         if ((xcrval & ~limits->xcr0_allowed) != 0) {
1443                 vm_inject_gp(vmx->vm, vcpu);
1444                 return (HANDLED);
1445         }
1446
1447         if (!(xcrval & XFEATURE_ENABLED_X87)) {
1448                 vm_inject_gp(vmx->vm, vcpu);
1449                 return (HANDLED);
1450         }
1451
1452         /* AVX (YMM_Hi128) requires SSE. */
1453         if (xcrval & XFEATURE_ENABLED_AVX &&
1454             (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1455                 vm_inject_gp(vmx->vm, vcpu);
1456                 return (HANDLED);
1457         }
1458
1459         /*
1460          * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1461          * ZMM_Hi256, and Hi16_ZMM.
1462          */
1463         if (xcrval & XFEATURE_AVX512 &&
1464             (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1465             (XFEATURE_AVX512 | XFEATURE_AVX)) {
1466                 vm_inject_gp(vmx->vm, vcpu);
1467                 return (HANDLED);
1468         }
1469
1470         /*
1471          * Intel MPX requires both bound register state flags to be
1472          * set.
1473          */
1474         if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1475             ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1476                 vm_inject_gp(vmx->vm, vcpu);
1477                 return (HANDLED);
1478         }
1479
1480         /*
1481          * This runs "inside" vmrun() with the guest's FPU state, so
1482          * modifying xcr0 directly modifies the guest's xcr0, not the
1483          * host's.
1484          */
1485         load_xcr(0, xcrval);
1486         return (HANDLED);
1487 }
1488
1489 static uint64_t
1490 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1491 {
1492         const struct vmxctx *vmxctx;
1493
1494         vmxctx = &vmx->ctx[vcpu];
1495
1496         switch (ident) {
1497         case 0:
1498                 return (vmxctx->guest_rax);
1499         case 1:
1500                 return (vmxctx->guest_rcx);
1501         case 2:
1502                 return (vmxctx->guest_rdx);
1503         case 3:
1504                 return (vmxctx->guest_rbx);
1505         case 4:
1506                 return (vmcs_read(VMCS_GUEST_RSP));
1507         case 5:
1508                 return (vmxctx->guest_rbp);
1509         case 6:
1510                 return (vmxctx->guest_rsi);
1511         case 7:
1512                 return (vmxctx->guest_rdi);
1513         case 8:
1514                 return (vmxctx->guest_r8);
1515         case 9:
1516                 return (vmxctx->guest_r9);
1517         case 10:
1518                 return (vmxctx->guest_r10);
1519         case 11:
1520                 return (vmxctx->guest_r11);
1521         case 12:
1522                 return (vmxctx->guest_r12);
1523         case 13:
1524                 return (vmxctx->guest_r13);
1525         case 14:
1526                 return (vmxctx->guest_r14);
1527         case 15:
1528                 return (vmxctx->guest_r15);
1529         default:
1530                 panic("invalid vmx register %d", ident);
1531         }
1532 }
1533
1534 static void
1535 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1536 {
1537         struct vmxctx *vmxctx;
1538
1539         vmxctx = &vmx->ctx[vcpu];
1540
1541         switch (ident) {
1542         case 0:
1543                 vmxctx->guest_rax = regval;
1544                 break;
1545         case 1:
1546                 vmxctx->guest_rcx = regval;
1547                 break;
1548         case 2:
1549                 vmxctx->guest_rdx = regval;
1550                 break;
1551         case 3:
1552                 vmxctx->guest_rbx = regval;
1553                 break;
1554         case 4:
1555                 vmcs_write(VMCS_GUEST_RSP, regval);
1556                 break;
1557         case 5:
1558                 vmxctx->guest_rbp = regval;
1559                 break;
1560         case 6:
1561                 vmxctx->guest_rsi = regval;
1562                 break;
1563         case 7:
1564                 vmxctx->guest_rdi = regval;
1565                 break;
1566         case 8:
1567                 vmxctx->guest_r8 = regval;
1568                 break;
1569         case 9:
1570                 vmxctx->guest_r9 = regval;
1571                 break;
1572         case 10:
1573                 vmxctx->guest_r10 = regval;
1574                 break;
1575         case 11:
1576                 vmxctx->guest_r11 = regval;
1577                 break;
1578         case 12:
1579                 vmxctx->guest_r12 = regval;
1580                 break;
1581         case 13:
1582                 vmxctx->guest_r13 = regval;
1583                 break;
1584         case 14:
1585                 vmxctx->guest_r14 = regval;
1586                 break;
1587         case 15:
1588                 vmxctx->guest_r15 = regval;
1589                 break;
1590         default:
1591                 panic("invalid vmx register %d", ident);
1592         }
1593 }
1594
1595 static int
1596 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1597 {
1598         uint64_t crval, regval;
1599
1600         /* We only handle mov to %cr0 at this time */
1601         if ((exitqual & 0xf0) != 0x00)
1602                 return (UNHANDLED);
1603
1604         regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1605
1606         vmcs_write(VMCS_CR0_SHADOW, regval);
1607
1608         crval = regval | cr0_ones_mask;
1609         crval &= ~cr0_zeros_mask;
1610         vmcs_write(VMCS_GUEST_CR0, crval);
1611
1612         if (regval & CR0_PG) {
1613                 uint64_t efer, entry_ctls;
1614
1615                 /*
1616                  * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1617                  * the "IA-32e mode guest" bit in VM-entry control must be
1618                  * equal.
1619                  */
1620                 efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1621                 if (efer & EFER_LME) {
1622                         efer |= EFER_LMA;
1623                         vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1624                         entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1625                         entry_ctls |= VM_ENTRY_GUEST_LMA;
1626                         vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1627                 }
1628         }
1629
1630         return (HANDLED);
1631 }
1632
1633 static int
1634 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1635 {
1636         uint64_t crval, regval;
1637
1638         /* We only handle mov to %cr4 at this time */
1639         if ((exitqual & 0xf0) != 0x00)
1640                 return (UNHANDLED);
1641
1642         regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1643
1644         vmcs_write(VMCS_CR4_SHADOW, regval);
1645
1646         crval = regval | cr4_ones_mask;
1647         crval &= ~cr4_zeros_mask;
1648         vmcs_write(VMCS_GUEST_CR4, crval);
1649
1650         return (HANDLED);
1651 }
1652
1653 static int
1654 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1655 {
1656         struct vlapic *vlapic;
1657         uint64_t cr8;
1658         int regnum;
1659
1660         /* We only handle mov %cr8 to/from a register at this time. */
1661         if ((exitqual & 0xe0) != 0x00) {
1662                 return (UNHANDLED);
1663         }
1664
1665         vlapic = vm_lapic(vmx->vm, vcpu);
1666         regnum = (exitqual >> 8) & 0xf;
1667         if (exitqual & 0x10) {
1668                 cr8 = vlapic_get_cr8(vlapic);
1669                 vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1670         } else {
1671                 cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1672                 vlapic_set_cr8(vlapic, cr8);
1673         }
1674
1675         return (HANDLED);
1676 }
1677
1678 /*
1679  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1680  */
1681 static int
1682 vmx_cpl(void)
1683 {
1684         uint32_t ssar;
1685
1686         ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1687         return ((ssar >> 5) & 0x3);
1688 }
1689
1690 static enum vm_cpu_mode
1691 vmx_cpu_mode(void)
1692 {
1693         uint32_t csar;
1694
1695         if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1696                 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1697                 if (csar & 0x2000)
1698                         return (CPU_MODE_64BIT);        /* CS.L = 1 */
1699                 else
1700                         return (CPU_MODE_COMPATIBILITY);
1701         } else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1702                 return (CPU_MODE_PROTECTED);
1703         } else {
1704                 return (CPU_MODE_REAL);
1705         }
1706 }
1707
1708 static enum vm_paging_mode
1709 vmx_paging_mode(void)
1710 {
1711
1712         if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1713                 return (PAGING_MODE_FLAT);
1714         if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1715                 return (PAGING_MODE_32);
1716         if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1717                 return (PAGING_MODE_64);
1718         else
1719                 return (PAGING_MODE_PAE);
1720 }
1721
1722 static uint64_t
1723 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1724 {
1725         uint64_t val;
1726         int error;
1727         enum vm_reg_name reg;
1728
1729         reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1730         error = vmx_getreg(vmx, vcpuid, reg, &val);
1731         KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1732         return (val);
1733 }
1734
1735 static uint64_t
1736 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1737 {
1738         uint64_t val;
1739         int error;
1740
1741         if (rep) {
1742                 error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1743                 KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1744         } else {
1745                 val = 1;
1746         }
1747         return (val);
1748 }
1749
1750 static int
1751 inout_str_addrsize(uint32_t inst_info)
1752 {
1753         uint32_t size;
1754
1755         size = (inst_info >> 7) & 0x7;
1756         switch (size) {
1757         case 0:
1758                 return (2);     /* 16 bit */
1759         case 1:
1760                 return (4);     /* 32 bit */
1761         case 2:
1762                 return (8);     /* 64 bit */
1763         default:
1764                 panic("%s: invalid size encoding %d", __func__, size);
1765         }
1766 }
1767
1768 static void
1769 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1770     struct vm_inout_str *vis)
1771 {
1772         int error, s;
1773
1774         if (in) {
1775                 vis->seg_name = VM_REG_GUEST_ES;
1776         } else {
1777                 s = (inst_info >> 15) & 0x7;
1778                 vis->seg_name = vm_segment_name(s);
1779         }
1780
1781         error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1782         KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1783 }
1784
1785 static void
1786 vmx_paging_info(struct vm_guest_paging *paging)
1787 {
1788         paging->cr3 = vmcs_guest_cr3();
1789         paging->cpl = vmx_cpl();
1790         paging->cpu_mode = vmx_cpu_mode();
1791         paging->paging_mode = vmx_paging_mode();
1792 }
1793
1794 static void
1795 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1796 {
1797         struct vm_guest_paging *paging;
1798         uint32_t csar;
1799
1800         paging = &vmexit->u.inst_emul.paging;
1801
1802         vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1803         vmexit->inst_length = 0;
1804         vmexit->u.inst_emul.gpa = gpa;
1805         vmexit->u.inst_emul.gla = gla;
1806         vmx_paging_info(paging);
1807         switch (paging->cpu_mode) {
1808         case CPU_MODE_REAL:
1809                 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1810                 vmexit->u.inst_emul.cs_d = 0;
1811                 break;
1812         case CPU_MODE_PROTECTED:
1813         case CPU_MODE_COMPATIBILITY:
1814                 vmexit->u.inst_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1815                 csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1816                 vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1817                 break;
1818         default:
1819                 vmexit->u.inst_emul.cs_base = 0;
1820                 vmexit->u.inst_emul.cs_d = 0;
1821                 break;
1822         }
1823         vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1824 }
1825
1826 static int
1827 ept_fault_type(uint64_t ept_qual)
1828 {
1829         int fault_type;
1830
1831         if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1832                 fault_type = VM_PROT_WRITE;
1833         else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1834                 fault_type = VM_PROT_EXECUTE;
1835         else
1836                 fault_type= VM_PROT_READ;
1837
1838         return (fault_type);
1839 }
1840
1841 static boolean_t
1842 ept_emulation_fault(uint64_t ept_qual)
1843 {
1844         int read, write;
1845
1846         /* EPT fault on an instruction fetch doesn't make sense here */
1847         if (ept_qual & EPT_VIOLATION_INST_FETCH)
1848                 return (FALSE);
1849
1850         /* EPT fault must be a read fault or a write fault */
1851         read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1852         write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1853         if ((read | write) == 0)
1854                 return (FALSE);
1855
1856         /*
1857          * The EPT violation must have been caused by accessing a
1858          * guest-physical address that is a translation of a guest-linear
1859          * address.
1860          */
1861         if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1862             (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1863                 return (FALSE);
1864         }
1865
1866         return (TRUE);
1867 }
1868
1869 static __inline int
1870 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1871 {
1872         uint32_t proc_ctls2;
1873
1874         proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1875         return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1876 }
1877
1878 static __inline int
1879 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1880 {
1881         uint32_t proc_ctls2;
1882
1883         proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1884         return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1885 }
1886
1887 static int
1888 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1889     uint64_t qual)
1890 {
1891         int error, handled, offset;
1892         uint32_t *apic_regs, vector;
1893         bool retu;
1894
1895         handled = HANDLED;
1896         offset = APIC_WRITE_OFFSET(qual);
1897
1898         if (!apic_access_virtualization(vmx, vcpuid)) {
1899                 /*
1900                  * In general there should not be any APIC write VM-exits
1901                  * unless APIC-access virtualization is enabled.
1902                  *
1903                  * However self-IPI virtualization can legitimately trigger
1904                  * an APIC-write VM-exit so treat it specially.
1905                  */
1906                 if (x2apic_virtualization(vmx, vcpuid) &&
1907                     offset == APIC_OFFSET_SELF_IPI) {
1908                         apic_regs = (uint32_t *)(vlapic->apic_page);
1909                         vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1910                         vlapic_self_ipi_handler(vlapic, vector);
1911                         return (HANDLED);
1912                 } else
1913                         return (UNHANDLED);
1914         }
1915
1916         switch (offset) {
1917         case APIC_OFFSET_ID:
1918                 vlapic_id_write_handler(vlapic);
1919                 break;
1920         case APIC_OFFSET_LDR:
1921                 vlapic_ldr_write_handler(vlapic);
1922                 break;
1923         case APIC_OFFSET_DFR:
1924                 vlapic_dfr_write_handler(vlapic);
1925                 break;
1926         case APIC_OFFSET_SVR:
1927                 vlapic_svr_write_handler(vlapic);
1928                 break;
1929         case APIC_OFFSET_ESR:
1930                 vlapic_esr_write_handler(vlapic);
1931                 break;
1932         case APIC_OFFSET_ICR_LOW:
1933                 retu = false;
1934                 error = vlapic_icrlo_write_handler(vlapic, &retu);
1935                 if (error != 0 || retu)
1936                         handled = UNHANDLED;
1937                 break;
1938         case APIC_OFFSET_CMCI_LVT:
1939         case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1940                 vlapic_lvt_write_handler(vlapic, offset);
1941                 break;
1942         case APIC_OFFSET_TIMER_ICR:
1943                 vlapic_icrtmr_write_handler(vlapic);
1944                 break;
1945         case APIC_OFFSET_TIMER_DCR:
1946                 vlapic_dcr_write_handler(vlapic);
1947                 break;
1948         default:
1949                 handled = UNHANDLED;
1950                 break;
1951         }
1952         return (handled);
1953 }
1954
1955 static bool
1956 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1957 {
1958
1959         if (apic_access_virtualization(vmx, vcpuid) &&
1960             (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1961                 return (true);
1962         else
1963                 return (false);
1964 }
1965
1966 static int
1967 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1968 {
1969         uint64_t qual;
1970         int access_type, offset, allowed;
1971
1972         if (!apic_access_virtualization(vmx, vcpuid))
1973                 return (UNHANDLED);
1974
1975         qual = vmexit->u.vmx.exit_qualification;
1976         access_type = APIC_ACCESS_TYPE(qual);
1977         offset = APIC_ACCESS_OFFSET(qual);
1978
1979         allowed = 0;
1980         if (access_type == 0) {
1981                 /*
1982                  * Read data access to the following registers is expected.
1983                  */
1984                 switch (offset) {
1985                 case APIC_OFFSET_APR:
1986                 case APIC_OFFSET_PPR:
1987                 case APIC_OFFSET_RRR:
1988                 case APIC_OFFSET_CMCI_LVT:
1989                 case APIC_OFFSET_TIMER_CCR:
1990                         allowed = 1;
1991                         break;
1992                 default:
1993                         break;
1994                 }
1995         } else if (access_type == 1) {
1996                 /*
1997                  * Write data access to the following registers is expected.
1998                  */
1999                 switch (offset) {
2000                 case APIC_OFFSET_VER:
2001                 case APIC_OFFSET_APR:
2002                 case APIC_OFFSET_PPR:
2003                 case APIC_OFFSET_RRR:
2004                 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2005                 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2006                 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2007                 case APIC_OFFSET_CMCI_LVT:
2008                 case APIC_OFFSET_TIMER_CCR:
2009                         allowed = 1;
2010                         break;
2011                 default:
2012                         break;
2013                 }
2014         }
2015
2016         if (allowed) {
2017                 vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
2018                     VIE_INVALID_GLA);
2019         }
2020
2021         /*
2022          * Regardless of whether the APIC-access is allowed this handler
2023          * always returns UNHANDLED:
2024          * - if the access is allowed then it is handled by emulating the
2025          *   instruction that caused the VM-exit (outside the critical section)
2026          * - if the access is not allowed then it will be converted to an
2027          *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2028          */
2029         return (UNHANDLED);
2030 }
2031
2032 static enum task_switch_reason
2033 vmx_task_switch_reason(uint64_t qual)
2034 {
2035         int reason;
2036
2037         reason = (qual >> 30) & 0x3;
2038         switch (reason) {
2039         case 0:
2040                 return (TSR_CALL);
2041         case 1:
2042                 return (TSR_IRET);
2043         case 2:
2044                 return (TSR_JMP);
2045         case 3:
2046                 return (TSR_IDT_GATE);
2047         default:
2048                 panic("%s: invalid reason %d", __func__, reason);
2049         }
2050 }
2051
2052 static int
2053 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2054 {
2055         int error;
2056
2057         if (lapic_msr(num))
2058                 error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2059         else
2060                 error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2061
2062         return (error);
2063 }
2064
2065 static int
2066 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2067 {
2068         struct vmxctx *vmxctx;
2069         uint64_t result;
2070         uint32_t eax, edx;
2071         int error;
2072
2073         if (lapic_msr(num))
2074                 error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2075         else
2076                 error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2077
2078         if (error == 0) {
2079                 eax = result;
2080                 vmxctx = &vmx->ctx[vcpuid];
2081                 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2082                 KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2083
2084                 edx = result >> 32;
2085                 error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2086                 KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2087         }
2088
2089         return (error);
2090 }
2091
2092 static int
2093 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2094 {
2095         int error, errcode, errcode_valid, handled, in;
2096         struct vmxctx *vmxctx;
2097         struct vlapic *vlapic;
2098         struct vm_inout_str *vis;
2099         struct vm_task_switch *ts;
2100         uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2101         uint32_t intr_type, intr_vec, reason;
2102         uint64_t exitintinfo, qual, gpa;
2103         bool retu;
2104
2105         CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2106         CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2107
2108         handled = UNHANDLED;
2109         vmxctx = &vmx->ctx[vcpu];
2110
2111         qual = vmexit->u.vmx.exit_qualification;
2112         reason = vmexit->u.vmx.exit_reason;
2113         vmexit->exitcode = VM_EXITCODE_BOGUS;
2114
2115         vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2116
2117         /*
2118          * VM-entry failures during or after loading guest state.
2119          *
2120          * These VM-exits are uncommon but must be handled specially
2121          * as most VM-exit fields are not populated as usual.
2122          */
2123         if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2124                 VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2125                 __asm __volatile("int $18");
2126                 return (1);
2127         }
2128
2129         /*
2130          * VM exits that can be triggered during event delivery need to
2131          * be handled specially by re-injecting the event if the IDT
2132          * vectoring information field's valid bit is set.
2133          *
2134          * See "Information for VM Exits During Event Delivery" in Intel SDM
2135          * for details.
2136          */
2137         idtvec_info = vmcs_idt_vectoring_info();
2138         if (idtvec_info & VMCS_IDT_VEC_VALID) {
2139                 idtvec_info &= ~(1 << 12); /* clear undefined bit */
2140                 exitintinfo = idtvec_info;
2141                 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2142                         idtvec_err = vmcs_idt_vectoring_err();
2143                         exitintinfo |= (uint64_t)idtvec_err << 32;
2144                 }
2145                 error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2146                 KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2147                     __func__, error));
2148
2149                 /*
2150                  * If 'virtual NMIs' are being used and the VM-exit
2151                  * happened while injecting an NMI during the previous
2152                  * VM-entry, then clear "blocking by NMI" in the
2153                  * Guest Interruptibility-State so the NMI can be
2154                  * reinjected on the subsequent VM-entry.
2155                  *
2156                  * However, if the NMI was being delivered through a task
2157                  * gate, then the new task must start execution with NMIs
2158                  * blocked so don't clear NMI blocking in this case.
2159                  */
2160                 intr_type = idtvec_info & VMCS_INTR_T_MASK;
2161                 if (intr_type == VMCS_INTR_T_NMI) {
2162                         if (reason != EXIT_REASON_TASK_SWITCH)
2163                                 vmx_clear_nmi_blocking(vmx, vcpu);
2164                         else
2165                                 vmx_assert_nmi_blocking(vmx, vcpu);
2166                 }
2167
2168                 /*
2169                  * Update VM-entry instruction length if the event being
2170                  * delivered was a software interrupt or software exception.
2171                  */
2172                 if (intr_type == VMCS_INTR_T_SWINTR ||
2173                     intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2174                     intr_type == VMCS_INTR_T_SWEXCEPTION) {
2175                         vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2176                 }
2177         }
2178
2179         switch (reason) {
2180         case EXIT_REASON_TASK_SWITCH:
2181                 ts = &vmexit->u.task_switch;
2182                 ts->tsssel = qual & 0xffff;
2183                 ts->reason = vmx_task_switch_reason(qual);
2184                 ts->ext = 0;
2185                 ts->errcode_valid = 0;
2186                 vmx_paging_info(&ts->paging);
2187                 /*
2188                  * If the task switch was due to a CALL, JMP, IRET, software
2189                  * interrupt (INT n) or software exception (INT3, INTO),
2190                  * then the saved %rip references the instruction that caused
2191                  * the task switch. The instruction length field in the VMCS
2192                  * is valid in this case.
2193                  *
2194                  * In all other cases (e.g., NMI, hardware exception) the
2195                  * saved %rip is one that would have been saved in the old TSS
2196                  * had the task switch completed normally so the instruction
2197                  * length field is not needed in this case and is explicitly
2198                  * set to 0.
2199                  */
2200                 if (ts->reason == TSR_IDT_GATE) {
2201                         KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2202                             ("invalid idtvec_info %#x for IDT task switch",
2203                             idtvec_info));
2204                         intr_type = idtvec_info & VMCS_INTR_T_MASK;
2205                         if (intr_type != VMCS_INTR_T_SWINTR &&
2206                             intr_type != VMCS_INTR_T_SWEXCEPTION &&
2207                             intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2208                                 /* Task switch triggered by external event */
2209                                 ts->ext = 1;
2210                                 vmexit->inst_length = 0;
2211                                 if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2212                                         ts->errcode_valid = 1;
2213                                         ts->errcode = vmcs_idt_vectoring_err();
2214                                 }
2215                         }
2216                 }
2217                 vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2218                 VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2219                     "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2220                     ts->ext ? "external" : "internal",
2221                     ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2222                 break;
2223         case EXIT_REASON_CR_ACCESS:
2224                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2225                 switch (qual & 0xf) {
2226                 case 0:
2227                         handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2228                         break;
2229                 case 4:
2230                         handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2231                         break;
2232                 case 8:
2233                         handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2234                         break;
2235                 }
2236                 break;
2237         case EXIT_REASON_RDMSR:
2238                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2239                 retu = false;
2240                 ecx = vmxctx->guest_rcx;
2241                 VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2242                 error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2243                 if (error) {
2244                         vmexit->exitcode = VM_EXITCODE_RDMSR;
2245                         vmexit->u.msr.code = ecx;
2246                 } else if (!retu) {
2247                         handled = HANDLED;
2248                 } else {
2249                         /* Return to userspace with a valid exitcode */
2250                         KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2251                             ("emulate_rdmsr retu with bogus exitcode"));
2252                 }
2253                 break;
2254         case EXIT_REASON_WRMSR:
2255                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2256                 retu = false;
2257                 eax = vmxctx->guest_rax;
2258                 ecx = vmxctx->guest_rcx;
2259                 edx = vmxctx->guest_rdx;
2260                 VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2261                     ecx, (uint64_t)edx << 32 | eax);
2262                 error = emulate_wrmsr(vmx, vcpu, ecx,
2263                     (uint64_t)edx << 32 | eax, &retu);
2264                 if (error) {
2265                         vmexit->exitcode = VM_EXITCODE_WRMSR;
2266                         vmexit->u.msr.code = ecx;
2267                         vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2268                 } else if (!retu) {
2269                         handled = HANDLED;
2270                 } else {
2271                         /* Return to userspace with a valid exitcode */
2272                         KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2273                             ("emulate_wrmsr retu with bogus exitcode"));
2274                 }
2275                 break;
2276         case EXIT_REASON_HLT:
2277                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2278                 vmexit->exitcode = VM_EXITCODE_HLT;
2279                 vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2280                 break;
2281         case EXIT_REASON_MTF:
2282                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2283                 vmexit->exitcode = VM_EXITCODE_MTRAP;
2284                 vmexit->inst_length = 0;
2285                 break;
2286         case EXIT_REASON_PAUSE:
2287                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2288                 vmexit->exitcode = VM_EXITCODE_PAUSE;
2289                 break;
2290         case EXIT_REASON_INTR_WINDOW:
2291                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2292                 vmx_clear_int_window_exiting(vmx, vcpu);
2293                 return (1);
2294         case EXIT_REASON_EXT_INTR:
2295                 /*
2296                  * External interrupts serve only to cause VM exits and allow
2297                  * the host interrupt handler to run.
2298                  *
2299                  * If this external interrupt triggers a virtual interrupt
2300                  * to a VM, then that state will be recorded by the
2301                  * host interrupt handler in the VM's softc. We will inject
2302                  * this virtual interrupt during the subsequent VM enter.
2303                  */
2304                 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2305
2306                 /*
2307                  * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2308                  * This appears to be a bug in VMware Fusion?
2309                  */
2310                 if (!(intr_info & VMCS_INTR_VALID))
2311                         return (1);
2312                 KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2313                     (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2314                     ("VM exit interruption info invalid: %#x", intr_info));
2315                 vmx_trigger_hostintr(intr_info & 0xff);
2316
2317                 /*
2318                  * This is special. We want to treat this as an 'handled'
2319                  * VM-exit but not increment the instruction pointer.
2320                  */
2321                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2322                 return (1);
2323         case EXIT_REASON_NMI_WINDOW:
2324                 /* Exit to allow the pending virtual NMI to be injected */
2325                 if (vm_nmi_pending(vmx->vm, vcpu))
2326                         vmx_inject_nmi(vmx, vcpu);
2327                 vmx_clear_nmi_window_exiting(vmx, vcpu);
2328                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2329                 return (1);
2330         case EXIT_REASON_INOUT:
2331                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2332                 vmexit->exitcode = VM_EXITCODE_INOUT;
2333                 vmexit->u.inout.bytes = (qual & 0x7) + 1;
2334                 vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2335                 vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2336                 vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2337                 vmexit->u.inout.port = (uint16_t)(qual >> 16);
2338                 vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2339                 if (vmexit->u.inout.string) {
2340                         inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2341                         vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2342                         vis = &vmexit->u.inout_str;
2343                         vmx_paging_info(&vis->paging);
2344                         vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2345                         vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2346                         vis->index = inout_str_index(vmx, vcpu, in);
2347                         vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2348                         vis->addrsize = inout_str_addrsize(inst_info);
2349                         inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2350                 }
2351                 break;
2352         case EXIT_REASON_CPUID:
2353                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2354                 handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2355                 break;
2356         case EXIT_REASON_EXCEPTION:
2357                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2358                 intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2359                 KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2360                     ("VM exit interruption info invalid: %#x", intr_info));
2361
2362                 intr_vec = intr_info & 0xff;
2363                 intr_type = intr_info & VMCS_INTR_T_MASK;
2364
2365                 /*
2366                  * If Virtual NMIs control is 1 and the VM-exit is due to a
2367                  * fault encountered during the execution of IRET then we must
2368                  * restore the state of "virtual-NMI blocking" before resuming
2369                  * the guest.
2370                  *
2371                  * See "Resuming Guest Software after Handling an Exception".
2372                  * See "Information for VM Exits Due to Vectored Events".
2373                  */
2374                 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2375                     (intr_vec != IDT_DF) &&
2376                     (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2377                         vmx_restore_nmi_blocking(vmx, vcpu);
2378
2379                 /*
2380                  * The NMI has already been handled in vmx_exit_handle_nmi().
2381                  */
2382                 if (intr_type == VMCS_INTR_T_NMI)
2383                         return (1);
2384
2385                 /*
2386                  * Call the machine check handler by hand. Also don't reflect
2387                  * the machine check back into the guest.
2388                  */
2389                 if (intr_vec == IDT_MC) {
2390                         VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2391                         __asm __volatile("int $18");
2392                         return (1);
2393                 }
2394
2395                 if (intr_vec == IDT_PF) {
2396                         error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2397                         KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2398                             __func__, error));
2399                 }
2400
2401                 /*
2402                  * Software exceptions exhibit trap-like behavior. This in
2403                  * turn requires populating the VM-entry instruction length
2404                  * so that the %rip in the trap frame is past the INT3/INTO
2405                  * instruction.
2406                  */
2407                 if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2408                         vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2409
2410                 /* Reflect all other exceptions back into the guest */
2411                 errcode_valid = errcode = 0;
2412                 if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2413                         errcode_valid = 1;
2414                         errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2415                 }
2416                 VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2417                     "the guest", intr_vec, errcode);
2418                 error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2419                     errcode_valid, errcode, 0);
2420                 KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2421                     __func__, error));
2422                 return (1);
2423
2424         case EXIT_REASON_EPT_FAULT:
2425                 /*
2426                  * If 'gpa' lies within the address space allocated to
2427                  * memory then this must be a nested page fault otherwise
2428                  * this must be an instruction that accesses MMIO space.
2429                  */
2430                 gpa = vmcs_gpa();
2431                 if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2432                     apic_access_fault(vmx, vcpu, gpa)) {
2433                         vmexit->exitcode = VM_EXITCODE_PAGING;
2434                         vmexit->inst_length = 0;
2435                         vmexit->u.paging.gpa = gpa;
2436                         vmexit->u.paging.fault_type = ept_fault_type(qual);
2437                         vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2438                 } else if (ept_emulation_fault(qual)) {
2439                         vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2440                         vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2441                 }
2442                 /*
2443                  * If Virtual NMIs control is 1 and the VM-exit is due to an
2444                  * EPT fault during the execution of IRET then we must restore
2445                  * the state of "virtual-NMI blocking" before resuming.
2446                  *
2447                  * See description of "NMI unblocking due to IRET" in
2448                  * "Exit Qualification for EPT Violations".
2449                  */
2450                 if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2451                     (qual & EXIT_QUAL_NMIUDTI) != 0)
2452                         vmx_restore_nmi_blocking(vmx, vcpu);
2453                 break;
2454         case EXIT_REASON_VIRTUALIZED_EOI:
2455                 vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2456                 vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2457                 vmexit->inst_length = 0;        /* trap-like */
2458                 break;
2459         case EXIT_REASON_APIC_ACCESS:
2460                 handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2461                 break;
2462         case EXIT_REASON_APIC_WRITE:
2463                 /*
2464                  * APIC-write VM exit is trap-like so the %rip is already
2465                  * pointing to the next instruction.
2466                  */
2467                 vmexit->inst_length = 0;
2468                 vlapic = vm_lapic(vmx->vm, vcpu);
2469                 handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2470                 break;
2471         case EXIT_REASON_XSETBV:
2472                 handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2473                 break;
2474         case EXIT_REASON_MONITOR:
2475                 vmexit->exitcode = VM_EXITCODE_MONITOR;
2476                 break;
2477         case EXIT_REASON_MWAIT:
2478                 vmexit->exitcode = VM_EXITCODE_MWAIT;
2479                 break;
2480         default:
2481                 vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2482                 break;
2483         }
2484
2485         if (handled) {
2486                 /*
2487                  * It is possible that control is returned to userland
2488                  * even though we were able to handle the VM exit in the
2489                  * kernel.
2490                  *
2491                  * In such a case we want to make sure that the userland
2492                  * restarts guest execution at the instruction *after*
2493                  * the one we just processed. Therefore we update the
2494                  * guest rip in the VMCS and in 'vmexit'.
2495                  */
2496                 vmexit->rip += vmexit->inst_length;
2497                 vmexit->inst_length = 0;
2498                 vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2499         } else {
2500                 if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2501                         /*
2502                          * If this VM exit was not claimed by anybody then
2503                          * treat it as a generic VMX exit.
2504                          */
2505                         vmexit->exitcode = VM_EXITCODE_VMX;
2506                         vmexit->u.vmx.status = VM_SUCCESS;
2507                         vmexit->u.vmx.inst_type = 0;
2508                         vmexit->u.vmx.inst_error = 0;
2509                 } else {
2510                         /*
2511                          * The exitcode and collateral have been populated.
2512                          * The VM exit will be processed further in userland.
2513                          */
2514                 }
2515         }
2516         return (handled);
2517 }
2518
2519 static __inline void
2520 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2521 {
2522
2523         KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2524             ("vmx_exit_inst_error: invalid inst_fail_status %d",
2525             vmxctx->inst_fail_status));
2526
2527         vmexit->inst_length = 0;
2528         vmexit->exitcode = VM_EXITCODE_VMX;
2529         vmexit->u.vmx.status = vmxctx->inst_fail_status;
2530         vmexit->u.vmx.inst_error = vmcs_instruction_error();
2531         vmexit->u.vmx.exit_reason = ~0;
2532         vmexit->u.vmx.exit_qualification = ~0;
2533
2534         switch (rc) {
2535         case VMX_VMRESUME_ERROR:
2536         case VMX_VMLAUNCH_ERROR:
2537         case VMX_INVEPT_ERROR:
2538                 vmexit->u.vmx.inst_type = rc;
2539                 break;
2540         default:
2541                 panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2542         }
2543 }
2544
2545 /*
2546  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2547  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2548  * sufficient to simply vector to the NMI handler via a software interrupt.
2549  * However, this must be done before maskable interrupts are enabled
2550  * otherwise the "iret" issued by an interrupt handler will incorrectly
2551  * clear NMI blocking.
2552  */
2553 static __inline void
2554 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2555 {
2556         uint32_t intr_info;
2557
2558         KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2559
2560         if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2561                 return;
2562
2563         intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2564         KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2565             ("VM exit interruption info invalid: %#x", intr_info));
2566
2567         if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2568                 KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2569                     "to NMI has invalid vector: %#x", intr_info));
2570                 VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2571                 __asm __volatile("int $2");
2572         }
2573 }
2574
2575 static int
2576 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2577     struct vm_eventinfo *evinfo)
2578 {
2579         int rc, handled, launched;
2580         struct vmx *vmx;
2581         struct vm *vm;
2582         struct vmxctx *vmxctx;
2583         struct vmcs *vmcs;
2584         struct vm_exit *vmexit;
2585         struct vlapic *vlapic;
2586         uint32_t exit_reason;
2587
2588         vmx = arg;
2589         vm = vmx->vm;
2590         vmcs = &vmx->vmcs[vcpu];
2591         vmxctx = &vmx->ctx[vcpu];
2592         vlapic = vm_lapic(vm, vcpu);
2593         vmexit = vm_exitinfo(vm, vcpu);
2594         launched = 0;
2595
2596         KASSERT(vmxctx->pmap == pmap,
2597             ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2598
2599         vmx_msr_guest_enter(vmx, vcpu);
2600
2601         VMPTRLD(vmcs);
2602
2603         /*
2604          * XXX
2605          * We do this every time because we may setup the virtual machine
2606          * from a different process than the one that actually runs it.
2607          *
2608          * If the life of a virtual machine was spent entirely in the context
2609          * of a single process we could do this once in vmx_vminit().
2610          */
2611         vmcs_write(VMCS_HOST_CR3, rcr3());
2612
2613         vmcs_write(VMCS_GUEST_RIP, rip);
2614         vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2615         do {
2616                 KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2617                     "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2618
2619                 handled = UNHANDLED;
2620                 /*
2621                  * Interrupts are disabled from this point on until the
2622                  * guest starts executing. This is done for the following
2623                  * reasons:
2624                  *
2625                  * If an AST is asserted on this thread after the check below,
2626                  * then the IPI_AST notification will not be lost, because it
2627                  * will cause a VM exit due to external interrupt as soon as
2628                  * the guest state is loaded.
2629                  *
2630                  * A posted interrupt after 'vmx_inject_interrupts()' will
2631                  * not be "lost" because it will be held pending in the host
2632                  * APIC because interrupts are disabled. The pending interrupt
2633                  * will be recognized as soon as the guest state is loaded.
2634                  *
2635                  * The same reasoning applies to the IPI generated by
2636                  * pmap_invalidate_ept().
2637                  */
2638                 disable_intr();
2639                 vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2640
2641                 /*
2642                  * Check for vcpu suspension after injecting events because
2643                  * vmx_inject_interrupts() can suspend the vcpu due to a
2644                  * triple fault.
2645                  */
2646                 if (vcpu_suspended(evinfo)) {
2647                         enable_intr();
2648                         vm_exit_suspended(vmx->vm, vcpu, rip);
2649                         break;
2650                 }
2651
2652                 if (vcpu_rendezvous_pending(evinfo)) {
2653                         enable_intr();
2654                         vm_exit_rendezvous(vmx->vm, vcpu, rip);
2655                         break;
2656                 }
2657
2658                 if (vcpu_reqidle(evinfo)) {
2659                         enable_intr();
2660                         vm_exit_reqidle(vmx->vm, vcpu, rip);
2661                         break;
2662                 }
2663
2664                 if (vcpu_should_yield(vm, vcpu)) {
2665                         enable_intr();
2666                         vm_exit_astpending(vmx->vm, vcpu, rip);
2667                         vmx_astpending_trace(vmx, vcpu, rip);
2668                         handled = HANDLED;
2669                         break;
2670                 }
2671
2672                 vmx_run_trace(vmx, vcpu);
2673                 rc = vmx_enter_guest(vmxctx, vmx, launched);
2674
2675                 /* Collect some information for VM exit processing */
2676                 vmexit->rip = rip = vmcs_guest_rip();
2677                 vmexit->inst_length = vmexit_instruction_length();
2678                 vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2679                 vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2680
2681                 /* Update 'nextrip' */
2682                 vmx->state[vcpu].nextrip = rip;
2683
2684                 if (rc == VMX_GUEST_VMEXIT) {
2685                         vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2686                         enable_intr();
2687                         handled = vmx_exit_process(vmx, vcpu, vmexit);
2688                 } else {
2689                         enable_intr();
2690                         vmx_exit_inst_error(vmxctx, rc, vmexit);
2691                 }
2692                 launched = 1;
2693                 vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2694                 rip = vmexit->rip;
2695         } while (handled);
2696
2697         /*
2698          * If a VM exit has been handled then the exitcode must be BOGUS
2699          * If a VM exit is not handled then the exitcode must not be BOGUS
2700          */
2701         if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2702             (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2703                 panic("Mismatch between handled (%d) and exitcode (%d)",
2704                       handled, vmexit->exitcode);
2705         }
2706
2707         if (!handled)
2708                 vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2709
2710         VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2711             vmexit->exitcode);
2712
2713         VMCLEAR(vmcs);
2714         vmx_msr_guest_exit(vmx, vcpu);
2715
2716         return (0);
2717 }
2718
2719 static void
2720 vmx_vmcleanup(void *arg)
2721 {
2722         int i;
2723         struct vmx *vmx = arg;
2724
2725         if (apic_access_virtualization(vmx, 0))
2726                 vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2727
2728         for (i = 0; i < VM_MAXCPU; i++)
2729                 vpid_free(vmx->state[i].vpid);
2730
2731         free(vmx, M_VMX);
2732
2733         return;
2734 }
2735
2736 static register_t *
2737 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2738 {
2739
2740         switch (reg) {
2741         case VM_REG_GUEST_RAX:
2742                 return (&vmxctx->guest_rax);
2743         case VM_REG_GUEST_RBX:
2744                 return (&vmxctx->guest_rbx);
2745         case VM_REG_GUEST_RCX:
2746                 return (&vmxctx->guest_rcx);
2747         case VM_REG_GUEST_RDX:
2748                 return (&vmxctx->guest_rdx);
2749         case VM_REG_GUEST_RSI:
2750                 return (&vmxctx->guest_rsi);
2751         case VM_REG_GUEST_RDI:
2752                 return (&vmxctx->guest_rdi);
2753         case VM_REG_GUEST_RBP:
2754                 return (&vmxctx->guest_rbp);
2755         case VM_REG_GUEST_R8:
2756                 return (&vmxctx->guest_r8);
2757         case VM_REG_GUEST_R9:
2758                 return (&vmxctx->guest_r9);
2759         case VM_REG_GUEST_R10:
2760                 return (&vmxctx->guest_r10);
2761         case VM_REG_GUEST_R11:
2762                 return (&vmxctx->guest_r11);
2763         case VM_REG_GUEST_R12:
2764                 return (&vmxctx->guest_r12);
2765         case VM_REG_GUEST_R13:
2766                 return (&vmxctx->guest_r13);
2767         case VM_REG_GUEST_R14:
2768                 return (&vmxctx->guest_r14);
2769         case VM_REG_GUEST_R15:
2770                 return (&vmxctx->guest_r15);
2771         case VM_REG_GUEST_CR2:
2772                 return (&vmxctx->guest_cr2);
2773         default:
2774                 break;
2775         }
2776         return (NULL);
2777 }
2778
2779 static int
2780 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2781 {
2782         register_t *regp;
2783
2784         if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2785                 *retval = *regp;
2786                 return (0);
2787         } else
2788                 return (EINVAL);
2789 }
2790
2791 static int
2792 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2793 {
2794         register_t *regp;
2795
2796         if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2797                 *regp = val;
2798                 return (0);
2799         } else
2800                 return (EINVAL);
2801 }
2802
2803 static int
2804 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2805 {
2806         uint64_t gi;
2807         int error;
2808
2809         error = vmcs_getreg(&vmx->vmcs[vcpu], running, 
2810             VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2811         *retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2812         return (error);
2813 }
2814
2815 static int
2816 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2817 {
2818         struct vmcs *vmcs;
2819         uint64_t gi;
2820         int error, ident;
2821
2822         /*
2823          * Forcing the vcpu into an interrupt shadow is not supported.
2824          */
2825         if (val) {
2826                 error = EINVAL;
2827                 goto done;
2828         }
2829
2830         vmcs = &vmx->vmcs[vcpu];
2831         ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2832         error = vmcs_getreg(vmcs, running, ident, &gi);
2833         if (error == 0) {
2834                 gi &= ~HWINTR_BLOCKING;
2835                 error = vmcs_setreg(vmcs, running, ident, gi);
2836         }
2837 done:
2838         VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2839             error ? "failed" : "succeeded");
2840         return (error);
2841 }
2842
2843 static int
2844 vmx_shadow_reg(int reg)
2845 {
2846         int shreg;
2847
2848         shreg = -1;
2849
2850         switch (reg) {
2851         case VM_REG_GUEST_CR0:
2852                 shreg = VMCS_CR0_SHADOW;
2853                 break;
2854         case VM_REG_GUEST_CR4:
2855                 shreg = VMCS_CR4_SHADOW;
2856                 break;
2857         default:
2858                 break;
2859         }
2860
2861         return (shreg);
2862 }
2863
2864 static int
2865 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2866 {
2867         int running, hostcpu;
2868         struct vmx *vmx = arg;
2869
2870         running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2871         if (running && hostcpu != curcpu)
2872                 panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2873
2874         if (reg == VM_REG_GUEST_INTR_SHADOW)
2875                 return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
2876
2877         if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2878                 return (0);
2879
2880         return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2881 }
2882
2883 static int
2884 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2885 {
2886         int error, hostcpu, running, shadow;
2887         uint64_t ctls;
2888         pmap_t pmap;
2889         struct vmx *vmx = arg;
2890
2891         running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2892         if (running && hostcpu != curcpu)
2893                 panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2894
2895         if (reg == VM_REG_GUEST_INTR_SHADOW)
2896                 return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
2897
2898         if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2899                 return (0);
2900
2901         error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2902
2903         if (error == 0) {
2904                 /*
2905                  * If the "load EFER" VM-entry control is 1 then the
2906                  * value of EFER.LMA must be identical to "IA-32e mode guest"
2907                  * bit in the VM-entry control.
2908                  */
2909                 if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2910                     (reg == VM_REG_GUEST_EFER)) {
2911                         vmcs_getreg(&vmx->vmcs[vcpu], running,
2912                                     VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2913                         if (val & EFER_LMA)
2914                                 ctls |= VM_ENTRY_GUEST_LMA;
2915                         else
2916                                 ctls &= ~VM_ENTRY_GUEST_LMA;
2917                         vmcs_setreg(&vmx->vmcs[vcpu], running,
2918                                     VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2919                 }
2920
2921                 shadow = vmx_shadow_reg(reg);
2922                 if (shadow > 0) {
2923                         /*
2924                          * Store the unmodified value in the shadow
2925                          */                     
2926                         error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2927                                     VMCS_IDENT(shadow), val);
2928                 }
2929
2930                 if (reg == VM_REG_GUEST_CR3) {
2931                         /*
2932                          * Invalidate the guest vcpu's TLB mappings to emulate
2933                          * the behavior of updating %cr3.
2934                          *
2935                          * XXX the processor retains global mappings when %cr3
2936                          * is updated but vmx_invvpid() does not.
2937                          */
2938                         pmap = vmx->ctx[vcpu].pmap;
2939                         vmx_invvpid(vmx, vcpu, pmap, running);
2940                 }
2941         }
2942
2943         return (error);
2944 }
2945
2946 static int
2947 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2948 {
2949         int hostcpu, running;
2950         struct vmx *vmx = arg;
2951
2952         running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2953         if (running && hostcpu != curcpu)
2954                 panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2955
2956         return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
2957 }
2958
2959 static int
2960 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2961 {
2962         int hostcpu, running;
2963         struct vmx *vmx = arg;
2964
2965         running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2966         if (running && hostcpu != curcpu)
2967                 panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2968
2969         return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
2970 }
2971
2972 static int
2973 vmx_getcap(void *arg, int vcpu, int type, int *retval)
2974 {
2975         struct vmx *vmx = arg;
2976         int vcap;
2977         int ret;
2978
2979         ret = ENOENT;
2980
2981         vcap = vmx->cap[vcpu].set;
2982
2983         switch (type) {
2984         case VM_CAP_HALT_EXIT:
2985                 if (cap_halt_exit)
2986                         ret = 0;
2987                 break;
2988         case VM_CAP_PAUSE_EXIT:
2989                 if (cap_pause_exit)
2990                         ret = 0;
2991                 break;
2992         case VM_CAP_MTRAP_EXIT:
2993                 if (cap_monitor_trap)
2994                         ret = 0;
2995                 break;
2996         case VM_CAP_UNRESTRICTED_GUEST:
2997                 if (cap_unrestricted_guest)
2998                         ret = 0;
2999                 break;
3000         case VM_CAP_ENABLE_INVPCID:
3001                 if (cap_invpcid)
3002                         ret = 0;
3003                 break;
3004         default:
3005                 break;
3006         }
3007
3008         if (ret == 0)
3009                 *retval = (vcap & (1 << type)) ? 1 : 0;
3010
3011         return (ret);
3012 }
3013
3014 static int
3015 vmx_setcap(void *arg, int vcpu, int type, int val)
3016 {
3017         struct vmx *vmx = arg;
3018         struct vmcs *vmcs = &vmx->vmcs[vcpu];
3019         uint32_t baseval;
3020         uint32_t *pptr;
3021         int error;
3022         int flag;
3023         int reg;
3024         int retval;
3025
3026         retval = ENOENT;
3027         pptr = NULL;
3028
3029         switch (type) {
3030         case VM_CAP_HALT_EXIT:
3031                 if (cap_halt_exit) {
3032                         retval = 0;
3033                         pptr = &vmx->cap[vcpu].proc_ctls;
3034                         baseval = *pptr;
3035                         flag = PROCBASED_HLT_EXITING;
3036                         reg = VMCS_PRI_PROC_BASED_CTLS;
3037                 }
3038                 break;
3039         case VM_CAP_MTRAP_EXIT:
3040                 if (cap_monitor_trap) {
3041                         retval = 0;
3042                         pptr = &vmx->cap[vcpu].proc_ctls;
3043                         baseval = *pptr;
3044                         flag = PROCBASED_MTF;
3045                         reg = VMCS_PRI_PROC_BASED_CTLS;
3046                 }
3047                 break;
3048         case VM_CAP_PAUSE_EXIT:
3049                 if (cap_pause_exit) {
3050                         retval = 0;
3051                         pptr = &vmx->cap[vcpu].proc_ctls;
3052                         baseval = *pptr;
3053                         flag = PROCBASED_PAUSE_EXITING;
3054                         reg = VMCS_PRI_PROC_BASED_CTLS;
3055                 }
3056                 break;
3057         case VM_CAP_UNRESTRICTED_GUEST:
3058                 if (cap_unrestricted_guest) {
3059                         retval = 0;
3060                         pptr = &vmx->cap[vcpu].proc_ctls2;
3061                         baseval = *pptr;
3062                         flag = PROCBASED2_UNRESTRICTED_GUEST;
3063                         reg = VMCS_SEC_PROC_BASED_CTLS;
3064                 }
3065                 break;
3066         case VM_CAP_ENABLE_INVPCID:
3067                 if (cap_invpcid) {
3068                         retval = 0;
3069                         pptr = &vmx->cap[vcpu].proc_ctls2;
3070                         baseval = *pptr;
3071                         flag = PROCBASED2_ENABLE_INVPCID;
3072                         reg = VMCS_SEC_PROC_BASED_CTLS;
3073                 }
3074                 break;
3075         default:
3076                 break;
3077         }
3078
3079         if (retval == 0) {
3080                 if (val) {
3081                         baseval |= flag;
3082                 } else {
3083                         baseval &= ~flag;
3084                 }
3085                 VMPTRLD(vmcs);
3086                 error = vmwrite(reg, baseval);
3087                 VMCLEAR(vmcs);
3088
3089                 if (error) {
3090                         retval = error;
3091                 } else {
3092                         /*
3093                          * Update optional stored flags, and record
3094                          * setting
3095                          */
3096                         if (pptr != NULL) {
3097                                 *pptr = baseval;
3098                         }
3099
3100                         if (val) {
3101                                 vmx->cap[vcpu].set |= (1 << type);
3102                         } else {
3103                                 vmx->cap[vcpu].set &= ~(1 << type);
3104                         }
3105                 }
3106         }
3107
3108         return (retval);
3109 }
3110
3111 struct vlapic_vtx {
3112         struct vlapic   vlapic;
3113         struct pir_desc *pir_desc;
3114         struct vmx      *vmx;
3115 };
3116
3117 #define VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)   \
3118 do {                                                                    \
3119         VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",     \
3120             level ? "level" : "edge", vector);                          \
3121         VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);  \
3122         VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);  \
3123         VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);  \
3124         VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);  \
3125         VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3126 } while (0)
3127
3128 /*
3129  * vlapic->ops handlers that utilize the APICv hardware assist described in
3130  * Chapter 29 of the Intel SDM.
3131  */
3132 static int
3133 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3134 {
3135         struct vlapic_vtx *vlapic_vtx;
3136         struct pir_desc *pir_desc;
3137         uint64_t mask;
3138         int idx, notify;
3139
3140         vlapic_vtx = (struct vlapic_vtx *)vlapic;
3141         pir_desc = vlapic_vtx->pir_desc;
3142
3143         /*
3144          * Keep track of interrupt requests in the PIR descriptor. This is
3145          * because the virtual APIC page pointed to by the VMCS cannot be
3146          * modified if the vcpu is running.
3147          */
3148         idx = vector / 64;
3149         mask = 1UL << (vector % 64);
3150         atomic_set_long(&pir_desc->pir[idx], mask);
3151         notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3152
3153         VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3154             level, "vmx_set_intr_ready");
3155         return (notify);
3156 }
3157
3158 static int
3159 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3160 {
3161         struct vlapic_vtx *vlapic_vtx;
3162         struct pir_desc *pir_desc;
3163         struct LAPIC *lapic;
3164         uint64_t pending, pirval;
3165         uint32_t ppr, vpr;
3166         int i;
3167
3168         /*
3169          * This function is only expected to be called from the 'HLT' exit
3170          * handler which does not care about the vector that is pending.
3171          */
3172         KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3173
3174         vlapic_vtx = (struct vlapic_vtx *)vlapic;
3175         pir_desc = vlapic_vtx->pir_desc;
3176
3177         pending = atomic_load_acq_long(&pir_desc->pending);
3178         if (!pending) {
3179                 /*
3180                  * While a virtual interrupt may have already been
3181                  * processed the actual delivery maybe pending the
3182                  * interruptibility of the guest.  Recognize a pending
3183                  * interrupt by reevaluating virtual interrupts
3184                  * following Section 29.2.1 in the Intel SDM Volume 3.
3185                  */
3186                 uint64_t val;
3187                 uint8_t rvi, ppr;
3188
3189                 vmx_getreg(vlapic_vtx->vmx, vlapic->vcpuid,
3190                     VMCS_IDENT(VMCS_GUEST_INTR_STATUS), &val);
3191                 rvi = val & APIC_TPR_INT;
3192                 lapic = vlapic->apic_page;
3193                 ppr = lapic->ppr & APIC_TPR_INT;
3194                 if (rvi > ppr) {
3195                         return (1);
3196                 }
3197
3198                 return (0);
3199         }
3200
3201         /*
3202          * If there is an interrupt pending then it will be recognized only
3203          * if its priority is greater than the processor priority.
3204          *
3205          * Special case: if the processor priority is zero then any pending
3206          * interrupt will be recognized.
3207          */
3208         lapic = vlapic->apic_page;
3209         ppr = lapic->ppr & APIC_TPR_INT;
3210         if (ppr == 0)
3211                 return (1);
3212
3213         VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3214             lapic->ppr);
3215
3216         for (i = 3; i >= 0; i--) {
3217                 pirval = pir_desc->pir[i];
3218                 if (pirval != 0) {
3219                         vpr = (i * 64 + flsl(pirval) - 1) & APIC_TPR_INT;
3220                         return (vpr > ppr);
3221                 }
3222         }
3223         return (0);
3224 }
3225
3226 static void
3227 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3228 {
3229
3230         panic("vmx_intr_accepted: not expected to be called");
3231 }
3232
3233 static void
3234 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3235 {
3236         struct vlapic_vtx *vlapic_vtx;
3237         struct vmx *vmx;
3238         struct vmcs *vmcs;
3239         uint64_t mask, val;
3240
3241         KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3242         KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3243             ("vmx_set_tmr: vcpu cannot be running"));
3244
3245         vlapic_vtx = (struct vlapic_vtx *)vlapic;
3246         vmx = vlapic_vtx->vmx;
3247         vmcs = &vmx->vmcs[vlapic->vcpuid];
3248         mask = 1UL << (vector % 64);
3249
3250         VMPTRLD(vmcs);
3251         val = vmcs_read(VMCS_EOI_EXIT(vector));
3252         if (level)
3253                 val |= mask;
3254         else
3255                 val &= ~mask;
3256         vmcs_write(VMCS_EOI_EXIT(vector), val);
3257         VMCLEAR(vmcs);
3258 }
3259
3260 static void
3261 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3262 {
3263         struct vmx *vmx;
3264         struct vmcs *vmcs;
3265         uint32_t proc_ctls2;
3266         int vcpuid, error;
3267
3268         vcpuid = vlapic->vcpuid;
3269         vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3270         vmcs = &vmx->vmcs[vcpuid];
3271
3272         proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3273         KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3274             ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3275
3276         proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3277         proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3278         vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3279
3280         VMPTRLD(vmcs);
3281         vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3282         VMCLEAR(vmcs);
3283
3284         if (vlapic->vcpuid == 0) {
3285                 /*
3286                  * The nested page table mappings are shared by all vcpus
3287                  * so unmap the APIC access page just once.
3288                  */
3289                 error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3290                 KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3291                     __func__, error));
3292
3293                 /*
3294                  * The MSR bitmap is shared by all vcpus so modify it only
3295                  * once in the context of vcpu 0.
3296                  */
3297                 error = vmx_allow_x2apic_msrs(vmx);
3298                 KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3299                     __func__, error));
3300         }
3301 }
3302
3303 static void
3304 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3305 {
3306
3307         ipi_cpu(hostcpu, pirvec);
3308 }
3309
3310 /*
3311  * Transfer the pending interrupts in the PIR descriptor to the IRR
3312  * in the virtual APIC page.
3313  */
3314 static void
3315 vmx_inject_pir(struct vlapic *vlapic)
3316 {
3317         struct vlapic_vtx *vlapic_vtx;
3318         struct pir_desc *pir_desc;
3319         struct LAPIC *lapic;
3320         uint64_t val, pirval;
3321         int rvi, pirbase = -1;
3322         uint16_t intr_status_old, intr_status_new;
3323
3324         vlapic_vtx = (struct vlapic_vtx *)vlapic;
3325         pir_desc = vlapic_vtx->pir_desc;
3326         if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3327                 VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3328                     "no posted interrupt pending");
3329                 return;
3330         }
3331
3332         pirval = 0;
3333         pirbase = -1;
3334         lapic = vlapic->apic_page;
3335
3336         val = atomic_readandclear_long(&pir_desc->pir[0]);
3337         if (val != 0) {
3338                 lapic->irr0 |= val;
3339                 lapic->irr1 |= val >> 32;
3340                 pirbase = 0;
3341                 pirval = val;
3342         }
3343
3344         val = atomic_readandclear_long(&pir_desc->pir[1]);
3345         if (val != 0) {
3346                 lapic->irr2 |= val;
3347                 lapic->irr3 |= val >> 32;
3348                 pirbase = 64;
3349                 pirval = val;
3350         }
3351
3352         val = atomic_readandclear_long(&pir_desc->pir[2]);
3353         if (val != 0) {
3354                 lapic->irr4 |= val;
3355                 lapic->irr5 |= val >> 32;
3356                 pirbase = 128;
3357                 pirval = val;
3358         }
3359
3360         val = atomic_readandclear_long(&pir_desc->pir[3]);
3361         if (val != 0) {
3362                 lapic->irr6 |= val;
3363                 lapic->irr7 |= val >> 32;
3364                 pirbase = 192;
3365                 pirval = val;
3366         }
3367
3368         VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3369
3370         /*
3371          * Update RVI so the processor can evaluate pending virtual
3372          * interrupts on VM-entry.
3373          *
3374          * It is possible for pirval to be 0 here, even though the
3375          * pending bit has been set. The scenario is:
3376          * CPU-Y is sending a posted interrupt to CPU-X, which
3377          * is running a guest and processing posted interrupts in h/w.
3378          * CPU-X will eventually exit and the state seen in s/w is
3379          * the pending bit set, but no PIR bits set.
3380          *
3381          *      CPU-X                      CPU-Y
3382          *   (vm running)                (host running)
3383          *   rx posted interrupt
3384          *   CLEAR pending bit
3385          *                               SET PIR bit
3386          *   READ/CLEAR PIR bits
3387          *                               SET pending bit
3388          *   (vm exit)
3389          *   pending bit set, PIR 0
3390          */
3391         if (pirval != 0) {
3392                 rvi = pirbase + flsl(pirval) - 1;
3393                 intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3394                 intr_status_new = (intr_status_old & 0xFF00) | rvi;
3395                 if (intr_status_new > intr_status_old) {
3396                         vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3397                         VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3398                             "guest_intr_status changed from 0x%04x to 0x%04x",
3399                             intr_status_old, intr_status_new);
3400                 }
3401         }
3402 }
3403
3404 static struct vlapic *
3405 vmx_vlapic_init(void *arg, int vcpuid)
3406 {
3407         struct vmx *vmx;
3408         struct vlapic *vlapic;
3409         struct vlapic_vtx *vlapic_vtx;
3410         
3411         vmx = arg;
3412
3413         vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3414         vlapic->vm = vmx->vm;
3415         vlapic->vcpuid = vcpuid;
3416         vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3417
3418         vlapic_vtx = (struct vlapic_vtx *)vlapic;
3419         vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3420         vlapic_vtx->vmx = vmx;
3421
3422         if (virtual_interrupt_delivery) {
3423                 vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3424                 vlapic->ops.pending_intr = vmx_pending_intr;
3425                 vlapic->ops.intr_accepted = vmx_intr_accepted;
3426                 vlapic->ops.set_tmr = vmx_set_tmr;
3427                 vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3428         }
3429
3430         if (posted_interrupts)
3431                 vlapic->ops.post_intr = vmx_post_intr;
3432
3433         vlapic_init(vlapic);
3434
3435         return (vlapic);
3436 }
3437
3438 static void
3439 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3440 {
3441
3442         vlapic_cleanup(vlapic);
3443         free(vlapic, M_VLAPIC);
3444 }
3445
3446 struct vmm_ops vmm_ops_intel = {
3447         vmx_init,
3448         vmx_cleanup,
3449         vmx_restore,
3450         vmx_vminit,
3451         vmx_run,
3452         vmx_vmcleanup,
3453         vmx_getreg,
3454         vmx_setreg,
3455         vmx_getdesc,
3456         vmx_setdesc,
3457         vmx_getcap,
3458         vmx_setcap,
3459         ept_vmspace_alloc,
3460         ept_vmspace_free,
3461         vmx_vlapic_init,
3462         vmx_vlapic_cleanup,
3463 };