KVM: VMX: Drop bits 31:16 when shoving exception error code into VMCS
[linux-2.6-block.git] / arch / x86 / kvm / vmx / vmx.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * This module enables machines with Intel VT-x extensions to run virtual
6  * machines without emulation or binary translation.
7  *
8  * Copyright (C) 2006 Qumranet, Inc.
9  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10  *
11  * Authors:
12  *   Avi Kivity   <avi@qumranet.com>
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  */
15
16 #include <linux/highmem.h>
17 #include <linux/hrtimer.h>
18 #include <linux/kernel.h>
19 #include <linux/kvm_host.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/mod_devicetable.h>
23 #include <linux/mm.h>
24 #include <linux/objtool.h>
25 #include <linux/sched.h>
26 #include <linux/sched/smt.h>
27 #include <linux/slab.h>
28 #include <linux/tboot.h>
29 #include <linux/trace_events.h>
30 #include <linux/entry-kvm.h>
31
32 #include <asm/apic.h>
33 #include <asm/asm.h>
34 #include <asm/cpu.h>
35 #include <asm/cpu_device_id.h>
36 #include <asm/debugreg.h>
37 #include <asm/desc.h>
38 #include <asm/fpu/api.h>
39 #include <asm/fpu/xstate.h>
40 #include <asm/idtentry.h>
41 #include <asm/io.h>
42 #include <asm/irq_remapping.h>
43 #include <asm/kexec.h>
44 #include <asm/perf_event.h>
45 #include <asm/mmu_context.h>
46 #include <asm/mshyperv.h>
47 #include <asm/mwait.h>
48 #include <asm/spec-ctrl.h>
49 #include <asm/virtext.h>
50 #include <asm/vmx.h>
51
52 #include "capabilities.h"
53 #include "cpuid.h"
54 #include "evmcs.h"
55 #include "hyperv.h"
56 #include "kvm_onhyperv.h"
57 #include "irq.h"
58 #include "kvm_cache_regs.h"
59 #include "lapic.h"
60 #include "mmu.h"
61 #include "nested.h"
62 #include "pmu.h"
63 #include "sgx.h"
64 #include "trace.h"
65 #include "vmcs.h"
66 #include "vmcs12.h"
67 #include "vmx.h"
68 #include "x86.h"
69
70 MODULE_AUTHOR("Qumranet");
71 MODULE_LICENSE("GPL");
72
73 #ifdef MODULE
74 static const struct x86_cpu_id vmx_cpu_id[] = {
75         X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
76         {}
77 };
78 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
79 #endif
80
81 bool __read_mostly enable_vpid = 1;
82 module_param_named(vpid, enable_vpid, bool, 0444);
83
84 static bool __read_mostly enable_vnmi = 1;
85 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
86
87 bool __read_mostly flexpriority_enabled = 1;
88 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
89
90 bool __read_mostly enable_ept = 1;
91 module_param_named(ept, enable_ept, bool, S_IRUGO);
92
93 bool __read_mostly enable_unrestricted_guest = 1;
94 module_param_named(unrestricted_guest,
95                         enable_unrestricted_guest, bool, S_IRUGO);
96
97 bool __read_mostly enable_ept_ad_bits = 1;
98 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
99
100 static bool __read_mostly emulate_invalid_guest_state = true;
101 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
102
103 static bool __read_mostly fasteoi = 1;
104 module_param(fasteoi, bool, S_IRUGO);
105
106 module_param(enable_apicv, bool, S_IRUGO);
107
108 bool __read_mostly enable_ipiv = true;
109 module_param(enable_ipiv, bool, 0444);
110
111 /*
112  * If nested=1, nested virtualization is supported, i.e., guests may use
113  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
114  * use VMX instructions.
115  */
116 static bool __read_mostly nested = 1;
117 module_param(nested, bool, S_IRUGO);
118
119 bool __read_mostly enable_pml = 1;
120 module_param_named(pml, enable_pml, bool, S_IRUGO);
121
122 static bool __read_mostly error_on_inconsistent_vmcs_config = true;
123 module_param(error_on_inconsistent_vmcs_config, bool, 0444);
124
125 static bool __read_mostly dump_invalid_vmcs = 0;
126 module_param(dump_invalid_vmcs, bool, 0644);
127
128 #define MSR_BITMAP_MODE_X2APIC          1
129 #define MSR_BITMAP_MODE_X2APIC_APICV    2
130
131 #define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
132
133 /* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
134 static int __read_mostly cpu_preemption_timer_multi;
135 static bool __read_mostly enable_preemption_timer = 1;
136 #ifdef CONFIG_X86_64
137 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
138 #endif
139
140 extern bool __read_mostly allow_smaller_maxphyaddr;
141 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
142
143 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
144 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
145 #define KVM_VM_CR0_ALWAYS_ON                            \
146         (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
147
148 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
149 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
150 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
151
152 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
153
154 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
155         RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
156         RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
157         RTIT_STATUS_BYTECNT))
158
159 /*
160  * List of MSRs that can be directly passed to the guest.
161  * In addition to these x2apic and PT MSRs are handled specially.
162  */
163 static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
164         MSR_IA32_SPEC_CTRL,
165         MSR_IA32_PRED_CMD,
166         MSR_IA32_TSC,
167 #ifdef CONFIG_X86_64
168         MSR_FS_BASE,
169         MSR_GS_BASE,
170         MSR_KERNEL_GS_BASE,
171         MSR_IA32_XFD,
172         MSR_IA32_XFD_ERR,
173 #endif
174         MSR_IA32_SYSENTER_CS,
175         MSR_IA32_SYSENTER_ESP,
176         MSR_IA32_SYSENTER_EIP,
177         MSR_CORE_C1_RES,
178         MSR_CORE_C3_RESIDENCY,
179         MSR_CORE_C6_RESIDENCY,
180         MSR_CORE_C7_RESIDENCY,
181 };
182
183 /*
184  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
185  * ple_gap:    upper bound on the amount of time between two successive
186  *             executions of PAUSE in a loop. Also indicate if ple enabled.
187  *             According to test, this time is usually smaller than 128 cycles.
188  * ple_window: upper bound on the amount of time a guest is allowed to execute
189  *             in a PAUSE loop. Tests indicate that most spinlocks are held for
190  *             less than 2^12 cycles
191  * Time is measured based on a counter that runs at the same rate as the TSC,
192  * refer SDM volume 3b section 21.6.13 & 22.1.3.
193  */
194 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
195 module_param(ple_gap, uint, 0444);
196
197 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
198 module_param(ple_window, uint, 0444);
199
200 /* Default doubles per-vcpu window every exit. */
201 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
202 module_param(ple_window_grow, uint, 0444);
203
204 /* Default resets per-vcpu window every exit to ple_window. */
205 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
206 module_param(ple_window_shrink, uint, 0444);
207
208 /* Default is to compute the maximum so we can never overflow. */
209 static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
210 module_param(ple_window_max, uint, 0444);
211
212 /* Default is SYSTEM mode, 1 for host-guest mode */
213 int __read_mostly pt_mode = PT_MODE_SYSTEM;
214 module_param(pt_mode, int, S_IRUGO);
215
216 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
217 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
218 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
219
220 /* Storage for pre module init parameter parsing */
221 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
222
223 static const struct {
224         const char *option;
225         bool for_parse;
226 } vmentry_l1d_param[] = {
227         [VMENTER_L1D_FLUSH_AUTO]         = {"auto", true},
228         [VMENTER_L1D_FLUSH_NEVER]        = {"never", true},
229         [VMENTER_L1D_FLUSH_COND]         = {"cond", true},
230         [VMENTER_L1D_FLUSH_ALWAYS]       = {"always", true},
231         [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
232         [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
233 };
234
235 #define L1D_CACHE_ORDER 4
236 static void *vmx_l1d_flush_pages;
237
238 /* Control for disabling CPU Fill buffer clear */
239 static bool __read_mostly vmx_fb_clear_ctrl_available;
240
241 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
242 {
243         struct page *page;
244         unsigned int i;
245
246         if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
247                 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
248                 return 0;
249         }
250
251         if (!enable_ept) {
252                 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
253                 return 0;
254         }
255
256         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
257                 u64 msr;
258
259                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
260                 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
261                         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
262                         return 0;
263                 }
264         }
265
266         /* If set to auto use the default l1tf mitigation method */
267         if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
268                 switch (l1tf_mitigation) {
269                 case L1TF_MITIGATION_OFF:
270                         l1tf = VMENTER_L1D_FLUSH_NEVER;
271                         break;
272                 case L1TF_MITIGATION_FLUSH_NOWARN:
273                 case L1TF_MITIGATION_FLUSH:
274                 case L1TF_MITIGATION_FLUSH_NOSMT:
275                         l1tf = VMENTER_L1D_FLUSH_COND;
276                         break;
277                 case L1TF_MITIGATION_FULL:
278                 case L1TF_MITIGATION_FULL_FORCE:
279                         l1tf = VMENTER_L1D_FLUSH_ALWAYS;
280                         break;
281                 }
282         } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
283                 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
284         }
285
286         if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
287             !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
288                 /*
289                  * This allocation for vmx_l1d_flush_pages is not tied to a VM
290                  * lifetime and so should not be charged to a memcg.
291                  */
292                 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
293                 if (!page)
294                         return -ENOMEM;
295                 vmx_l1d_flush_pages = page_address(page);
296
297                 /*
298                  * Initialize each page with a different pattern in
299                  * order to protect against KSM in the nested
300                  * virtualization case.
301                  */
302                 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
303                         memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
304                                PAGE_SIZE);
305                 }
306         }
307
308         l1tf_vmx_mitigation = l1tf;
309
310         if (l1tf != VMENTER_L1D_FLUSH_NEVER)
311                 static_branch_enable(&vmx_l1d_should_flush);
312         else
313                 static_branch_disable(&vmx_l1d_should_flush);
314
315         if (l1tf == VMENTER_L1D_FLUSH_COND)
316                 static_branch_enable(&vmx_l1d_flush_cond);
317         else
318                 static_branch_disable(&vmx_l1d_flush_cond);
319         return 0;
320 }
321
322 static int vmentry_l1d_flush_parse(const char *s)
323 {
324         unsigned int i;
325
326         if (s) {
327                 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
328                         if (vmentry_l1d_param[i].for_parse &&
329                             sysfs_streq(s, vmentry_l1d_param[i].option))
330                                 return i;
331                 }
332         }
333         return -EINVAL;
334 }
335
336 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
337 {
338         int l1tf, ret;
339
340         l1tf = vmentry_l1d_flush_parse(s);
341         if (l1tf < 0)
342                 return l1tf;
343
344         if (!boot_cpu_has(X86_BUG_L1TF))
345                 return 0;
346
347         /*
348          * Has vmx_init() run already? If not then this is the pre init
349          * parameter parsing. In that case just store the value and let
350          * vmx_init() do the proper setup after enable_ept has been
351          * established.
352          */
353         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
354                 vmentry_l1d_flush_param = l1tf;
355                 return 0;
356         }
357
358         mutex_lock(&vmx_l1d_flush_mutex);
359         ret = vmx_setup_l1d_flush(l1tf);
360         mutex_unlock(&vmx_l1d_flush_mutex);
361         return ret;
362 }
363
364 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
365 {
366         if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
367                 return sprintf(s, "???\n");
368
369         return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
370 }
371
372 static void vmx_setup_fb_clear_ctrl(void)
373 {
374         u64 msr;
375
376         if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES) &&
377             !boot_cpu_has_bug(X86_BUG_MDS) &&
378             !boot_cpu_has_bug(X86_BUG_TAA)) {
379                 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
380                 if (msr & ARCH_CAP_FB_CLEAR_CTRL)
381                         vmx_fb_clear_ctrl_available = true;
382         }
383 }
384
385 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx)
386 {
387         u64 msr;
388
389         if (!vmx->disable_fb_clear)
390                 return;
391
392         msr = __rdmsr(MSR_IA32_MCU_OPT_CTRL);
393         msr |= FB_CLEAR_DIS;
394         native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, msr);
395         /* Cache the MSR value to avoid reading it later */
396         vmx->msr_ia32_mcu_opt_ctrl = msr;
397 }
398
399 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx)
400 {
401         if (!vmx->disable_fb_clear)
402                 return;
403
404         vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS;
405         native_wrmsrl(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl);
406 }
407
408 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx)
409 {
410         vmx->disable_fb_clear = vmx_fb_clear_ctrl_available;
411
412         /*
413          * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS
414          * at VMEntry. Skip the MSR read/write when a guest has no use case to
415          * execute VERW.
416          */
417         if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) ||
418            ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) &&
419             (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) &&
420             (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) &&
421             (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) &&
422             (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO)))
423                 vmx->disable_fb_clear = false;
424 }
425
426 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
427         .set = vmentry_l1d_flush_set,
428         .get = vmentry_l1d_flush_get,
429 };
430 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
431
432 static u32 vmx_segment_access_rights(struct kvm_segment *var);
433
434 void vmx_vmexit(void);
435
436 #define vmx_insn_failed(fmt...)         \
437 do {                                    \
438         WARN_ONCE(1, fmt);              \
439         pr_warn_ratelimited(fmt);       \
440 } while (0)
441
442 void vmread_error(unsigned long field, bool fault)
443 {
444         if (fault)
445                 kvm_spurious_fault();
446         else
447                 vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
448 }
449
450 noinline void vmwrite_error(unsigned long field, unsigned long value)
451 {
452         vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%u\n",
453                         field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
454 }
455
456 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
457 {
458         vmx_insn_failed("kvm: vmclear failed: %p/%llx err=%u\n",
459                         vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
460 }
461
462 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
463 {
464         vmx_insn_failed("kvm: vmptrld failed: %p/%llx err=%u\n",
465                         vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR));
466 }
467
468 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
469 {
470         vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
471                         ext, vpid, gva);
472 }
473
474 noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
475 {
476         vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
477                         ext, eptp, gpa);
478 }
479
480 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
481 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
482 /*
483  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
484  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
485  */
486 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
487
488 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
489 static DEFINE_SPINLOCK(vmx_vpid_lock);
490
491 struct vmcs_config vmcs_config;
492 struct vmx_capability vmx_capability;
493
494 #define VMX_SEGMENT_FIELD(seg)                                  \
495         [VCPU_SREG_##seg] = {                                   \
496                 .selector = GUEST_##seg##_SELECTOR,             \
497                 .base = GUEST_##seg##_BASE,                     \
498                 .limit = GUEST_##seg##_LIMIT,                   \
499                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
500         }
501
502 static const struct kvm_vmx_segment_field {
503         unsigned selector;
504         unsigned base;
505         unsigned limit;
506         unsigned ar_bytes;
507 } kvm_vmx_segment_fields[] = {
508         VMX_SEGMENT_FIELD(CS),
509         VMX_SEGMENT_FIELD(DS),
510         VMX_SEGMENT_FIELD(ES),
511         VMX_SEGMENT_FIELD(FS),
512         VMX_SEGMENT_FIELD(GS),
513         VMX_SEGMENT_FIELD(SS),
514         VMX_SEGMENT_FIELD(TR),
515         VMX_SEGMENT_FIELD(LDTR),
516 };
517
518 static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
519 {
520         vmx->segment_cache.bitmask = 0;
521 }
522
523 static unsigned long host_idt_base;
524
525 #if IS_ENABLED(CONFIG_HYPERV)
526 static bool __read_mostly enlightened_vmcs = true;
527 module_param(enlightened_vmcs, bool, 0444);
528
529 static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
530 {
531         struct hv_enlightened_vmcs *evmcs;
532         struct hv_partition_assist_pg **p_hv_pa_pg =
533                         &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
534         /*
535          * Synthetic VM-Exit is not enabled in current code and so All
536          * evmcs in singe VM shares same assist page.
537          */
538         if (!*p_hv_pa_pg)
539                 *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
540
541         if (!*p_hv_pa_pg)
542                 return -ENOMEM;
543
544         evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
545
546         evmcs->partition_assist_page =
547                 __pa(*p_hv_pa_pg);
548         evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
549         evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
550
551         return 0;
552 }
553
554 #endif /* IS_ENABLED(CONFIG_HYPERV) */
555
556 /*
557  * Comment's format: document - errata name - stepping - processor name.
558  * Refer from
559  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
560  */
561 static u32 vmx_preemption_cpu_tfms[] = {
562 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
563 0x000206E6,
564 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
565 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
566 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
567 0x00020652,
568 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
569 0x00020655,
570 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
571 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
572 /*
573  * 320767.pdf - AAP86  - B1 -
574  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
575  */
576 0x000106E5,
577 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
578 0x000106A0,
579 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
580 0x000106A1,
581 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
582 0x000106A4,
583  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
584  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
585  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
586 0x000106A5,
587  /* Xeon E3-1220 V2 */
588 0x000306A8,
589 };
590
591 static inline bool cpu_has_broken_vmx_preemption_timer(void)
592 {
593         u32 eax = cpuid_eax(0x00000001), i;
594
595         /* Clear the reserved bits */
596         eax &= ~(0x3U << 14 | 0xfU << 28);
597         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
598                 if (eax == vmx_preemption_cpu_tfms[i])
599                         return true;
600
601         return false;
602 }
603
604 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
605 {
606         return flexpriority_enabled && lapic_in_kernel(vcpu);
607 }
608
609 static int possible_passthrough_msr_slot(u32 msr)
610 {
611         u32 i;
612
613         for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
614                 if (vmx_possible_passthrough_msrs[i] == msr)
615                         return i;
616
617         return -ENOENT;
618 }
619
620 static bool is_valid_passthrough_msr(u32 msr)
621 {
622         bool r;
623
624         switch (msr) {
625         case 0x800 ... 0x8ff:
626                 /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
627                 return true;
628         case MSR_IA32_RTIT_STATUS:
629         case MSR_IA32_RTIT_OUTPUT_BASE:
630         case MSR_IA32_RTIT_OUTPUT_MASK:
631         case MSR_IA32_RTIT_CR3_MATCH:
632         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
633                 /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
634         case MSR_LBR_SELECT:
635         case MSR_LBR_TOS:
636         case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
637         case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
638         case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
639         case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
640         case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
641                 /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
642                 return true;
643         }
644
645         r = possible_passthrough_msr_slot(msr) != -ENOENT;
646
647         WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
648
649         return r;
650 }
651
652 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
653 {
654         int i;
655
656         i = kvm_find_user_return_msr(msr);
657         if (i >= 0)
658                 return &vmx->guest_uret_msrs[i];
659         return NULL;
660 }
661
662 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
663                                   struct vmx_uret_msr *msr, u64 data)
664 {
665         unsigned int slot = msr - vmx->guest_uret_msrs;
666         int ret = 0;
667
668         if (msr->load_into_hardware) {
669                 preempt_disable();
670                 ret = kvm_set_user_return_msr(slot, data, msr->mask);
671                 preempt_enable();
672         }
673         if (!ret)
674                 msr->data = data;
675         return ret;
676 }
677
678 #ifdef CONFIG_KEXEC_CORE
679 static void crash_vmclear_local_loaded_vmcss(void)
680 {
681         int cpu = raw_smp_processor_id();
682         struct loaded_vmcs *v;
683
684         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
685                             loaded_vmcss_on_cpu_link)
686                 vmcs_clear(v->vmcs);
687 }
688 #endif /* CONFIG_KEXEC_CORE */
689
690 static void __loaded_vmcs_clear(void *arg)
691 {
692         struct loaded_vmcs *loaded_vmcs = arg;
693         int cpu = raw_smp_processor_id();
694
695         if (loaded_vmcs->cpu != cpu)
696                 return; /* vcpu migration can race with cpu offline */
697         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
698                 per_cpu(current_vmcs, cpu) = NULL;
699
700         vmcs_clear(loaded_vmcs->vmcs);
701         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
702                 vmcs_clear(loaded_vmcs->shadow_vmcs);
703
704         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
705
706         /*
707          * Ensure all writes to loaded_vmcs, including deleting it from its
708          * current percpu list, complete before setting loaded_vmcs->cpu to
709          * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first
710          * and add loaded_vmcs to its percpu list before it's deleted from this
711          * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
712          */
713         smp_wmb();
714
715         loaded_vmcs->cpu = -1;
716         loaded_vmcs->launched = 0;
717 }
718
719 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
720 {
721         int cpu = loaded_vmcs->cpu;
722
723         if (cpu != -1)
724                 smp_call_function_single(cpu,
725                          __loaded_vmcs_clear, loaded_vmcs, 1);
726 }
727
728 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
729                                        unsigned field)
730 {
731         bool ret;
732         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
733
734         if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
735                 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
736                 vmx->segment_cache.bitmask = 0;
737         }
738         ret = vmx->segment_cache.bitmask & mask;
739         vmx->segment_cache.bitmask |= mask;
740         return ret;
741 }
742
743 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
744 {
745         u16 *p = &vmx->segment_cache.seg[seg].selector;
746
747         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
748                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
749         return *p;
750 }
751
752 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
753 {
754         ulong *p = &vmx->segment_cache.seg[seg].base;
755
756         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
757                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
758         return *p;
759 }
760
761 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
762 {
763         u32 *p = &vmx->segment_cache.seg[seg].limit;
764
765         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
766                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
767         return *p;
768 }
769
770 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
771 {
772         u32 *p = &vmx->segment_cache.seg[seg].ar;
773
774         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
775                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
776         return *p;
777 }
778
779 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
780 {
781         u32 eb;
782
783         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
784              (1u << DB_VECTOR) | (1u << AC_VECTOR);
785         /*
786          * Guest access to VMware backdoor ports could legitimately
787          * trigger #GP because of TSS I/O permission bitmap.
788          * We intercept those #GP and allow access to them anyway
789          * as VMware does.
790          */
791         if (enable_vmware_backdoor)
792                 eb |= (1u << GP_VECTOR);
793         if ((vcpu->guest_debug &
794              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
795             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
796                 eb |= 1u << BP_VECTOR;
797         if (to_vmx(vcpu)->rmode.vm86_active)
798                 eb = ~0;
799         if (!vmx_need_pf_intercept(vcpu))
800                 eb &= ~(1u << PF_VECTOR);
801
802         /* When we are running a nested L2 guest and L1 specified for it a
803          * certain exception bitmap, we must trap the same exceptions and pass
804          * them to L1. When running L2, we will only handle the exceptions
805          * specified above if L1 did not want them.
806          */
807         if (is_guest_mode(vcpu))
808                 eb |= get_vmcs12(vcpu)->exception_bitmap;
809         else {
810                 int mask = 0, match = 0;
811
812                 if (enable_ept && (eb & (1u << PF_VECTOR))) {
813                         /*
814                          * If EPT is enabled, #PF is currently only intercepted
815                          * if MAXPHYADDR is smaller on the guest than on the
816                          * host.  In that case we only care about present,
817                          * non-reserved faults.  For vmcs02, however, PFEC_MASK
818                          * and PFEC_MATCH are set in prepare_vmcs02_rare.
819                          */
820                         mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
821                         match = PFERR_PRESENT_MASK;
822                 }
823                 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
824                 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
825         }
826
827         /*
828          * Disabling xfd interception indicates that dynamic xfeatures
829          * might be used in the guest. Always trap #NM in this case
830          * to save guest xfd_err timely.
831          */
832         if (vcpu->arch.xfd_no_write_intercept)
833                 eb |= (1u << NM_VECTOR);
834
835         vmcs_write32(EXCEPTION_BITMAP, eb);
836 }
837
838 /*
839  * Check if MSR is intercepted for currently loaded MSR bitmap.
840  */
841 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr)
842 {
843         if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS))
844                 return true;
845
846         return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr);
847 }
848
849 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx)
850 {
851         unsigned int flags = 0;
852
853         if (vmx->loaded_vmcs->launched)
854                 flags |= VMX_RUN_VMRESUME;
855
856         /*
857          * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free
858          * to change it directly without causing a vmexit.  In that case read
859          * it after vmexit and store it in vmx->spec_ctrl.
860          */
861         if (unlikely(!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)))
862                 flags |= VMX_RUN_SAVE_SPEC_CTRL;
863
864         return flags;
865 }
866
867 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
868                 unsigned long entry, unsigned long exit)
869 {
870         vm_entry_controls_clearbit(vmx, entry);
871         vm_exit_controls_clearbit(vmx, exit);
872 }
873
874 int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
875 {
876         unsigned int i;
877
878         for (i = 0; i < m->nr; ++i) {
879                 if (m->val[i].index == msr)
880                         return i;
881         }
882         return -ENOENT;
883 }
884
885 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
886 {
887         int i;
888         struct msr_autoload *m = &vmx->msr_autoload;
889
890         switch (msr) {
891         case MSR_EFER:
892                 if (cpu_has_load_ia32_efer()) {
893                         clear_atomic_switch_msr_special(vmx,
894                                         VM_ENTRY_LOAD_IA32_EFER,
895                                         VM_EXIT_LOAD_IA32_EFER);
896                         return;
897                 }
898                 break;
899         case MSR_CORE_PERF_GLOBAL_CTRL:
900                 if (cpu_has_load_perf_global_ctrl()) {
901                         clear_atomic_switch_msr_special(vmx,
902                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
903                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
904                         return;
905                 }
906                 break;
907         }
908         i = vmx_find_loadstore_msr_slot(&m->guest, msr);
909         if (i < 0)
910                 goto skip_guest;
911         --m->guest.nr;
912         m->guest.val[i] = m->guest.val[m->guest.nr];
913         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
914
915 skip_guest:
916         i = vmx_find_loadstore_msr_slot(&m->host, msr);
917         if (i < 0)
918                 return;
919
920         --m->host.nr;
921         m->host.val[i] = m->host.val[m->host.nr];
922         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
923 }
924
925 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
926                 unsigned long entry, unsigned long exit,
927                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
928                 u64 guest_val, u64 host_val)
929 {
930         vmcs_write64(guest_val_vmcs, guest_val);
931         if (host_val_vmcs != HOST_IA32_EFER)
932                 vmcs_write64(host_val_vmcs, host_val);
933         vm_entry_controls_setbit(vmx, entry);
934         vm_exit_controls_setbit(vmx, exit);
935 }
936
937 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
938                                   u64 guest_val, u64 host_val, bool entry_only)
939 {
940         int i, j = 0;
941         struct msr_autoload *m = &vmx->msr_autoload;
942
943         switch (msr) {
944         case MSR_EFER:
945                 if (cpu_has_load_ia32_efer()) {
946                         add_atomic_switch_msr_special(vmx,
947                                         VM_ENTRY_LOAD_IA32_EFER,
948                                         VM_EXIT_LOAD_IA32_EFER,
949                                         GUEST_IA32_EFER,
950                                         HOST_IA32_EFER,
951                                         guest_val, host_val);
952                         return;
953                 }
954                 break;
955         case MSR_CORE_PERF_GLOBAL_CTRL:
956                 if (cpu_has_load_perf_global_ctrl()) {
957                         add_atomic_switch_msr_special(vmx,
958                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
959                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
960                                         GUEST_IA32_PERF_GLOBAL_CTRL,
961                                         HOST_IA32_PERF_GLOBAL_CTRL,
962                                         guest_val, host_val);
963                         return;
964                 }
965                 break;
966         case MSR_IA32_PEBS_ENABLE:
967                 /* PEBS needs a quiescent period after being disabled (to write
968                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
969                  * provide that period, so a CPU could write host's record into
970                  * guest's memory.
971                  */
972                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
973         }
974
975         i = vmx_find_loadstore_msr_slot(&m->guest, msr);
976         if (!entry_only)
977                 j = vmx_find_loadstore_msr_slot(&m->host, msr);
978
979         if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
980             (j < 0 &&  m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
981                 printk_once(KERN_WARNING "Not enough msr switch entries. "
982                                 "Can't add msr %x\n", msr);
983                 return;
984         }
985         if (i < 0) {
986                 i = m->guest.nr++;
987                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
988         }
989         m->guest.val[i].index = msr;
990         m->guest.val[i].value = guest_val;
991
992         if (entry_only)
993                 return;
994
995         if (j < 0) {
996                 j = m->host.nr++;
997                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
998         }
999         m->host.val[j].index = msr;
1000         m->host.val[j].value = host_val;
1001 }
1002
1003 static bool update_transition_efer(struct vcpu_vmx *vmx)
1004 {
1005         u64 guest_efer = vmx->vcpu.arch.efer;
1006         u64 ignore_bits = 0;
1007         int i;
1008
1009         /* Shadow paging assumes NX to be available.  */
1010         if (!enable_ept)
1011                 guest_efer |= EFER_NX;
1012
1013         /*
1014          * LMA and LME handled by hardware; SCE meaningless outside long mode.
1015          */
1016         ignore_bits |= EFER_SCE;
1017 #ifdef CONFIG_X86_64
1018         ignore_bits |= EFER_LMA | EFER_LME;
1019         /* SCE is meaningful only in long mode on Intel */
1020         if (guest_efer & EFER_LMA)
1021                 ignore_bits &= ~(u64)EFER_SCE;
1022 #endif
1023
1024         /*
1025          * On EPT, we can't emulate NX, so we must switch EFER atomically.
1026          * On CPUs that support "load IA32_EFER", always switch EFER
1027          * atomically, since it's faster than switching it manually.
1028          */
1029         if (cpu_has_load_ia32_efer() ||
1030             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
1031                 if (!(guest_efer & EFER_LMA))
1032                         guest_efer &= ~EFER_LME;
1033                 if (guest_efer != host_efer)
1034                         add_atomic_switch_msr(vmx, MSR_EFER,
1035                                               guest_efer, host_efer, false);
1036                 else
1037                         clear_atomic_switch_msr(vmx, MSR_EFER);
1038                 return false;
1039         }
1040
1041         i = kvm_find_user_return_msr(MSR_EFER);
1042         if (i < 0)
1043                 return false;
1044
1045         clear_atomic_switch_msr(vmx, MSR_EFER);
1046
1047         guest_efer &= ~ignore_bits;
1048         guest_efer |= host_efer & ignore_bits;
1049
1050         vmx->guest_uret_msrs[i].data = guest_efer;
1051         vmx->guest_uret_msrs[i].mask = ~ignore_bits;
1052
1053         return true;
1054 }
1055
1056 #ifdef CONFIG_X86_32
1057 /*
1058  * On 32-bit kernels, VM exits still load the FS and GS bases from the
1059  * VMCS rather than the segment table.  KVM uses this helper to figure
1060  * out the current bases to poke them into the VMCS before entry.
1061  */
1062 static unsigned long segment_base(u16 selector)
1063 {
1064         struct desc_struct *table;
1065         unsigned long v;
1066
1067         if (!(selector & ~SEGMENT_RPL_MASK))
1068                 return 0;
1069
1070         table = get_current_gdt_ro();
1071
1072         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1073                 u16 ldt_selector = kvm_read_ldt();
1074
1075                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1076                         return 0;
1077
1078                 table = (struct desc_struct *)segment_base(ldt_selector);
1079         }
1080         v = get_desc_base(&table[selector >> 3]);
1081         return v;
1082 }
1083 #endif
1084
1085 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1086 {
1087         return vmx_pt_mode_is_host_guest() &&
1088                !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1089 }
1090
1091 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1092 {
1093         /* The base must be 128-byte aligned and a legal physical address. */
1094         return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1095 }
1096
1097 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1098 {
1099         u32 i;
1100
1101         wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1102         wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1103         wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1104         wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1105         for (i = 0; i < addr_range; i++) {
1106                 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1107                 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1108         }
1109 }
1110
1111 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1112 {
1113         u32 i;
1114
1115         rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1116         rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1117         rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1118         rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1119         for (i = 0; i < addr_range; i++) {
1120                 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1121                 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1122         }
1123 }
1124
1125 static void pt_guest_enter(struct vcpu_vmx *vmx)
1126 {
1127         if (vmx_pt_mode_is_system())
1128                 return;
1129
1130         /*
1131          * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1132          * Save host state before VM entry.
1133          */
1134         rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1135         if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1136                 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1137                 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1138                 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1139         }
1140 }
1141
1142 static void pt_guest_exit(struct vcpu_vmx *vmx)
1143 {
1144         if (vmx_pt_mode_is_system())
1145                 return;
1146
1147         if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1148                 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges);
1149                 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges);
1150         }
1151
1152         /*
1153          * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest,
1154          * i.e. RTIT_CTL is always cleared on VM-Exit.  Restore it if necessary.
1155          */
1156         if (vmx->pt_desc.host.ctl)
1157                 wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1158 }
1159
1160 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1161                         unsigned long fs_base, unsigned long gs_base)
1162 {
1163         if (unlikely(fs_sel != host->fs_sel)) {
1164                 if (!(fs_sel & 7))
1165                         vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1166                 else
1167                         vmcs_write16(HOST_FS_SELECTOR, 0);
1168                 host->fs_sel = fs_sel;
1169         }
1170         if (unlikely(gs_sel != host->gs_sel)) {
1171                 if (!(gs_sel & 7))
1172                         vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1173                 else
1174                         vmcs_write16(HOST_GS_SELECTOR, 0);
1175                 host->gs_sel = gs_sel;
1176         }
1177         if (unlikely(fs_base != host->fs_base)) {
1178                 vmcs_writel(HOST_FS_BASE, fs_base);
1179                 host->fs_base = fs_base;
1180         }
1181         if (unlikely(gs_base != host->gs_base)) {
1182                 vmcs_writel(HOST_GS_BASE, gs_base);
1183                 host->gs_base = gs_base;
1184         }
1185 }
1186
1187 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1188 {
1189         struct vcpu_vmx *vmx = to_vmx(vcpu);
1190         struct vmcs_host_state *host_state;
1191 #ifdef CONFIG_X86_64
1192         int cpu = raw_smp_processor_id();
1193 #endif
1194         unsigned long fs_base, gs_base;
1195         u16 fs_sel, gs_sel;
1196         int i;
1197
1198         vmx->req_immediate_exit = false;
1199
1200         /*
1201          * Note that guest MSRs to be saved/restored can also be changed
1202          * when guest state is loaded. This happens when guest transitions
1203          * to/from long-mode by setting MSR_EFER.LMA.
1204          */
1205         if (!vmx->guest_uret_msrs_loaded) {
1206                 vmx->guest_uret_msrs_loaded = true;
1207                 for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1208                         if (!vmx->guest_uret_msrs[i].load_into_hardware)
1209                                 continue;
1210
1211                         kvm_set_user_return_msr(i,
1212                                                 vmx->guest_uret_msrs[i].data,
1213                                                 vmx->guest_uret_msrs[i].mask);
1214                 }
1215         }
1216
1217         if (vmx->nested.need_vmcs12_to_shadow_sync)
1218                 nested_sync_vmcs12_to_shadow(vcpu);
1219
1220         if (vmx->guest_state_loaded)
1221                 return;
1222
1223         host_state = &vmx->loaded_vmcs->host_state;
1224
1225         /*
1226          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1227          * allow segment selectors with cpl > 0 or ti == 1.
1228          */
1229         host_state->ldt_sel = kvm_read_ldt();
1230
1231 #ifdef CONFIG_X86_64
1232         savesegment(ds, host_state->ds_sel);
1233         savesegment(es, host_state->es_sel);
1234
1235         gs_base = cpu_kernelmode_gs_base(cpu);
1236         if (likely(is_64bit_mm(current->mm))) {
1237                 current_save_fsgs();
1238                 fs_sel = current->thread.fsindex;
1239                 gs_sel = current->thread.gsindex;
1240                 fs_base = current->thread.fsbase;
1241                 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1242         } else {
1243                 savesegment(fs, fs_sel);
1244                 savesegment(gs, gs_sel);
1245                 fs_base = read_msr(MSR_FS_BASE);
1246                 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1247         }
1248
1249         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1250 #else
1251         savesegment(fs, fs_sel);
1252         savesegment(gs, gs_sel);
1253         fs_base = segment_base(fs_sel);
1254         gs_base = segment_base(gs_sel);
1255 #endif
1256
1257         vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1258         vmx->guest_state_loaded = true;
1259 }
1260
1261 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1262 {
1263         struct vmcs_host_state *host_state;
1264
1265         if (!vmx->guest_state_loaded)
1266                 return;
1267
1268         host_state = &vmx->loaded_vmcs->host_state;
1269
1270         ++vmx->vcpu.stat.host_state_reload;
1271
1272 #ifdef CONFIG_X86_64
1273         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1274 #endif
1275         if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1276                 kvm_load_ldt(host_state->ldt_sel);
1277 #ifdef CONFIG_X86_64
1278                 load_gs_index(host_state->gs_sel);
1279 #else
1280                 loadsegment(gs, host_state->gs_sel);
1281 #endif
1282         }
1283         if (host_state->fs_sel & 7)
1284                 loadsegment(fs, host_state->fs_sel);
1285 #ifdef CONFIG_X86_64
1286         if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1287                 loadsegment(ds, host_state->ds_sel);
1288                 loadsegment(es, host_state->es_sel);
1289         }
1290 #endif
1291         invalidate_tss_limit();
1292 #ifdef CONFIG_X86_64
1293         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1294 #endif
1295         load_fixmap_gdt(raw_smp_processor_id());
1296         vmx->guest_state_loaded = false;
1297         vmx->guest_uret_msrs_loaded = false;
1298 }
1299
1300 #ifdef CONFIG_X86_64
1301 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1302 {
1303         preempt_disable();
1304         if (vmx->guest_state_loaded)
1305                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1306         preempt_enable();
1307         return vmx->msr_guest_kernel_gs_base;
1308 }
1309
1310 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1311 {
1312         preempt_disable();
1313         if (vmx->guest_state_loaded)
1314                 wrmsrl(MSR_KERNEL_GS_BASE, data);
1315         preempt_enable();
1316         vmx->msr_guest_kernel_gs_base = data;
1317 }
1318 #endif
1319
1320 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1321                         struct loaded_vmcs *buddy)
1322 {
1323         struct vcpu_vmx *vmx = to_vmx(vcpu);
1324         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1325         struct vmcs *prev;
1326
1327         if (!already_loaded) {
1328                 loaded_vmcs_clear(vmx->loaded_vmcs);
1329                 local_irq_disable();
1330
1331                 /*
1332                  * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1333                  * this cpu's percpu list, otherwise it may not yet be deleted
1334                  * from its previous cpu's percpu list.  Pairs with the
1335                  * smb_wmb() in __loaded_vmcs_clear().
1336                  */
1337                 smp_rmb();
1338
1339                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1340                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1341                 local_irq_enable();
1342         }
1343
1344         prev = per_cpu(current_vmcs, cpu);
1345         if (prev != vmx->loaded_vmcs->vmcs) {
1346                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1347                 vmcs_load(vmx->loaded_vmcs->vmcs);
1348
1349                 /*
1350                  * No indirect branch prediction barrier needed when switching
1351                  * the active VMCS within a guest, e.g. on nested VM-Enter.
1352                  * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1353                  */
1354                 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1355                         indirect_branch_prediction_barrier();
1356         }
1357
1358         if (!already_loaded) {
1359                 void *gdt = get_current_gdt_ro();
1360
1361                 /*
1362                  * Flush all EPTP/VPID contexts, the new pCPU may have stale
1363                  * TLB entries from its previous association with the vCPU.
1364                  */
1365                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1366
1367                 /*
1368                  * Linux uses per-cpu TSS and GDT, so set these when switching
1369                  * processors.  See 22.2.4.
1370                  */
1371                 vmcs_writel(HOST_TR_BASE,
1372                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1373                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
1374
1375                 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) {
1376                         /* 22.2.3 */
1377                         vmcs_writel(HOST_IA32_SYSENTER_ESP,
1378                                     (unsigned long)(cpu_entry_stack(cpu) + 1));
1379                 }
1380
1381                 vmx->loaded_vmcs->cpu = cpu;
1382         }
1383 }
1384
1385 /*
1386  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1387  * vcpu mutex is already taken.
1388  */
1389 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1390 {
1391         struct vcpu_vmx *vmx = to_vmx(vcpu);
1392
1393         vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1394
1395         vmx_vcpu_pi_load(vcpu, cpu);
1396
1397         vmx->host_debugctlmsr = get_debugctlmsr();
1398 }
1399
1400 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1401 {
1402         vmx_vcpu_pi_put(vcpu);
1403
1404         vmx_prepare_switch_to_host(to_vmx(vcpu));
1405 }
1406
1407 bool vmx_emulation_required(struct kvm_vcpu *vcpu)
1408 {
1409         return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1410 }
1411
1412 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1413 {
1414         struct vcpu_vmx *vmx = to_vmx(vcpu);
1415         unsigned long rflags, save_rflags;
1416
1417         if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1418                 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1419                 rflags = vmcs_readl(GUEST_RFLAGS);
1420                 if (vmx->rmode.vm86_active) {
1421                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1422                         save_rflags = vmx->rmode.save_rflags;
1423                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1424                 }
1425                 vmx->rflags = rflags;
1426         }
1427         return vmx->rflags;
1428 }
1429
1430 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1431 {
1432         struct vcpu_vmx *vmx = to_vmx(vcpu);
1433         unsigned long old_rflags;
1434
1435         if (is_unrestricted_guest(vcpu)) {
1436                 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1437                 vmx->rflags = rflags;
1438                 vmcs_writel(GUEST_RFLAGS, rflags);
1439                 return;
1440         }
1441
1442         old_rflags = vmx_get_rflags(vcpu);
1443         vmx->rflags = rflags;
1444         if (vmx->rmode.vm86_active) {
1445                 vmx->rmode.save_rflags = rflags;
1446                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1447         }
1448         vmcs_writel(GUEST_RFLAGS, rflags);
1449
1450         if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1451                 vmx->emulation_required = vmx_emulation_required(vcpu);
1452 }
1453
1454 static bool vmx_get_if_flag(struct kvm_vcpu *vcpu)
1455 {
1456         return vmx_get_rflags(vcpu) & X86_EFLAGS_IF;
1457 }
1458
1459 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1460 {
1461         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1462         int ret = 0;
1463
1464         if (interruptibility & GUEST_INTR_STATE_STI)
1465                 ret |= KVM_X86_SHADOW_INT_STI;
1466         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1467                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1468
1469         return ret;
1470 }
1471
1472 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1473 {
1474         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1475         u32 interruptibility = interruptibility_old;
1476
1477         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1478
1479         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1480                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1481         else if (mask & KVM_X86_SHADOW_INT_STI)
1482                 interruptibility |= GUEST_INTR_STATE_STI;
1483
1484         if ((interruptibility != interruptibility_old))
1485                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1486 }
1487
1488 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1489 {
1490         struct vcpu_vmx *vmx = to_vmx(vcpu);
1491         unsigned long value;
1492
1493         /*
1494          * Any MSR write that attempts to change bits marked reserved will
1495          * case a #GP fault.
1496          */
1497         if (data & vmx->pt_desc.ctl_bitmask)
1498                 return 1;
1499
1500         /*
1501          * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1502          * result in a #GP unless the same write also clears TraceEn.
1503          */
1504         if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1505                 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1506                 return 1;
1507
1508         /*
1509          * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1510          * and FabricEn would cause #GP, if
1511          * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1512          */
1513         if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1514                 !(data & RTIT_CTL_FABRIC_EN) &&
1515                 !intel_pt_validate_cap(vmx->pt_desc.caps,
1516                                         PT_CAP_single_range_output))
1517                 return 1;
1518
1519         /*
1520          * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1521          * utilize encodings marked reserved will cause a #GP fault.
1522          */
1523         value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1524         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1525                         !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1526                         RTIT_CTL_MTC_RANGE_OFFSET, &value))
1527                 return 1;
1528         value = intel_pt_validate_cap(vmx->pt_desc.caps,
1529                                                 PT_CAP_cycle_thresholds);
1530         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1531                         !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1532                         RTIT_CTL_CYC_THRESH_OFFSET, &value))
1533                 return 1;
1534         value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1535         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1536                         !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1537                         RTIT_CTL_PSB_FREQ_OFFSET, &value))
1538                 return 1;
1539
1540         /*
1541          * If ADDRx_CFG is reserved or the encodings is >2 will
1542          * cause a #GP fault.
1543          */
1544         value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1545         if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2))
1546                 return 1;
1547         value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1548         if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2))
1549                 return 1;
1550         value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1551         if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2))
1552                 return 1;
1553         value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1554         if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2))
1555                 return 1;
1556
1557         return 0;
1558 }
1559
1560 static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
1561                                         void *insn, int insn_len)
1562 {
1563         /*
1564          * Emulation of instructions in SGX enclaves is impossible as RIP does
1565          * not point at the failing instruction, and even if it did, the code
1566          * stream is inaccessible.  Inject #UD instead of exiting to userspace
1567          * so that guest userspace can't DoS the guest simply by triggering
1568          * emulation (enclaves are CPL3 only).
1569          */
1570         if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1571                 kvm_queue_exception(vcpu, UD_VECTOR);
1572                 return false;
1573         }
1574         return true;
1575 }
1576
1577 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1578 {
1579         union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1580         unsigned long rip, orig_rip;
1581         u32 instr_len;
1582
1583         /*
1584          * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1585          * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1586          * set when EPT misconfig occurs.  In practice, real hardware updates
1587          * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1588          * (namely Hyper-V) don't set it due to it being undefined behavior,
1589          * i.e. we end up advancing IP with some random value.
1590          */
1591         if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1592             exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1593                 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1594
1595                 /*
1596                  * Emulating an enclave's instructions isn't supported as KVM
1597                  * cannot access the enclave's memory or its true RIP, e.g. the
1598                  * vmcs.GUEST_RIP points at the exit point of the enclave, not
1599                  * the RIP that actually triggered the VM-Exit.  But, because
1600                  * most instructions that cause VM-Exit will #UD in an enclave,
1601                  * most instruction-based VM-Exits simply do not occur.
1602                  *
1603                  * There are a few exceptions, notably the debug instructions
1604                  * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1605                  * and generate #DB/#BP as expected, which KVM might intercept.
1606                  * But again, the CPU does the dirty work and saves an instr
1607                  * length of zero so VMMs don't shoot themselves in the foot.
1608                  * WARN if KVM tries to skip a non-zero length instruction on
1609                  * a VM-Exit from an enclave.
1610                  */
1611                 if (!instr_len)
1612                         goto rip_updated;
1613
1614                 WARN(exit_reason.enclave_mode,
1615                      "KVM: skipping instruction after SGX enclave VM-Exit");
1616
1617                 orig_rip = kvm_rip_read(vcpu);
1618                 rip = orig_rip + instr_len;
1619 #ifdef CONFIG_X86_64
1620                 /*
1621                  * We need to mask out the high 32 bits of RIP if not in 64-bit
1622                  * mode, but just finding out that we are in 64-bit mode is
1623                  * quite expensive.  Only do it if there was a carry.
1624                  */
1625                 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1626                         rip = (u32)rip;
1627 #endif
1628                 kvm_rip_write(vcpu, rip);
1629         } else {
1630                 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1631                         return 0;
1632         }
1633
1634 rip_updated:
1635         /* skipping an emulated instruction also counts */
1636         vmx_set_interrupt_shadow(vcpu, 0);
1637
1638         return 1;
1639 }
1640
1641 /*
1642  * Recognizes a pending MTF VM-exit and records the nested state for later
1643  * delivery.
1644  */
1645 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1646 {
1647         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1648         struct vcpu_vmx *vmx = to_vmx(vcpu);
1649
1650         if (!is_guest_mode(vcpu))
1651                 return;
1652
1653         /*
1654          * Per the SDM, MTF takes priority over debug-trap exceptions besides
1655          * T-bit traps. As instruction emulation is completed (i.e. at the
1656          * instruction boundary), any #DB exception pending delivery must be a
1657          * debug-trap. Record the pending MTF state to be delivered in
1658          * vmx_check_nested_events().
1659          */
1660         if (nested_cpu_has_mtf(vmcs12) &&
1661             (!vcpu->arch.exception.pending ||
1662              vcpu->arch.exception.nr == DB_VECTOR))
1663                 vmx->nested.mtf_pending = true;
1664         else
1665                 vmx->nested.mtf_pending = false;
1666 }
1667
1668 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1669 {
1670         vmx_update_emulated_instruction(vcpu);
1671         return skip_emulated_instruction(vcpu);
1672 }
1673
1674 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1675 {
1676         /*
1677          * Ensure that we clear the HLT state in the VMCS.  We don't need to
1678          * explicitly skip the instruction because if the HLT state is set,
1679          * then the instruction is already executing and RIP has already been
1680          * advanced.
1681          */
1682         if (kvm_hlt_in_guest(vcpu->kvm) &&
1683                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1684                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1685 }
1686
1687 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1688 {
1689         struct vcpu_vmx *vmx = to_vmx(vcpu);
1690         unsigned nr = vcpu->arch.exception.nr;
1691         bool has_error_code = vcpu->arch.exception.has_error_code;
1692         u32 error_code = vcpu->arch.exception.error_code;
1693         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1694
1695         kvm_deliver_exception_payload(vcpu);
1696
1697         if (has_error_code) {
1698                 /*
1699                  * Despite the error code being architecturally defined as 32
1700                  * bits, and the VMCS field being 32 bits, Intel CPUs and thus
1701                  * VMX don't actually supporting setting bits 31:16.  Hardware
1702                  * will (should) never provide a bogus error code, but AMD CPUs
1703                  * do generate error codes with bits 31:16 set, and so KVM's
1704                  * ABI lets userspace shove in arbitrary 32-bit values.  Drop
1705                  * the upper bits to avoid VM-Fail, losing information that
1706                  * does't really exist is preferable to killing the VM.
1707                  */
1708                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code);
1709                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1710         }
1711
1712         if (vmx->rmode.vm86_active) {
1713                 int inc_eip = 0;
1714                 if (kvm_exception_is_soft(nr))
1715                         inc_eip = vcpu->arch.event_exit_inst_len;
1716                 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1717                 return;
1718         }
1719
1720         WARN_ON_ONCE(vmx->emulation_required);
1721
1722         if (kvm_exception_is_soft(nr)) {
1723                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1724                              vmx->vcpu.arch.event_exit_inst_len);
1725                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1726         } else
1727                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1728
1729         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1730
1731         vmx_clear_hlt(vcpu);
1732 }
1733
1734 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1735                                bool load_into_hardware)
1736 {
1737         struct vmx_uret_msr *uret_msr;
1738
1739         uret_msr = vmx_find_uret_msr(vmx, msr);
1740         if (!uret_msr)
1741                 return;
1742
1743         uret_msr->load_into_hardware = load_into_hardware;
1744 }
1745
1746 /*
1747  * Configuring user return MSRs to automatically save, load, and restore MSRs
1748  * that need to be shoved into hardware when running the guest.  Note, omitting
1749  * an MSR here does _NOT_ mean it's not emulated, only that it will not be
1750  * loaded into hardware when running the guest.
1751  */
1752 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx)
1753 {
1754 #ifdef CONFIG_X86_64
1755         bool load_syscall_msrs;
1756
1757         /*
1758          * The SYSCALL MSRs are only needed on long mode guests, and only
1759          * when EFER.SCE is set.
1760          */
1761         load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1762                             (vmx->vcpu.arch.efer & EFER_SCE);
1763
1764         vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1765         vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1766         vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1767 #endif
1768         vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1769
1770         vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1771                            guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1772                            guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1773
1774         /*
1775          * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1776          * kernel and old userspace.  If those guests run on a tsx=off host, do
1777          * allow guests to use TSX_CTRL, but don't change the value in hardware
1778          * so that TSX remains always disabled.
1779          */
1780         vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1781
1782         /*
1783          * The set of MSRs to load may have changed, reload MSRs before the
1784          * next VM-Enter.
1785          */
1786         vmx->guest_uret_msrs_loaded = false;
1787 }
1788
1789 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1790 {
1791         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1792
1793         if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1794                 return vmcs12->tsc_offset;
1795
1796         return 0;
1797 }
1798
1799 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1800 {
1801         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1802
1803         if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1804             nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1805                 return vmcs12->tsc_multiplier;
1806
1807         return kvm_caps.default_tsc_scaling_ratio;
1808 }
1809
1810 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1811 {
1812         vmcs_write64(TSC_OFFSET, offset);
1813 }
1814
1815 static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1816 {
1817         vmcs_write64(TSC_MULTIPLIER, multiplier);
1818 }
1819
1820 /*
1821  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1822  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1823  * all guests if the "nested" module option is off, and can also be disabled
1824  * for a single guest by disabling its VMX cpuid bit.
1825  */
1826 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1827 {
1828         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1829 }
1830
1831 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1832                                                  uint64_t val)
1833 {
1834         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1835
1836         return !(val & ~valid_bits);
1837 }
1838
1839 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1840 {
1841         switch (msr->index) {
1842         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1843                 if (!nested)
1844                         return 1;
1845                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1846         case MSR_IA32_PERF_CAPABILITIES:
1847                 msr->data = vmx_get_perf_capabilities();
1848                 return 0;
1849         default:
1850                 return KVM_MSR_RET_INVALID;
1851         }
1852 }
1853
1854 /*
1855  * Reads an msr value (of 'msr_info->index') into 'msr_info->data'.
1856  * Returns 0 on success, non-0 otherwise.
1857  * Assumes vcpu_load() was already called.
1858  */
1859 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1860 {
1861         struct vcpu_vmx *vmx = to_vmx(vcpu);
1862         struct vmx_uret_msr *msr;
1863         u32 index;
1864
1865         switch (msr_info->index) {
1866 #ifdef CONFIG_X86_64
1867         case MSR_FS_BASE:
1868                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1869                 break;
1870         case MSR_GS_BASE:
1871                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1872                 break;
1873         case MSR_KERNEL_GS_BASE:
1874                 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1875                 break;
1876 #endif
1877         case MSR_EFER:
1878                 return kvm_get_msr_common(vcpu, msr_info);
1879         case MSR_IA32_TSX_CTRL:
1880                 if (!msr_info->host_initiated &&
1881                     !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1882                         return 1;
1883                 goto find_uret_msr;
1884         case MSR_IA32_UMWAIT_CONTROL:
1885                 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1886                         return 1;
1887
1888                 msr_info->data = vmx->msr_ia32_umwait_control;
1889                 break;
1890         case MSR_IA32_SPEC_CTRL:
1891                 if (!msr_info->host_initiated &&
1892                     !guest_has_spec_ctrl_msr(vcpu))
1893                         return 1;
1894
1895                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1896                 break;
1897         case MSR_IA32_SYSENTER_CS:
1898                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1899                 break;
1900         case MSR_IA32_SYSENTER_EIP:
1901                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1902                 break;
1903         case MSR_IA32_SYSENTER_ESP:
1904                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1905                 break;
1906         case MSR_IA32_BNDCFGS:
1907                 if (!kvm_mpx_supported() ||
1908                     (!msr_info->host_initiated &&
1909                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1910                         return 1;
1911                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1912                 break;
1913         case MSR_IA32_MCG_EXT_CTL:
1914                 if (!msr_info->host_initiated &&
1915                     !(vmx->msr_ia32_feature_control &
1916                       FEAT_CTL_LMCE_ENABLED))
1917                         return 1;
1918                 msr_info->data = vcpu->arch.mcg_ext_ctl;
1919                 break;
1920         case MSR_IA32_FEAT_CTL:
1921                 msr_info->data = vmx->msr_ia32_feature_control;
1922                 break;
1923         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1924                 if (!msr_info->host_initiated &&
1925                     !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1926                         return 1;
1927                 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1928                         [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1929                 break;
1930         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1931                 if (!nested_vmx_allowed(vcpu))
1932                         return 1;
1933                 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1934                                     &msr_info->data))
1935                         return 1;
1936                 /*
1937                  * Enlightened VMCS v1 doesn't have certain VMCS fields but
1938                  * instead of just ignoring the features, different Hyper-V
1939                  * versions are either trying to use them and fail or do some
1940                  * sanity checking and refuse to boot. Filter all unsupported
1941                  * features out.
1942                  */
1943                 if (!msr_info->host_initiated && guest_cpuid_has_evmcs(vcpu))
1944                         nested_evmcs_filter_control_msr(vcpu, msr_info->index,
1945                                                         &msr_info->data);
1946                 break;
1947         case MSR_IA32_RTIT_CTL:
1948                 if (!vmx_pt_mode_is_host_guest())
1949                         return 1;
1950                 msr_info->data = vmx->pt_desc.guest.ctl;
1951                 break;
1952         case MSR_IA32_RTIT_STATUS:
1953                 if (!vmx_pt_mode_is_host_guest())
1954                         return 1;
1955                 msr_info->data = vmx->pt_desc.guest.status;
1956                 break;
1957         case MSR_IA32_RTIT_CR3_MATCH:
1958                 if (!vmx_pt_mode_is_host_guest() ||
1959                         !intel_pt_validate_cap(vmx->pt_desc.caps,
1960                                                 PT_CAP_cr3_filtering))
1961                         return 1;
1962                 msr_info->data = vmx->pt_desc.guest.cr3_match;
1963                 break;
1964         case MSR_IA32_RTIT_OUTPUT_BASE:
1965                 if (!vmx_pt_mode_is_host_guest() ||
1966                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1967                                         PT_CAP_topa_output) &&
1968                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1969                                         PT_CAP_single_range_output)))
1970                         return 1;
1971                 msr_info->data = vmx->pt_desc.guest.output_base;
1972                 break;
1973         case MSR_IA32_RTIT_OUTPUT_MASK:
1974                 if (!vmx_pt_mode_is_host_guest() ||
1975                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1976                                         PT_CAP_topa_output) &&
1977                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1978                                         PT_CAP_single_range_output)))
1979                         return 1;
1980                 msr_info->data = vmx->pt_desc.guest.output_mask;
1981                 break;
1982         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1983                 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1984                 if (!vmx_pt_mode_is_host_guest() ||
1985                     (index >= 2 * vmx->pt_desc.num_address_ranges))
1986                         return 1;
1987                 if (index % 2)
1988                         msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1989                 else
1990                         msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1991                 break;
1992         case MSR_IA32_DEBUGCTLMSR:
1993                 msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1994                 break;
1995         default:
1996         find_uret_msr:
1997                 msr = vmx_find_uret_msr(vmx, msr_info->index);
1998                 if (msr) {
1999                         msr_info->data = msr->data;
2000                         break;
2001                 }
2002                 return kvm_get_msr_common(vcpu, msr_info);
2003         }
2004
2005         return 0;
2006 }
2007
2008 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
2009                                                     u64 data)
2010 {
2011 #ifdef CONFIG_X86_64
2012         if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
2013                 return (u32)data;
2014 #endif
2015         return (unsigned long)data;
2016 }
2017
2018 static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
2019 {
2020         u64 debugctl = vmx_supported_debugctl();
2021
2022         if (!intel_pmu_lbr_is_enabled(vcpu))
2023                 debugctl &= ~DEBUGCTLMSR_LBR_MASK;
2024
2025         if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
2026                 debugctl &= ~DEBUGCTLMSR_BUS_LOCK_DETECT;
2027
2028         return debugctl;
2029 }
2030
2031 /*
2032  * Writes msr value into the appropriate "register".
2033  * Returns 0 on success, non-0 otherwise.
2034  * Assumes vcpu_load() was already called.
2035  */
2036 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2037 {
2038         struct vcpu_vmx *vmx = to_vmx(vcpu);
2039         struct vmx_uret_msr *msr;
2040         int ret = 0;
2041         u32 msr_index = msr_info->index;
2042         u64 data = msr_info->data;
2043         u32 index;
2044
2045         switch (msr_index) {
2046         case MSR_EFER:
2047                 ret = kvm_set_msr_common(vcpu, msr_info);
2048                 break;
2049 #ifdef CONFIG_X86_64
2050         case MSR_FS_BASE:
2051                 vmx_segment_cache_clear(vmx);
2052                 vmcs_writel(GUEST_FS_BASE, data);
2053                 break;
2054         case MSR_GS_BASE:
2055                 vmx_segment_cache_clear(vmx);
2056                 vmcs_writel(GUEST_GS_BASE, data);
2057                 break;
2058         case MSR_KERNEL_GS_BASE:
2059                 vmx_write_guest_kernel_gs_base(vmx, data);
2060                 break;
2061         case MSR_IA32_XFD:
2062                 ret = kvm_set_msr_common(vcpu, msr_info);
2063                 /*
2064                  * Always intercepting WRMSR could incur non-negligible
2065                  * overhead given xfd might be changed frequently in
2066                  * guest context switch. Disable write interception
2067                  * upon the first write with a non-zero value (indicating
2068                  * potential usage on dynamic xfeatures). Also update
2069                  * exception bitmap to trap #NM for proper virtualization
2070                  * of guest xfd_err.
2071                  */
2072                 if (!ret && data) {
2073                         vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD,
2074                                                       MSR_TYPE_RW);
2075                         vcpu->arch.xfd_no_write_intercept = true;
2076                         vmx_update_exception_bitmap(vcpu);
2077                 }
2078                 break;
2079 #endif
2080         case MSR_IA32_SYSENTER_CS:
2081                 if (is_guest_mode(vcpu))
2082                         get_vmcs12(vcpu)->guest_sysenter_cs = data;
2083                 vmcs_write32(GUEST_SYSENTER_CS, data);
2084                 break;
2085         case MSR_IA32_SYSENTER_EIP:
2086                 if (is_guest_mode(vcpu)) {
2087                         data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2088                         get_vmcs12(vcpu)->guest_sysenter_eip = data;
2089                 }
2090                 vmcs_writel(GUEST_SYSENTER_EIP, data);
2091                 break;
2092         case MSR_IA32_SYSENTER_ESP:
2093                 if (is_guest_mode(vcpu)) {
2094                         data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2095                         get_vmcs12(vcpu)->guest_sysenter_esp = data;
2096                 }
2097                 vmcs_writel(GUEST_SYSENTER_ESP, data);
2098                 break;
2099         case MSR_IA32_DEBUGCTLMSR: {
2100                 u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
2101                 if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
2102                         if (report_ignored_msrs)
2103                                 vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
2104                                             __func__, data);
2105                         data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2106                         invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
2107                 }
2108
2109                 if (invalid)
2110                         return 1;
2111
2112                 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2113                                                 VM_EXIT_SAVE_DEBUG_CONTROLS)
2114                         get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2115
2116                 vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2117                 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2118                     (data & DEBUGCTLMSR_LBR))
2119                         intel_pmu_create_guest_lbr_event(vcpu);
2120                 return 0;
2121         }
2122         case MSR_IA32_BNDCFGS:
2123                 if (!kvm_mpx_supported() ||
2124                     (!msr_info->host_initiated &&
2125                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2126                         return 1;
2127                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2128                     (data & MSR_IA32_BNDCFGS_RSVD))
2129                         return 1;
2130
2131                 if (is_guest_mode(vcpu) &&
2132                     ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) ||
2133                      (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS)))
2134                         get_vmcs12(vcpu)->guest_bndcfgs = data;
2135
2136                 vmcs_write64(GUEST_BNDCFGS, data);
2137                 break;
2138         case MSR_IA32_UMWAIT_CONTROL:
2139                 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2140                         return 1;
2141
2142                 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2143                 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2144                         return 1;
2145
2146                 vmx->msr_ia32_umwait_control = data;
2147                 break;
2148         case MSR_IA32_SPEC_CTRL:
2149                 if (!msr_info->host_initiated &&
2150                     !guest_has_spec_ctrl_msr(vcpu))
2151                         return 1;
2152
2153                 if (kvm_spec_ctrl_test_value(data))
2154                         return 1;
2155
2156                 vmx->spec_ctrl = data;
2157                 if (!data)
2158                         break;
2159
2160                 /*
2161                  * For non-nested:
2162                  * When it's written (to non-zero) for the first time, pass
2163                  * it through.
2164                  *
2165                  * For nested:
2166                  * The handling of the MSR bitmap for L2 guests is done in
2167                  * nested_vmx_prepare_msr_bitmap. We should not touch the
2168                  * vmcs02.msr_bitmap here since it gets completely overwritten
2169                  * in the merging. We update the vmcs01 here for L1 as well
2170                  * since it will end up touching the MSR anyway now.
2171                  */
2172                 vmx_disable_intercept_for_msr(vcpu,
2173                                               MSR_IA32_SPEC_CTRL,
2174                                               MSR_TYPE_RW);
2175                 break;
2176         case MSR_IA32_TSX_CTRL:
2177                 if (!msr_info->host_initiated &&
2178                     !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2179                         return 1;
2180                 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2181                         return 1;
2182                 goto find_uret_msr;
2183         case MSR_IA32_PRED_CMD:
2184                 if (!msr_info->host_initiated &&
2185                     !guest_has_pred_cmd_msr(vcpu))
2186                         return 1;
2187
2188                 if (data & ~PRED_CMD_IBPB)
2189                         return 1;
2190                 if (!boot_cpu_has(X86_FEATURE_IBPB))
2191                         return 1;
2192                 if (!data)
2193                         break;
2194
2195                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2196
2197                 /*
2198                  * For non-nested:
2199                  * When it's written (to non-zero) for the first time, pass
2200                  * it through.
2201                  *
2202                  * For nested:
2203                  * The handling of the MSR bitmap for L2 guests is done in
2204                  * nested_vmx_prepare_msr_bitmap. We should not touch the
2205                  * vmcs02.msr_bitmap here since it gets completely overwritten
2206                  * in the merging.
2207                  */
2208                 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2209                 break;
2210         case MSR_IA32_CR_PAT:
2211                 if (!kvm_pat_valid(data))
2212                         return 1;
2213
2214                 if (is_guest_mode(vcpu) &&
2215                     get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2216                         get_vmcs12(vcpu)->guest_ia32_pat = data;
2217
2218                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2219                         vmcs_write64(GUEST_IA32_PAT, data);
2220                         vcpu->arch.pat = data;
2221                         break;
2222                 }
2223                 ret = kvm_set_msr_common(vcpu, msr_info);
2224                 break;
2225         case MSR_IA32_MCG_EXT_CTL:
2226                 if ((!msr_info->host_initiated &&
2227                      !(to_vmx(vcpu)->msr_ia32_feature_control &
2228                        FEAT_CTL_LMCE_ENABLED)) ||
2229                     (data & ~MCG_EXT_CTL_LMCE_EN))
2230                         return 1;
2231                 vcpu->arch.mcg_ext_ctl = data;
2232                 break;
2233         case MSR_IA32_FEAT_CTL:
2234                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2235                     (to_vmx(vcpu)->msr_ia32_feature_control &
2236                      FEAT_CTL_LOCKED && !msr_info->host_initiated))
2237                         return 1;
2238                 vmx->msr_ia32_feature_control = data;
2239                 if (msr_info->host_initiated && data == 0)
2240                         vmx_leave_nested(vcpu);
2241
2242                 /* SGX may be enabled/disabled by guest's firmware */
2243                 vmx_write_encls_bitmap(vcpu, NULL);
2244                 break;
2245         case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2246                 /*
2247                  * On real hardware, the LE hash MSRs are writable before
2248                  * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2249                  * at which point SGX related bits in IA32_FEATURE_CONTROL
2250                  * become writable.
2251                  *
2252                  * KVM does not emulate SGX activation for simplicity, so
2253                  * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2254                  * is unlocked.  This is technically not architectural
2255                  * behavior, but it's close enough.
2256                  */
2257                 if (!msr_info->host_initiated &&
2258                     (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2259                     ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2260                     !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2261                         return 1;
2262                 vmx->msr_ia32_sgxlepubkeyhash
2263                         [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2264                 break;
2265         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2266                 if (!msr_info->host_initiated)
2267                         return 1; /* they are read-only */
2268                 if (!nested_vmx_allowed(vcpu))
2269                         return 1;
2270                 return vmx_set_vmx_msr(vcpu, msr_index, data);
2271         case MSR_IA32_RTIT_CTL:
2272                 if (!vmx_pt_mode_is_host_guest() ||
2273                         vmx_rtit_ctl_check(vcpu, data) ||
2274                         vmx->nested.vmxon)
2275                         return 1;
2276                 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2277                 vmx->pt_desc.guest.ctl = data;
2278                 pt_update_intercept_for_msr(vcpu);
2279                 break;
2280         case MSR_IA32_RTIT_STATUS:
2281                 if (!pt_can_write_msr(vmx))
2282                         return 1;
2283                 if (data & MSR_IA32_RTIT_STATUS_MASK)
2284                         return 1;
2285                 vmx->pt_desc.guest.status = data;
2286                 break;
2287         case MSR_IA32_RTIT_CR3_MATCH:
2288                 if (!pt_can_write_msr(vmx))
2289                         return 1;
2290                 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2291                                            PT_CAP_cr3_filtering))
2292                         return 1;
2293                 vmx->pt_desc.guest.cr3_match = data;
2294                 break;
2295         case MSR_IA32_RTIT_OUTPUT_BASE:
2296                 if (!pt_can_write_msr(vmx))
2297                         return 1;
2298                 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2299                                            PT_CAP_topa_output) &&
2300                     !intel_pt_validate_cap(vmx->pt_desc.caps,
2301                                            PT_CAP_single_range_output))
2302                         return 1;
2303                 if (!pt_output_base_valid(vcpu, data))
2304                         return 1;
2305                 vmx->pt_desc.guest.output_base = data;
2306                 break;
2307         case MSR_IA32_RTIT_OUTPUT_MASK:
2308                 if (!pt_can_write_msr(vmx))
2309                         return 1;
2310                 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2311                                            PT_CAP_topa_output) &&
2312                     !intel_pt_validate_cap(vmx->pt_desc.caps,
2313                                            PT_CAP_single_range_output))
2314                         return 1;
2315                 vmx->pt_desc.guest.output_mask = data;
2316                 break;
2317         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2318                 if (!pt_can_write_msr(vmx))
2319                         return 1;
2320                 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2321                 if (index >= 2 * vmx->pt_desc.num_address_ranges)
2322                         return 1;
2323                 if (is_noncanonical_address(data, vcpu))
2324                         return 1;
2325                 if (index % 2)
2326                         vmx->pt_desc.guest.addr_b[index / 2] = data;
2327                 else
2328                         vmx->pt_desc.guest.addr_a[index / 2] = data;
2329                 break;
2330         case MSR_IA32_PERF_CAPABILITIES:
2331                 if (data && !vcpu_to_pmu(vcpu)->version)
2332                         return 1;
2333                 if (data & PMU_CAP_LBR_FMT) {
2334                         if ((data & PMU_CAP_LBR_FMT) !=
2335                             (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2336                                 return 1;
2337                         if (!cpuid_model_is_consistent(vcpu))
2338                                 return 1;
2339                 }
2340                 if (data & PERF_CAP_PEBS_FORMAT) {
2341                         if ((data & PERF_CAP_PEBS_MASK) !=
2342                             (vmx_get_perf_capabilities() & PERF_CAP_PEBS_MASK))
2343                                 return 1;
2344                         if (!guest_cpuid_has(vcpu, X86_FEATURE_DS))
2345                                 return 1;
2346                         if (!guest_cpuid_has(vcpu, X86_FEATURE_DTES64))
2347                                 return 1;
2348                         if (!cpuid_model_is_consistent(vcpu))
2349                                 return 1;
2350                 }
2351                 ret = kvm_set_msr_common(vcpu, msr_info);
2352                 break;
2353
2354         default:
2355         find_uret_msr:
2356                 msr = vmx_find_uret_msr(vmx, msr_index);
2357                 if (msr)
2358                         ret = vmx_set_guest_uret_msr(vmx, msr, data);
2359                 else
2360                         ret = kvm_set_msr_common(vcpu, msr_info);
2361         }
2362
2363         /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */
2364         if (msr_index == MSR_IA32_ARCH_CAPABILITIES)
2365                 vmx_update_fb_clear_dis(vcpu, vmx);
2366
2367         return ret;
2368 }
2369
2370 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2371 {
2372         unsigned long guest_owned_bits;
2373
2374         kvm_register_mark_available(vcpu, reg);
2375
2376         switch (reg) {
2377         case VCPU_REGS_RSP:
2378                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2379                 break;
2380         case VCPU_REGS_RIP:
2381                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2382                 break;
2383         case VCPU_EXREG_PDPTR:
2384                 if (enable_ept)
2385                         ept_save_pdptrs(vcpu);
2386                 break;
2387         case VCPU_EXREG_CR0:
2388                 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2389
2390                 vcpu->arch.cr0 &= ~guest_owned_bits;
2391                 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2392                 break;
2393         case VCPU_EXREG_CR3:
2394                 /*
2395                  * When intercepting CR3 loads, e.g. for shadowing paging, KVM's
2396                  * CR3 is loaded into hardware, not the guest's CR3.
2397                  */
2398                 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING))
2399                         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2400                 break;
2401         case VCPU_EXREG_CR4:
2402                 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2403
2404                 vcpu->arch.cr4 &= ~guest_owned_bits;
2405                 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2406                 break;
2407         default:
2408                 KVM_BUG_ON(1, vcpu->kvm);
2409                 break;
2410         }
2411 }
2412
2413 static __init int cpu_has_kvm_support(void)
2414 {
2415         return cpu_has_vmx();
2416 }
2417
2418 static __init int vmx_disabled_by_bios(void)
2419 {
2420         return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2421                !boot_cpu_has(X86_FEATURE_VMX);
2422 }
2423
2424 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2425 {
2426         u64 msr;
2427
2428         cr4_set_bits(X86_CR4_VMXE);
2429
2430         asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2431                           _ASM_EXTABLE(1b, %l[fault])
2432                           : : [vmxon_pointer] "m"(vmxon_pointer)
2433                           : : fault);
2434         return 0;
2435
2436 fault:
2437         WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2438                   rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2439         cr4_clear_bits(X86_CR4_VMXE);
2440
2441         return -EFAULT;
2442 }
2443
2444 static int vmx_hardware_enable(void)
2445 {
2446         int cpu = raw_smp_processor_id();
2447         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2448         int r;
2449
2450         if (cr4_read_shadow() & X86_CR4_VMXE)
2451                 return -EBUSY;
2452
2453         /*
2454          * This can happen if we hot-added a CPU but failed to allocate
2455          * VP assist page for it.
2456          */
2457         if (static_branch_unlikely(&enable_evmcs) &&
2458             !hv_get_vp_assist_page(cpu))
2459                 return -EFAULT;
2460
2461         intel_pt_handle_vmx(1);
2462
2463         r = kvm_cpu_vmxon(phys_addr);
2464         if (r) {
2465                 intel_pt_handle_vmx(0);
2466                 return r;
2467         }
2468
2469         if (enable_ept)
2470                 ept_sync_global();
2471
2472         return 0;
2473 }
2474
2475 static void vmclear_local_loaded_vmcss(void)
2476 {
2477         int cpu = raw_smp_processor_id();
2478         struct loaded_vmcs *v, *n;
2479
2480         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2481                                  loaded_vmcss_on_cpu_link)
2482                 __loaded_vmcs_clear(v);
2483 }
2484
2485 static void vmx_hardware_disable(void)
2486 {
2487         vmclear_local_loaded_vmcss();
2488
2489         if (cpu_vmxoff())
2490                 kvm_spurious_fault();
2491
2492         intel_pt_handle_vmx(0);
2493 }
2494
2495 /*
2496  * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2497  * directly instead of going through cpu_has(), to ensure KVM is trapping
2498  * ENCLS whenever it's supported in hardware.  It does not matter whether
2499  * the host OS supports or has enabled SGX.
2500  */
2501 static bool cpu_has_sgx(void)
2502 {
2503         return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2504 }
2505
2506 /*
2507  * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2508  * can't be used due to errata where VM Exit may incorrectly clear
2509  * IA32_PERF_GLOBAL_CTRL[34:32]. Work around the errata by using the
2510  * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2511  */
2512 static bool cpu_has_perf_global_ctrl_bug(void)
2513 {
2514         if (boot_cpu_data.x86 == 0x6) {
2515                 switch (boot_cpu_data.x86_model) {
2516                 case INTEL_FAM6_NEHALEM_EP:     /* AAK155 */
2517                 case INTEL_FAM6_NEHALEM:        /* AAP115 */
2518                 case INTEL_FAM6_WESTMERE:       /* AAT100 */
2519                 case INTEL_FAM6_WESTMERE_EP:    /* BC86,AAY89,BD102 */
2520                 case INTEL_FAM6_NEHALEM_EX:     /* BA97 */
2521                         return true;
2522                 default:
2523                         break;
2524                 }
2525         }
2526
2527         return false;
2528 }
2529
2530 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2531                                       u32 msr, u32 *result)
2532 {
2533         u32 vmx_msr_low, vmx_msr_high;
2534         u32 ctl = ctl_min | ctl_opt;
2535
2536         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2537
2538         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2539         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2540
2541         /* Ensure minimum (required) set of control bits are supported. */
2542         if (ctl_min & ~ctl)
2543                 return -EIO;
2544
2545         *result = ctl;
2546         return 0;
2547 }
2548
2549 static __init u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
2550 {
2551         u64 allowed;
2552
2553         rdmsrl(msr, allowed);
2554
2555         return  ctl_opt & allowed;
2556 }
2557
2558 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2559                                     struct vmx_capability *vmx_cap)
2560 {
2561         u32 vmx_msr_low, vmx_msr_high;
2562         u32 _pin_based_exec_control = 0;
2563         u32 _cpu_based_exec_control = 0;
2564         u32 _cpu_based_2nd_exec_control = 0;
2565         u64 _cpu_based_3rd_exec_control = 0;
2566         u32 _vmexit_control = 0;
2567         u32 _vmentry_control = 0;
2568         u64 misc_msr;
2569         int i;
2570
2571         /*
2572          * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory.
2573          * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always
2574          * intercepts writes to PAT and EFER, i.e. never enables those controls.
2575          */
2576         struct {
2577                 u32 entry_control;
2578                 u32 exit_control;
2579         } const vmcs_entry_exit_pairs[] = {
2580                 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,  VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL },
2581                 { VM_ENTRY_LOAD_IA32_PAT,               VM_EXIT_LOAD_IA32_PAT },
2582                 { VM_ENTRY_LOAD_IA32_EFER,              VM_EXIT_LOAD_IA32_EFER },
2583                 { VM_ENTRY_LOAD_BNDCFGS,                VM_EXIT_CLEAR_BNDCFGS },
2584                 { VM_ENTRY_LOAD_IA32_RTIT_CTL,          VM_EXIT_CLEAR_IA32_RTIT_CTL },
2585         };
2586
2587         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2588
2589         if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
2590                                 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL,
2591                                 MSR_IA32_VMX_PROCBASED_CTLS,
2592                                 &_cpu_based_exec_control))
2593                 return -EIO;
2594         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2595                 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL,
2596                                         KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL,
2597                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2598                                         &_cpu_based_2nd_exec_control))
2599                         return -EIO;
2600         }
2601 #ifndef CONFIG_X86_64
2602         if (!(_cpu_based_2nd_exec_control &
2603                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2604                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2605 #endif
2606
2607         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2608                 _cpu_based_2nd_exec_control &= ~(
2609                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2610                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2611                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2612
2613         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2614                 &vmx_cap->ept, &vmx_cap->vpid);
2615
2616         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
2617             vmx_cap->ept) {
2618                 pr_warn_once("EPT CAP should not exist if not support "
2619                                 "1-setting enable EPT VM-execution control\n");
2620
2621                 if (error_on_inconsistent_vmcs_config)
2622                         return -EIO;
2623
2624                 vmx_cap->ept = 0;
2625         }
2626         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2627             vmx_cap->vpid) {
2628                 pr_warn_once("VPID CAP should not exist if not support "
2629                                 "1-setting enable VPID VM-execution control\n");
2630
2631                 if (error_on_inconsistent_vmcs_config)
2632                         return -EIO;
2633
2634                 vmx_cap->vpid = 0;
2635         }
2636
2637         if (!cpu_has_sgx())
2638                 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING;
2639
2640         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS)
2641                 _cpu_based_3rd_exec_control =
2642                         adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL,
2643                                               MSR_IA32_VMX_PROCBASED_CTLS3);
2644
2645         if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS,
2646                                 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS,
2647                                 MSR_IA32_VMX_EXIT_CTLS,
2648                                 &_vmexit_control))
2649                 return -EIO;
2650
2651         if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL,
2652                                 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL,
2653                                 MSR_IA32_VMX_PINBASED_CTLS,
2654                                 &_pin_based_exec_control))
2655                 return -EIO;
2656
2657         if (cpu_has_broken_vmx_preemption_timer())
2658                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2659         if (!(_cpu_based_2nd_exec_control &
2660                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2661                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2662
2663         if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS,
2664                                 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS,
2665                                 MSR_IA32_VMX_ENTRY_CTLS,
2666                                 &_vmentry_control))
2667                 return -EIO;
2668
2669         for (i = 0; i < ARRAY_SIZE(vmcs_entry_exit_pairs); i++) {
2670                 u32 n_ctrl = vmcs_entry_exit_pairs[i].entry_control;
2671                 u32 x_ctrl = vmcs_entry_exit_pairs[i].exit_control;
2672
2673                 if (!(_vmentry_control & n_ctrl) == !(_vmexit_control & x_ctrl))
2674                         continue;
2675
2676                 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, entry = %x, exit = %x\n",
2677                              _vmentry_control & n_ctrl, _vmexit_control & x_ctrl);
2678
2679                 if (error_on_inconsistent_vmcs_config)
2680                         return -EIO;
2681
2682                 _vmentry_control &= ~n_ctrl;
2683                 _vmexit_control &= ~x_ctrl;
2684         }
2685
2686         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2687
2688         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2689         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2690                 return -EIO;
2691
2692 #ifdef CONFIG_X86_64
2693         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2694         if (vmx_msr_high & (1u<<16))
2695                 return -EIO;
2696 #endif
2697
2698         /* Require Write-Back (WB) memory type for VMCS accesses. */
2699         if (((vmx_msr_high >> 18) & 15) != 6)
2700                 return -EIO;
2701
2702         rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
2703
2704         vmcs_conf->size = vmx_msr_high & 0x1fff;
2705         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2706
2707         vmcs_conf->revision_id = vmx_msr_low;
2708
2709         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2710         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2711         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2712         vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
2713         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2714         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2715         vmcs_conf->misc = misc_msr;
2716
2717         return 0;
2718 }
2719
2720 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2721 {
2722         int node = cpu_to_node(cpu);
2723         struct page *pages;
2724         struct vmcs *vmcs;
2725
2726         pages = __alloc_pages_node(node, flags, 0);
2727         if (!pages)
2728                 return NULL;
2729         vmcs = page_address(pages);
2730         memset(vmcs, 0, vmcs_config.size);
2731
2732         /* KVM supports Enlightened VMCS v1 only */
2733         if (static_branch_unlikely(&enable_evmcs))
2734                 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2735         else
2736                 vmcs->hdr.revision_id = vmcs_config.revision_id;
2737
2738         if (shadow)
2739                 vmcs->hdr.shadow_vmcs = 1;
2740         return vmcs;
2741 }
2742
2743 void free_vmcs(struct vmcs *vmcs)
2744 {
2745         free_page((unsigned long)vmcs);
2746 }
2747
2748 /*
2749  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2750  */
2751 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2752 {
2753         if (!loaded_vmcs->vmcs)
2754                 return;
2755         loaded_vmcs_clear(loaded_vmcs);
2756         free_vmcs(loaded_vmcs->vmcs);
2757         loaded_vmcs->vmcs = NULL;
2758         if (loaded_vmcs->msr_bitmap)
2759                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2760         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2761 }
2762
2763 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2764 {
2765         loaded_vmcs->vmcs = alloc_vmcs(false);
2766         if (!loaded_vmcs->vmcs)
2767                 return -ENOMEM;
2768
2769         vmcs_clear(loaded_vmcs->vmcs);
2770
2771         loaded_vmcs->shadow_vmcs = NULL;
2772         loaded_vmcs->hv_timer_soft_disabled = false;
2773         loaded_vmcs->cpu = -1;
2774         loaded_vmcs->launched = 0;
2775
2776         if (cpu_has_vmx_msr_bitmap()) {
2777                 loaded_vmcs->msr_bitmap = (unsigned long *)
2778                                 __get_free_page(GFP_KERNEL_ACCOUNT);
2779                 if (!loaded_vmcs->msr_bitmap)
2780                         goto out_vmcs;
2781                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2782         }
2783
2784         memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2785         memset(&loaded_vmcs->controls_shadow, 0,
2786                 sizeof(struct vmcs_controls_shadow));
2787
2788         return 0;
2789
2790 out_vmcs:
2791         free_loaded_vmcs(loaded_vmcs);
2792         return -ENOMEM;
2793 }
2794
2795 static void free_kvm_area(void)
2796 {
2797         int cpu;
2798
2799         for_each_possible_cpu(cpu) {
2800                 free_vmcs(per_cpu(vmxarea, cpu));
2801                 per_cpu(vmxarea, cpu) = NULL;
2802         }
2803 }
2804
2805 static __init int alloc_kvm_area(void)
2806 {
2807         int cpu;
2808
2809         for_each_possible_cpu(cpu) {
2810                 struct vmcs *vmcs;
2811
2812                 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2813                 if (!vmcs) {
2814                         free_kvm_area();
2815                         return -ENOMEM;
2816                 }
2817
2818                 /*
2819                  * When eVMCS is enabled, alloc_vmcs_cpu() sets
2820                  * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2821                  * revision_id reported by MSR_IA32_VMX_BASIC.
2822                  *
2823                  * However, even though not explicitly documented by
2824                  * TLFS, VMXArea passed as VMXON argument should
2825                  * still be marked with revision_id reported by
2826                  * physical CPU.
2827                  */
2828                 if (static_branch_unlikely(&enable_evmcs))
2829                         vmcs->hdr.revision_id = vmcs_config.revision_id;
2830
2831                 per_cpu(vmxarea, cpu) = vmcs;
2832         }
2833         return 0;
2834 }
2835
2836 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2837                 struct kvm_segment *save)
2838 {
2839         if (!emulate_invalid_guest_state) {
2840                 /*
2841                  * CS and SS RPL should be equal during guest entry according
2842                  * to VMX spec, but in reality it is not always so. Since vcpu
2843                  * is in the middle of the transition from real mode to
2844                  * protected mode it is safe to assume that RPL 0 is a good
2845                  * default value.
2846                  */
2847                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2848                         save->selector &= ~SEGMENT_RPL_MASK;
2849                 save->dpl = save->selector & SEGMENT_RPL_MASK;
2850                 save->s = 1;
2851         }
2852         __vmx_set_segment(vcpu, save, seg);
2853 }
2854
2855 static void enter_pmode(struct kvm_vcpu *vcpu)
2856 {
2857         unsigned long flags;
2858         struct vcpu_vmx *vmx = to_vmx(vcpu);
2859
2860         /*
2861          * Update real mode segment cache. It may be not up-to-date if segment
2862          * register was written while vcpu was in a guest mode.
2863          */
2864         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2865         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2866         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2867         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2868         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2869         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2870
2871         vmx->rmode.vm86_active = 0;
2872
2873         __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2874
2875         flags = vmcs_readl(GUEST_RFLAGS);
2876         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2877         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2878         vmcs_writel(GUEST_RFLAGS, flags);
2879
2880         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2881                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2882
2883         vmx_update_exception_bitmap(vcpu);
2884
2885         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2886         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2887         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2888         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2889         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2890         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2891 }
2892
2893 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2894 {
2895         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2896         struct kvm_segment var = *save;
2897
2898         var.dpl = 0x3;
2899         if (seg == VCPU_SREG_CS)
2900                 var.type = 0x3;
2901
2902         if (!emulate_invalid_guest_state) {
2903                 var.selector = var.base >> 4;
2904                 var.base = var.base & 0xffff0;
2905                 var.limit = 0xffff;
2906                 var.g = 0;
2907                 var.db = 0;
2908                 var.present = 1;
2909                 var.s = 1;
2910                 var.l = 0;
2911                 var.unusable = 0;
2912                 var.type = 0x3;
2913                 var.avl = 0;
2914                 if (save->base & 0xf)
2915                         printk_once(KERN_WARNING "kvm: segment base is not "
2916                                         "paragraph aligned when entering "
2917                                         "protected mode (seg=%d)", seg);
2918         }
2919
2920         vmcs_write16(sf->selector, var.selector);
2921         vmcs_writel(sf->base, var.base);
2922         vmcs_write32(sf->limit, var.limit);
2923         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2924 }
2925
2926 static void enter_rmode(struct kvm_vcpu *vcpu)
2927 {
2928         unsigned long flags;
2929         struct vcpu_vmx *vmx = to_vmx(vcpu);
2930         struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2931
2932         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2933         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2934         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2935         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2936         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2937         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2938         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2939
2940         vmx->rmode.vm86_active = 1;
2941
2942         /*
2943          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2944          * vcpu. Warn the user that an update is overdue.
2945          */
2946         if (!kvm_vmx->tss_addr)
2947                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2948                              "called before entering vcpu\n");
2949
2950         vmx_segment_cache_clear(vmx);
2951
2952         vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2953         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2954         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2955
2956         flags = vmcs_readl(GUEST_RFLAGS);
2957         vmx->rmode.save_rflags = flags;
2958
2959         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2960
2961         vmcs_writel(GUEST_RFLAGS, flags);
2962         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2963         vmx_update_exception_bitmap(vcpu);
2964
2965         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2966         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2967         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2968         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2969         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2970         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2971 }
2972
2973 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2974 {
2975         struct vcpu_vmx *vmx = to_vmx(vcpu);
2976
2977         /* Nothing to do if hardware doesn't support EFER. */
2978         if (!vmx_find_uret_msr(vmx, MSR_EFER))
2979                 return 0;
2980
2981         vcpu->arch.efer = efer;
2982 #ifdef CONFIG_X86_64
2983         if (efer & EFER_LMA)
2984                 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE);
2985         else
2986                 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE);
2987 #else
2988         if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm))
2989                 return 1;
2990 #endif
2991
2992         vmx_setup_uret_msrs(vmx);
2993         return 0;
2994 }
2995
2996 #ifdef CONFIG_X86_64
2997
2998 static void enter_lmode(struct kvm_vcpu *vcpu)
2999 {
3000         u32 guest_tr_ar;
3001
3002         vmx_segment_cache_clear(to_vmx(vcpu));
3003
3004         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
3005         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
3006                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
3007                                      __func__);
3008                 vmcs_write32(GUEST_TR_AR_BYTES,
3009                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
3010                              | VMX_AR_TYPE_BUSY_64_TSS);
3011         }
3012         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
3013 }
3014
3015 static void exit_lmode(struct kvm_vcpu *vcpu)
3016 {
3017         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
3018 }
3019
3020 #endif
3021
3022 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
3023 {
3024         struct vcpu_vmx *vmx = to_vmx(vcpu);
3025
3026         /*
3027          * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
3028          * the CPU is not required to invalidate guest-physical mappings on
3029          * VM-Entry, even if VPID is disabled.  Guest-physical mappings are
3030          * associated with the root EPT structure and not any particular VPID
3031          * (INVVPID also isn't required to invalidate guest-physical mappings).
3032          */
3033         if (enable_ept) {
3034                 ept_sync_global();
3035         } else if (enable_vpid) {
3036                 if (cpu_has_vmx_invvpid_global()) {
3037                         vpid_sync_vcpu_global();
3038                 } else {
3039                         vpid_sync_vcpu_single(vmx->vpid);
3040                         vpid_sync_vcpu_single(vmx->nested.vpid02);
3041                 }
3042         }
3043 }
3044
3045 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu)
3046 {
3047         if (is_guest_mode(vcpu))
3048                 return nested_get_vpid02(vcpu);
3049         return to_vmx(vcpu)->vpid;
3050 }
3051
3052 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
3053 {
3054         struct kvm_mmu *mmu = vcpu->arch.mmu;
3055         u64 root_hpa = mmu->root.hpa;
3056
3057         /* No flush required if the current context is invalid. */
3058         if (!VALID_PAGE(root_hpa))
3059                 return;
3060
3061         if (enable_ept)
3062                 ept_sync_context(construct_eptp(vcpu, root_hpa,
3063                                                 mmu->root_role.level));
3064         else
3065                 vpid_sync_context(vmx_get_current_vpid(vcpu));
3066 }
3067
3068 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
3069 {
3070         /*
3071          * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in
3072          * vmx_flush_tlb_guest() for an explanation of why this is ok.
3073          */
3074         vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
3075 }
3076
3077 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
3078 {
3079         /*
3080          * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
3081          * vpid couldn't be allocated for this vCPU.  VM-Enter and VM-Exit are
3082          * required to flush GVA->{G,H}PA mappings from the TLB if vpid is
3083          * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
3084          * i.e. no explicit INVVPID is necessary.
3085          */
3086         vpid_sync_context(vmx_get_current_vpid(vcpu));
3087 }
3088
3089 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
3090 {
3091         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3092
3093         if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
3094                 return;
3095
3096         if (is_pae_paging(vcpu)) {
3097                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
3098                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
3099                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
3100                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
3101         }
3102 }
3103
3104 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
3105 {
3106         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
3107
3108         if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
3109                 return;
3110
3111         mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
3112         mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
3113         mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
3114         mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
3115
3116         kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR);
3117 }
3118
3119 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \
3120                           CPU_BASED_CR3_STORE_EXITING)
3121
3122 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3123 {
3124         struct vcpu_vmx *vmx = to_vmx(vcpu);
3125         unsigned long hw_cr0, old_cr0_pg;
3126         u32 tmp;
3127
3128         old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG);
3129
3130         hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3131         if (is_unrestricted_guest(vcpu))
3132                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3133         else {
3134                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3135                 if (!enable_ept)
3136                         hw_cr0 |= X86_CR0_WP;
3137
3138                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3139                         enter_pmode(vcpu);
3140
3141                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3142                         enter_rmode(vcpu);
3143         }
3144
3145         vmcs_writel(CR0_READ_SHADOW, cr0);
3146         vmcs_writel(GUEST_CR0, hw_cr0);
3147         vcpu->arch.cr0 = cr0;
3148         kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3149
3150 #ifdef CONFIG_X86_64
3151         if (vcpu->arch.efer & EFER_LME) {
3152                 if (!old_cr0_pg && (cr0 & X86_CR0_PG))
3153                         enter_lmode(vcpu);
3154                 else if (old_cr0_pg && !(cr0 & X86_CR0_PG))
3155                         exit_lmode(vcpu);
3156         }
3157 #endif
3158
3159         if (enable_ept && !is_unrestricted_guest(vcpu)) {
3160                 /*
3161                  * Ensure KVM has an up-to-date snapshot of the guest's CR3.  If
3162                  * the below code _enables_ CR3 exiting, vmx_cache_reg() will
3163                  * (correctly) stop reading vmcs.GUEST_CR3 because it thinks
3164                  * KVM's CR3 is installed.
3165                  */
3166                 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3167                         vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3168
3169                 /*
3170                  * When running with EPT but not unrestricted guest, KVM must
3171                  * intercept CR3 accesses when paging is _disabled_.  This is
3172                  * necessary because restricted guests can't actually run with
3173                  * paging disabled, and so KVM stuffs its own CR3 in order to
3174                  * run the guest when identity mapped page tables.
3175                  *
3176                  * Do _NOT_ check the old CR0.PG, e.g. to optimize away the
3177                  * update, it may be stale with respect to CR3 interception,
3178                  * e.g. after nested VM-Enter.
3179                  *
3180                  * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or
3181                  * stores to forward them to L1, even if KVM does not need to
3182                  * intercept them to preserve its identity mapped page tables.
3183                  */
3184                 if (!(cr0 & X86_CR0_PG)) {
3185                         exec_controls_setbit(vmx, CR3_EXITING_BITS);
3186                 } else if (!is_guest_mode(vcpu)) {
3187                         exec_controls_clearbit(vmx, CR3_EXITING_BITS);
3188                 } else {
3189                         tmp = exec_controls_get(vmx);
3190                         tmp &= ~CR3_EXITING_BITS;
3191                         tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS;
3192                         exec_controls_set(vmx, tmp);
3193                 }
3194
3195                 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */
3196                 if ((old_cr0_pg ^ cr0) & X86_CR0_PG)
3197                         vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3198
3199                 /*
3200                  * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but
3201                  * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG.
3202                  */
3203                 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG))
3204                         kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3);
3205         }
3206
3207         /* depends on vcpu->arch.cr0 to be set to a new value */
3208         vmx->emulation_required = vmx_emulation_required(vcpu);
3209 }
3210
3211 static int vmx_get_max_tdp_level(void)
3212 {
3213         if (cpu_has_vmx_ept_5levels())
3214                 return 5;
3215         return 4;
3216 }
3217
3218 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3219 {
3220         u64 eptp = VMX_EPTP_MT_WB;
3221
3222         eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3223
3224         if (enable_ept_ad_bits &&
3225             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3226                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3227         eptp |= root_hpa;
3228
3229         return eptp;
3230 }
3231
3232 static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3233                              int root_level)
3234 {
3235         struct kvm *kvm = vcpu->kvm;
3236         bool update_guest_cr3 = true;
3237         unsigned long guest_cr3;
3238         u64 eptp;
3239
3240         if (enable_ept) {
3241                 eptp = construct_eptp(vcpu, root_hpa, root_level);
3242                 vmcs_write64(EPT_POINTER, eptp);
3243
3244                 hv_track_root_tdp(vcpu, root_hpa);
3245
3246                 if (!enable_unrestricted_guest && !is_paging(vcpu))
3247                         guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3248                 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3))
3249                         guest_cr3 = vcpu->arch.cr3;
3250                 else /* vmcs.GUEST_CR3 is already up-to-date. */
3251                         update_guest_cr3 = false;
3252                 vmx_ept_load_pdptrs(vcpu);
3253         } else {
3254                 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3255         }
3256
3257         if (update_guest_cr3)
3258                 vmcs_writel(GUEST_CR3, guest_cr3);
3259 }
3260
3261
3262 static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3263 {
3264         /*
3265          * We operate under the default treatment of SMM, so VMX cannot be
3266          * enabled under SMM.  Note, whether or not VMXE is allowed at all,
3267          * i.e. is a reserved bit, is handled by common x86 code.
3268          */
3269         if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3270                 return false;
3271
3272         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3273                 return false;
3274
3275         return true;
3276 }
3277
3278 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3279 {
3280         unsigned long old_cr4 = vcpu->arch.cr4;
3281         struct vcpu_vmx *vmx = to_vmx(vcpu);
3282         /*
3283          * Pass through host's Machine Check Enable value to hw_cr4, which
3284          * is in force while we are in guest mode.  Do not let guests control
3285          * this bit, even if host CR4.MCE == 0.
3286          */
3287         unsigned long hw_cr4;
3288
3289         hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3290         if (is_unrestricted_guest(vcpu))
3291                 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3292         else if (vmx->rmode.vm86_active)
3293                 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3294         else
3295                 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3296
3297         if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3298                 if (cr4 & X86_CR4_UMIP) {
3299                         secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3300                         hw_cr4 &= ~X86_CR4_UMIP;
3301                 } else if (!is_guest_mode(vcpu) ||
3302                         !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3303                         secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3304                 }
3305         }
3306
3307         vcpu->arch.cr4 = cr4;
3308         kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3309
3310         if (!is_unrestricted_guest(vcpu)) {
3311                 if (enable_ept) {
3312                         if (!is_paging(vcpu)) {
3313                                 hw_cr4 &= ~X86_CR4_PAE;
3314                                 hw_cr4 |= X86_CR4_PSE;
3315                         } else if (!(cr4 & X86_CR4_PAE)) {
3316                                 hw_cr4 &= ~X86_CR4_PAE;
3317                         }
3318                 }
3319
3320                 /*
3321                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3322                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
3323                  * to be manually disabled when guest switches to non-paging
3324                  * mode.
3325                  *
3326                  * If !enable_unrestricted_guest, the CPU is always running
3327                  * with CR0.PG=1 and CR4 needs to be modified.
3328                  * If enable_unrestricted_guest, the CPU automatically
3329                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3330                  */
3331                 if (!is_paging(vcpu))
3332                         hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3333         }
3334
3335         vmcs_writel(CR4_READ_SHADOW, cr4);
3336         vmcs_writel(GUEST_CR4, hw_cr4);
3337
3338         if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3339                 kvm_update_cpuid_runtime(vcpu);
3340 }
3341
3342 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3343 {
3344         struct vcpu_vmx *vmx = to_vmx(vcpu);
3345         u32 ar;
3346
3347         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3348                 *var = vmx->rmode.segs[seg];
3349                 if (seg == VCPU_SREG_TR
3350                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3351                         return;
3352                 var->base = vmx_read_guest_seg_base(vmx, seg);
3353                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
3354                 return;
3355         }
3356         var->base = vmx_read_guest_seg_base(vmx, seg);
3357         var->limit = vmx_read_guest_seg_limit(vmx, seg);
3358         var->selector = vmx_read_guest_seg_selector(vmx, seg);
3359         ar = vmx_read_guest_seg_ar(vmx, seg);
3360         var->unusable = (ar >> 16) & 1;
3361         var->type = ar & 15;
3362         var->s = (ar >> 4) & 1;
3363         var->dpl = (ar >> 5) & 3;
3364         /*
3365          * Some userspaces do not preserve unusable property. Since usable
3366          * segment has to be present according to VMX spec we can use present
3367          * property to amend userspace bug by making unusable segment always
3368          * nonpresent. vmx_segment_access_rights() already marks nonpresent
3369          * segment as unusable.
3370          */
3371         var->present = !var->unusable;
3372         var->avl = (ar >> 12) & 1;
3373         var->l = (ar >> 13) & 1;
3374         var->db = (ar >> 14) & 1;
3375         var->g = (ar >> 15) & 1;
3376 }
3377
3378 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3379 {
3380         struct kvm_segment s;
3381
3382         if (to_vmx(vcpu)->rmode.vm86_active) {
3383                 vmx_get_segment(vcpu, &s, seg);
3384                 return s.base;
3385         }
3386         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3387 }
3388
3389 int vmx_get_cpl(struct kvm_vcpu *vcpu)
3390 {
3391         struct vcpu_vmx *vmx = to_vmx(vcpu);
3392
3393         if (unlikely(vmx->rmode.vm86_active))
3394                 return 0;
3395         else {
3396                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3397                 return VMX_AR_DPL(ar);
3398         }
3399 }
3400
3401 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3402 {
3403         u32 ar;
3404
3405         if (var->unusable || !var->present)
3406                 ar = 1 << 16;
3407         else {
3408                 ar = var->type & 15;
3409                 ar |= (var->s & 1) << 4;
3410                 ar |= (var->dpl & 3) << 5;
3411                 ar |= (var->present & 1) << 7;
3412                 ar |= (var->avl & 1) << 12;
3413                 ar |= (var->l & 1) << 13;
3414                 ar |= (var->db & 1) << 14;
3415                 ar |= (var->g & 1) << 15;
3416         }
3417
3418         return ar;
3419 }
3420
3421 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3422 {
3423         struct vcpu_vmx *vmx = to_vmx(vcpu);
3424         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3425
3426         vmx_segment_cache_clear(vmx);
3427
3428         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3429                 vmx->rmode.segs[seg] = *var;
3430                 if (seg == VCPU_SREG_TR)
3431                         vmcs_write16(sf->selector, var->selector);
3432                 else if (var->s)
3433                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3434                 return;
3435         }
3436
3437         vmcs_writel(sf->base, var->base);
3438         vmcs_write32(sf->limit, var->limit);
3439         vmcs_write16(sf->selector, var->selector);
3440
3441         /*
3442          *   Fix the "Accessed" bit in AR field of segment registers for older
3443          * qemu binaries.
3444          *   IA32 arch specifies that at the time of processor reset the
3445          * "Accessed" bit in the AR field of segment registers is 1. And qemu
3446          * is setting it to 0 in the userland code. This causes invalid guest
3447          * state vmexit when "unrestricted guest" mode is turned on.
3448          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3449          * tree. Newer qemu binaries with that qemu fix would not need this
3450          * kvm hack.
3451          */
3452         if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3453                 var->type |= 0x1; /* Accessed */
3454
3455         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3456 }
3457
3458 static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3459 {
3460         __vmx_set_segment(vcpu, var, seg);
3461
3462         to_vmx(vcpu)->emulation_required = vmx_emulation_required(vcpu);
3463 }
3464
3465 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3466 {
3467         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3468
3469         *db = (ar >> 14) & 1;
3470         *l = (ar >> 13) & 1;
3471 }
3472
3473 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3474 {
3475         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3476         dt->address = vmcs_readl(GUEST_IDTR_BASE);
3477 }
3478
3479 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3480 {
3481         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3482         vmcs_writel(GUEST_IDTR_BASE, dt->address);
3483 }
3484
3485 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3486 {
3487         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3488         dt->address = vmcs_readl(GUEST_GDTR_BASE);
3489 }
3490
3491 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3492 {
3493         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3494         vmcs_writel(GUEST_GDTR_BASE, dt->address);
3495 }
3496
3497 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3498 {
3499         struct kvm_segment var;
3500         u32 ar;
3501
3502         vmx_get_segment(vcpu, &var, seg);
3503         var.dpl = 0x3;
3504         if (seg == VCPU_SREG_CS)
3505                 var.type = 0x3;
3506         ar = vmx_segment_access_rights(&var);
3507
3508         if (var.base != (var.selector << 4))
3509                 return false;
3510         if (var.limit != 0xffff)
3511                 return false;
3512         if (ar != 0xf3)
3513                 return false;
3514
3515         return true;
3516 }
3517
3518 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3519 {
3520         struct kvm_segment cs;
3521         unsigned int cs_rpl;
3522
3523         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3524         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3525
3526         if (cs.unusable)
3527                 return false;
3528         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3529                 return false;
3530         if (!cs.s)
3531                 return false;
3532         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3533                 if (cs.dpl > cs_rpl)
3534                         return false;
3535         } else {
3536                 if (cs.dpl != cs_rpl)
3537                         return false;
3538         }
3539         if (!cs.present)
3540                 return false;
3541
3542         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3543         return true;
3544 }
3545
3546 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3547 {
3548         struct kvm_segment ss;
3549         unsigned int ss_rpl;
3550
3551         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3552         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3553
3554         if (ss.unusable)
3555                 return true;
3556         if (ss.type != 3 && ss.type != 7)
3557                 return false;
3558         if (!ss.s)
3559                 return false;
3560         if (ss.dpl != ss_rpl) /* DPL != RPL */
3561                 return false;
3562         if (!ss.present)
3563                 return false;
3564
3565         return true;
3566 }
3567
3568 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3569 {
3570         struct kvm_segment var;
3571         unsigned int rpl;
3572
3573         vmx_get_segment(vcpu, &var, seg);
3574         rpl = var.selector & SEGMENT_RPL_MASK;
3575
3576         if (var.unusable)
3577                 return true;
3578         if (!var.s)
3579                 return false;
3580         if (!var.present)
3581                 return false;
3582         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3583                 if (var.dpl < rpl) /* DPL < RPL */
3584                         return false;
3585         }
3586
3587         /* TODO: Add other members to kvm_segment_field to allow checking for other access
3588          * rights flags
3589          */
3590         return true;
3591 }
3592
3593 static bool tr_valid(struct kvm_vcpu *vcpu)
3594 {
3595         struct kvm_segment tr;
3596
3597         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3598
3599         if (tr.unusable)
3600                 return false;
3601         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
3602                 return false;
3603         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3604                 return false;
3605         if (!tr.present)
3606                 return false;
3607
3608         return true;
3609 }
3610
3611 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3612 {
3613         struct kvm_segment ldtr;
3614
3615         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3616
3617         if (ldtr.unusable)
3618                 return true;
3619         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
3620                 return false;
3621         if (ldtr.type != 2)
3622                 return false;
3623         if (!ldtr.present)
3624                 return false;
3625
3626         return true;
3627 }
3628
3629 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3630 {
3631         struct kvm_segment cs, ss;
3632
3633         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3634         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3635
3636         return ((cs.selector & SEGMENT_RPL_MASK) ==
3637                  (ss.selector & SEGMENT_RPL_MASK));
3638 }
3639
3640 /*
3641  * Check if guest state is valid. Returns true if valid, false if
3642  * not.
3643  * We assume that registers are always usable
3644  */
3645 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3646 {
3647         /* real mode guest state checks */
3648         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3649                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3650                         return false;
3651                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3652                         return false;
3653                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3654                         return false;
3655                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3656                         return false;
3657                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3658                         return false;
3659                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3660                         return false;
3661         } else {
3662         /* protected mode guest state checks */
3663                 if (!cs_ss_rpl_check(vcpu))
3664                         return false;
3665                 if (!code_segment_valid(vcpu))
3666                         return false;
3667                 if (!stack_segment_valid(vcpu))
3668                         return false;
3669                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3670                         return false;
3671                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3672                         return false;
3673                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3674                         return false;
3675                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3676                         return false;
3677                 if (!tr_valid(vcpu))
3678                         return false;
3679                 if (!ldtr_valid(vcpu))
3680                         return false;
3681         }
3682         /* TODO:
3683          * - Add checks on RIP
3684          * - Add checks on RFLAGS
3685          */
3686
3687         return true;
3688 }
3689
3690 static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3691 {
3692         const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3693         u16 data;
3694         int i;
3695
3696         for (i = 0; i < 3; i++) {
3697                 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3698                         return -EFAULT;
3699         }
3700
3701         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3702         if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3703                 return -EFAULT;
3704
3705         data = ~0;
3706         if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3707                 return -EFAULT;
3708
3709         return 0;
3710 }
3711
3712 static int init_rmode_identity_map(struct kvm *kvm)
3713 {
3714         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3715         int i, r = 0;
3716         void __user *uaddr;
3717         u32 tmp;
3718
3719         /* Protect kvm_vmx->ept_identity_pagetable_done. */
3720         mutex_lock(&kvm->slots_lock);
3721
3722         if (likely(kvm_vmx->ept_identity_pagetable_done))
3723                 goto out;
3724
3725         if (!kvm_vmx->ept_identity_map_addr)
3726                 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3727
3728         uaddr = __x86_set_memory_region(kvm,
3729                                         IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3730                                         kvm_vmx->ept_identity_map_addr,
3731                                         PAGE_SIZE);
3732         if (IS_ERR(uaddr)) {
3733                 r = PTR_ERR(uaddr);
3734                 goto out;
3735         }
3736
3737         /* Set up identity-mapping pagetable for EPT in real mode */
3738         for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) {
3739                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3740                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3741                 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3742                         r = -EFAULT;
3743                         goto out;
3744                 }
3745         }
3746         kvm_vmx->ept_identity_pagetable_done = true;
3747
3748 out:
3749         mutex_unlock(&kvm->slots_lock);
3750         return r;
3751 }
3752
3753 static void seg_setup(int seg)
3754 {
3755         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3756         unsigned int ar;
3757
3758         vmcs_write16(sf->selector, 0);
3759         vmcs_writel(sf->base, 0);
3760         vmcs_write32(sf->limit, 0xffff);
3761         ar = 0x93;
3762         if (seg == VCPU_SREG_CS)
3763                 ar |= 0x08; /* code segment */
3764
3765         vmcs_write32(sf->ar_bytes, ar);
3766 }
3767
3768 static int alloc_apic_access_page(struct kvm *kvm)
3769 {
3770         struct page *page;
3771         void __user *hva;
3772         int ret = 0;
3773
3774         mutex_lock(&kvm->slots_lock);
3775         if (kvm->arch.apic_access_memslot_enabled)
3776                 goto out;
3777         hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3778                                       APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3779         if (IS_ERR(hva)) {
3780                 ret = PTR_ERR(hva);
3781                 goto out;
3782         }
3783
3784         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3785         if (is_error_page(page)) {
3786                 ret = -EFAULT;
3787                 goto out;
3788         }
3789
3790         /*
3791          * Do not pin the page in memory, so that memory hot-unplug
3792          * is able to migrate it.
3793          */
3794         put_page(page);
3795         kvm->arch.apic_access_memslot_enabled = true;
3796 out:
3797         mutex_unlock(&kvm->slots_lock);
3798         return ret;
3799 }
3800
3801 int allocate_vpid(void)
3802 {
3803         int vpid;
3804
3805         if (!enable_vpid)
3806                 return 0;
3807         spin_lock(&vmx_vpid_lock);
3808         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3809         if (vpid < VMX_NR_VPIDS)
3810                 __set_bit(vpid, vmx_vpid_bitmap);
3811         else
3812                 vpid = 0;
3813         spin_unlock(&vmx_vpid_lock);
3814         return vpid;
3815 }
3816
3817 void free_vpid(int vpid)
3818 {
3819         if (!enable_vpid || vpid == 0)
3820                 return;
3821         spin_lock(&vmx_vpid_lock);
3822         __clear_bit(vpid, vmx_vpid_bitmap);
3823         spin_unlock(&vmx_vpid_lock);
3824 }
3825
3826 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
3827 {
3828         /*
3829          * When KVM is a nested hypervisor on top of Hyper-V and uses
3830          * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR
3831          * bitmap has changed.
3832          */
3833         if (static_branch_unlikely(&enable_evmcs))
3834                 evmcs_touch_msr_bitmap();
3835
3836         vmx->nested.force_msr_bitmap_recalc = true;
3837 }
3838
3839 void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3840 {
3841         struct vcpu_vmx *vmx = to_vmx(vcpu);
3842         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3843
3844         if (!cpu_has_vmx_msr_bitmap())
3845                 return;
3846
3847         vmx_msr_bitmap_l01_changed(vmx);
3848
3849         /*
3850          * Mark the desired intercept state in shadow bitmap, this is needed
3851          * for resync when the MSR filters change.
3852         */
3853         if (is_valid_passthrough_msr(msr)) {
3854                 int idx = possible_passthrough_msr_slot(msr);
3855
3856                 if (idx != -ENOENT) {
3857                         if (type & MSR_TYPE_R)
3858                                 clear_bit(idx, vmx->shadow_msr_intercept.read);
3859                         if (type & MSR_TYPE_W)
3860                                 clear_bit(idx, vmx->shadow_msr_intercept.write);
3861                 }
3862         }
3863
3864         if ((type & MSR_TYPE_R) &&
3865             !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3866                 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3867                 type &= ~MSR_TYPE_R;
3868         }
3869
3870         if ((type & MSR_TYPE_W) &&
3871             !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3872                 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3873                 type &= ~MSR_TYPE_W;
3874         }
3875
3876         if (type & MSR_TYPE_R)
3877                 vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3878
3879         if (type & MSR_TYPE_W)
3880                 vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3881 }
3882
3883 void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3884 {
3885         struct vcpu_vmx *vmx = to_vmx(vcpu);
3886         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3887
3888         if (!cpu_has_vmx_msr_bitmap())
3889                 return;
3890
3891         vmx_msr_bitmap_l01_changed(vmx);
3892
3893         /*
3894          * Mark the desired intercept state in shadow bitmap, this is needed
3895          * for resync when the MSR filter changes.
3896         */
3897         if (is_valid_passthrough_msr(msr)) {
3898                 int idx = possible_passthrough_msr_slot(msr);
3899
3900                 if (idx != -ENOENT) {
3901                         if (type & MSR_TYPE_R)
3902                                 set_bit(idx, vmx->shadow_msr_intercept.read);
3903                         if (type & MSR_TYPE_W)
3904                                 set_bit(idx, vmx->shadow_msr_intercept.write);
3905                 }
3906         }
3907
3908         if (type & MSR_TYPE_R)
3909                 vmx_set_msr_bitmap_read(msr_bitmap, msr);
3910
3911         if (type & MSR_TYPE_W)
3912                 vmx_set_msr_bitmap_write(msr_bitmap, msr);
3913 }
3914
3915 static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3916 {
3917         unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3918         unsigned long read_intercept;
3919         int msr;
3920
3921         read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3922
3923         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3924                 unsigned int read_idx = msr / BITS_PER_LONG;
3925                 unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3926
3927                 msr_bitmap[read_idx] = read_intercept;
3928                 msr_bitmap[write_idx] = ~0ul;
3929         }
3930 }
3931
3932 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu)
3933 {
3934         struct vcpu_vmx *vmx = to_vmx(vcpu);
3935         u8 mode;
3936
3937         if (!cpu_has_vmx_msr_bitmap())
3938                 return;
3939
3940         if (cpu_has_secondary_exec_ctrls() &&
3941             (secondary_exec_controls_get(vmx) &
3942              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3943                 mode = MSR_BITMAP_MODE_X2APIC;
3944                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3945                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3946         } else {
3947                 mode = 0;
3948         }
3949
3950         if (mode == vmx->x2apic_msr_bitmap_mode)
3951                 return;
3952
3953         vmx->x2apic_msr_bitmap_mode = mode;
3954
3955         vmx_reset_x2apic_msrs(vcpu, mode);
3956
3957         /*
3958          * TPR reads and writes can be virtualized even if virtual interrupt
3959          * delivery is not in use.
3960          */
3961         vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3962                                   !(mode & MSR_BITMAP_MODE_X2APIC));
3963
3964         if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3965                 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3966                 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3967                 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3968                 if (enable_ipiv)
3969                         vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW);
3970         }
3971 }
3972
3973 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3974 {
3975         struct vcpu_vmx *vmx = to_vmx(vcpu);
3976         bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3977         u32 i;
3978
3979         vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3980         vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3981         vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3982         vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3983         for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) {
3984                 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3985                 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3986         }
3987 }
3988
3989 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3990 {
3991         struct vcpu_vmx *vmx = to_vmx(vcpu);
3992         void *vapic_page;
3993         u32 vppr;
3994         int rvi;
3995
3996         if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3997                 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3998                 WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3999                 return false;
4000
4001         rvi = vmx_get_rvi();
4002
4003         vapic_page = vmx->nested.virtual_apic_map.hva;
4004         vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
4005
4006         return ((rvi & 0xf0) > (vppr & 0xf0));
4007 }
4008
4009 static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
4010 {
4011         struct vcpu_vmx *vmx = to_vmx(vcpu);
4012         u32 i;
4013
4014         /*
4015          * Redo intercept permissions for MSRs that KVM is passing through to
4016          * the guest.  Disabling interception will check the new MSR filter and
4017          * ensure that KVM enables interception if usersepace wants to filter
4018          * the MSR.  MSRs that KVM is already intercepting don't need to be
4019          * refreshed since KVM is going to intercept them regardless of what
4020          * userspace wants.
4021          */
4022         for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
4023                 u32 msr = vmx_possible_passthrough_msrs[i];
4024
4025                 if (!test_bit(i, vmx->shadow_msr_intercept.read))
4026                         vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_R);
4027
4028                 if (!test_bit(i, vmx->shadow_msr_intercept.write))
4029                         vmx_disable_intercept_for_msr(vcpu, msr, MSR_TYPE_W);
4030         }
4031
4032         /* PT MSRs can be passed through iff PT is exposed to the guest. */
4033         if (vmx_pt_mode_is_host_guest())
4034                 pt_update_intercept_for_msr(vcpu);
4035 }
4036
4037 static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
4038                                                      int pi_vec)
4039 {
4040 #ifdef CONFIG_SMP
4041         if (vcpu->mode == IN_GUEST_MODE) {
4042                 /*
4043                  * The vector of the virtual has already been set in the PIR.
4044                  * Send a notification event to deliver the virtual interrupt
4045                  * unless the vCPU is the currently running vCPU, i.e. the
4046                  * event is being sent from a fastpath VM-Exit handler, in
4047                  * which case the PIR will be synced to the vIRR before
4048                  * re-entering the guest.
4049                  *
4050                  * When the target is not the running vCPU, the following
4051                  * possibilities emerge:
4052                  *
4053                  * Case 1: vCPU stays in non-root mode. Sending a notification
4054                  * event posts the interrupt to the vCPU.
4055                  *
4056                  * Case 2: vCPU exits to root mode and is still runnable. The
4057                  * PIR will be synced to the vIRR before re-entering the guest.
4058                  * Sending a notification event is ok as the host IRQ handler
4059                  * will ignore the spurious event.
4060                  *
4061                  * Case 3: vCPU exits to root mode and is blocked. vcpu_block()
4062                  * has already synced PIR to vIRR and never blocks the vCPU if
4063                  * the vIRR is not empty. Therefore, a blocked vCPU here does
4064                  * not wait for any requested interrupts in PIR, and sending a
4065                  * notification event also results in a benign, spurious event.
4066                  */
4067
4068                 if (vcpu != kvm_get_running_vcpu())
4069                         apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
4070                 return;
4071         }
4072 #endif
4073         /*
4074          * The vCPU isn't in the guest; wake the vCPU in case it is blocking,
4075          * otherwise do nothing as KVM will grab the highest priority pending
4076          * IRQ via ->sync_pir_to_irr() in vcpu_enter_guest().
4077          */
4078         kvm_vcpu_wake_up(vcpu);
4079 }
4080
4081 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
4082                                                 int vector)
4083 {
4084         struct vcpu_vmx *vmx = to_vmx(vcpu);
4085
4086         if (is_guest_mode(vcpu) &&
4087             vector == vmx->nested.posted_intr_nv) {
4088                 /*
4089                  * If a posted intr is not recognized by hardware,
4090                  * we will accomplish it in the next vmentry.
4091                  */
4092                 vmx->nested.pi_pending = true;
4093                 kvm_make_request(KVM_REQ_EVENT, vcpu);
4094
4095                 /*
4096                  * This pairs with the smp_mb_*() after setting vcpu->mode in
4097                  * vcpu_enter_guest() to guarantee the vCPU sees the event
4098                  * request if triggering a posted interrupt "fails" because
4099                  * vcpu->mode != IN_GUEST_MODE.  The extra barrier is needed as
4100                  * the smb_wmb() in kvm_make_request() only ensures everything
4101                  * done before making the request is visible when the request
4102                  * is visible, it doesn't ensure ordering between the store to
4103                  * vcpu->requests and the load from vcpu->mode.
4104                  */
4105                 smp_mb__after_atomic();
4106
4107                 /* the PIR and ON have been set by L1. */
4108                 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR);
4109                 return 0;
4110         }
4111         return -1;
4112 }
4113 /*
4114  * Send interrupt to vcpu via posted interrupt way.
4115  * 1. If target vcpu is running(non-root mode), send posted interrupt
4116  * notification to vcpu and hardware will sync PIR to vIRR atomically.
4117  * 2. If target vcpu isn't running(root mode), kick it to pick up the
4118  * interrupt from PIR in next vmentry.
4119  */
4120 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
4121 {
4122         struct vcpu_vmx *vmx = to_vmx(vcpu);
4123         int r;
4124
4125         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
4126         if (!r)
4127                 return 0;
4128
4129         /* Note, this is called iff the local APIC is in-kernel. */
4130         if (!vcpu->arch.apic->apicv_active)
4131                 return -1;
4132
4133         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
4134                 return 0;
4135
4136         /* If a previous notification has sent the IPI, nothing to do.  */
4137         if (pi_test_and_set_on(&vmx->pi_desc))
4138                 return 0;
4139
4140         /*
4141          * The implied barrier in pi_test_and_set_on() pairs with the smp_mb_*()
4142          * after setting vcpu->mode in vcpu_enter_guest(), thus the vCPU is
4143          * guaranteed to see PID.ON=1 and sync the PIR to IRR if triggering a
4144          * posted interrupt "fails" because vcpu->mode != IN_GUEST_MODE.
4145          */
4146         kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_VECTOR);
4147         return 0;
4148 }
4149
4150 static void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
4151                                   int trig_mode, int vector)
4152 {
4153         struct kvm_vcpu *vcpu = apic->vcpu;
4154
4155         if (vmx_deliver_posted_interrupt(vcpu, vector)) {
4156                 kvm_lapic_set_irr(vector, apic);
4157                 kvm_make_request(KVM_REQ_EVENT, vcpu);
4158                 kvm_vcpu_kick(vcpu);
4159         } else {
4160                 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode,
4161                                            trig_mode, vector);
4162         }
4163 }
4164
4165 /*
4166  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4167  * will not change in the lifetime of the guest.
4168  * Note that host-state that does change is set elsewhere. E.g., host-state
4169  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4170  */
4171 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4172 {
4173         u32 low32, high32;
4174         unsigned long tmpl;
4175         unsigned long cr0, cr3, cr4;
4176
4177         cr0 = read_cr0();
4178         WARN_ON(cr0 & X86_CR0_TS);
4179         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
4180
4181         /*
4182          * Save the most likely value for this task's CR3 in the VMCS.
4183          * We can't use __get_current_cr3_fast() because we're not atomic.
4184          */
4185         cr3 = __read_cr3();
4186         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
4187         vmx->loaded_vmcs->host_state.cr3 = cr3;
4188
4189         /* Save the most likely value for this task's CR4 in the VMCS. */
4190         cr4 = cr4_read_shadow();
4191         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
4192         vmx->loaded_vmcs->host_state.cr4 = cr4;
4193
4194         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
4195 #ifdef CONFIG_X86_64
4196         /*
4197          * Load null selectors, so we can avoid reloading them in
4198          * vmx_prepare_switch_to_host(), in case userspace uses
4199          * the null selectors too (the expected case).
4200          */
4201         vmcs_write16(HOST_DS_SELECTOR, 0);
4202         vmcs_write16(HOST_ES_SELECTOR, 0);
4203 #else
4204         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4205         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4206 #endif
4207         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4208         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
4209
4210         vmcs_writel(HOST_IDTR_BASE, host_idt_base);   /* 22.2.4 */
4211
4212         vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4213
4214         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4215         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4216
4217         /*
4218          * SYSENTER is used for 32-bit system calls on either 32-bit or
4219          * 64-bit kernels.  It is always zero If neither is allowed, otherwise
4220          * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may
4221          * have already done so!).
4222          */
4223         if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32))
4224                 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0);
4225
4226         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4227         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
4228
4229         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4230                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
4231                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4232         }
4233
4234         if (cpu_has_load_ia32_efer())
4235                 vmcs_write64(HOST_IA32_EFER, host_efer);
4236 }
4237
4238 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4239 {
4240         struct kvm_vcpu *vcpu = &vmx->vcpu;
4241
4242         vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4243                                           ~vcpu->arch.cr4_guest_rsvd_bits;
4244         if (!enable_ept) {
4245                 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
4246                 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
4247         }
4248         if (is_guest_mode(&vmx->vcpu))
4249                 vcpu->arch.cr4_guest_owned_bits &=
4250                         ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4251         vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4252 }
4253
4254 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4255 {
4256         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4257
4258         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4259                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4260
4261         if (!enable_vnmi)
4262                 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4263
4264         if (!enable_preemption_timer)
4265                 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4266
4267         return pin_based_exec_ctrl;
4268 }
4269
4270 static u32 vmx_vmentry_ctrl(void)
4271 {
4272         u32 vmentry_ctrl = vmcs_config.vmentry_ctrl;
4273
4274         if (vmx_pt_mode_is_system())
4275                 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP |
4276                                   VM_ENTRY_LOAD_IA32_RTIT_CTL);
4277         /*
4278          * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically.
4279          */
4280         vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
4281                           VM_ENTRY_LOAD_IA32_EFER |
4282                           VM_ENTRY_IA32E_MODE);
4283
4284         if (cpu_has_perf_global_ctrl_bug())
4285                 vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
4286
4287         return vmentry_ctrl;
4288 }
4289
4290 static u32 vmx_vmexit_ctrl(void)
4291 {
4292         u32 vmexit_ctrl = vmcs_config.vmexit_ctrl;
4293
4294         /*
4295          * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for
4296          * nested virtualization and thus allowed to be set in vmcs12.
4297          */
4298         vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER |
4299                          VM_EXIT_SAVE_VMX_PREEMPTION_TIMER);
4300
4301         if (vmx_pt_mode_is_system())
4302                 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP |
4303                                  VM_EXIT_CLEAR_IA32_RTIT_CTL);
4304
4305         if (cpu_has_perf_global_ctrl_bug())
4306                 vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
4307
4308         /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */
4309         return vmexit_ctrl &
4310                 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
4311 }
4312
4313 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4314 {
4315         struct vcpu_vmx *vmx = to_vmx(vcpu);
4316
4317         if (is_guest_mode(vcpu)) {
4318                 vmx->nested.update_vmcs01_apicv_status = true;
4319                 return;
4320         }
4321
4322         pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4323
4324         if (kvm_vcpu_apicv_active(vcpu)) {
4325                 secondary_exec_controls_setbit(vmx,
4326                                                SECONDARY_EXEC_APIC_REGISTER_VIRT |
4327                                                SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4328                 if (enable_ipiv)
4329                         tertiary_exec_controls_setbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4330         } else {
4331                 secondary_exec_controls_clearbit(vmx,
4332                                                  SECONDARY_EXEC_APIC_REGISTER_VIRT |
4333                                                  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4334                 if (enable_ipiv)
4335                         tertiary_exec_controls_clearbit(vmx, TERTIARY_EXEC_IPI_VIRT);
4336         }
4337
4338         vmx_update_msr_bitmap_x2apic(vcpu);
4339 }
4340
4341 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
4342 {
4343         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4344
4345         /*
4346          * Not used by KVM, but fully supported for nesting, i.e. are allowed in
4347          * vmcs12 and propagated to vmcs02 when set in vmcs12.
4348          */
4349         exec_control &= ~(CPU_BASED_RDTSC_EXITING |
4350                           CPU_BASED_USE_IO_BITMAPS |
4351                           CPU_BASED_MONITOR_TRAP_FLAG |
4352                           CPU_BASED_PAUSE_EXITING);
4353
4354         /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */
4355         exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING |
4356                           CPU_BASED_NMI_WINDOW_EXITING);
4357
4358         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4359                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4360
4361         if (!cpu_need_tpr_shadow(&vmx->vcpu))
4362                 exec_control &= ~CPU_BASED_TPR_SHADOW;
4363
4364 #ifdef CONFIG_X86_64
4365         if (exec_control & CPU_BASED_TPR_SHADOW)
4366                 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING |
4367                                   CPU_BASED_CR8_STORE_EXITING);
4368         else
4369                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
4370                                 CPU_BASED_CR8_LOAD_EXITING;
4371 #endif
4372         /* No need to intercept CR3 access or INVPLG when using EPT. */
4373         if (enable_ept)
4374                 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4375                                   CPU_BASED_CR3_STORE_EXITING |
4376                                   CPU_BASED_INVLPG_EXITING);
4377         if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4378                 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4379                                 CPU_BASED_MONITOR_EXITING);
4380         if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4381                 exec_control &= ~CPU_BASED_HLT_EXITING;
4382         return exec_control;
4383 }
4384
4385 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx)
4386 {
4387         u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl;
4388
4389         /*
4390          * IPI virtualization relies on APICv. Disable IPI virtualization if
4391          * APICv is inhibited.
4392          */
4393         if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu))
4394                 exec_control &= ~TERTIARY_EXEC_IPI_VIRT;
4395
4396         return exec_control;
4397 }
4398
4399 /*
4400  * Adjust a single secondary execution control bit to intercept/allow an
4401  * instruction in the guest.  This is usually done based on whether or not a
4402  * feature has been exposed to the guest in order to correctly emulate faults.
4403  */
4404 static inline void
4405 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4406                                   u32 control, bool enabled, bool exiting)
4407 {
4408         /*
4409          * If the control is for an opt-in feature, clear the control if the
4410          * feature is not exposed to the guest, i.e. not enabled.  If the
4411          * control is opt-out, i.e. an exiting control, clear the control if
4412          * the feature _is_ exposed to the guest, i.e. exiting/interception is
4413          * disabled for the associated instruction.  Note, the caller is
4414          * responsible presetting exec_control to set all supported bits.
4415          */
4416         if (enabled == exiting)
4417                 *exec_control &= ~control;
4418
4419         /*
4420          * Update the nested MSR settings so that a nested VMM can/can't set
4421          * controls for features that are/aren't exposed to the guest.
4422          */
4423         if (nested) {
4424                 if (enabled)
4425                         vmx->nested.msrs.secondary_ctls_high |= control;
4426                 else
4427                         vmx->nested.msrs.secondary_ctls_high &= ~control;
4428         }
4429 }
4430
4431 /*
4432  * Wrapper macro for the common case of adjusting a secondary execution control
4433  * based on a single guest CPUID bit, with a dedicated feature bit.  This also
4434  * verifies that the control is actually supported by KVM and hardware.
4435  */
4436 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4437 ({                                                                       \
4438         bool __enabled;                                                  \
4439                                                                          \
4440         if (cpu_has_vmx_##name()) {                                      \
4441                 __enabled = guest_cpuid_has(&(vmx)->vcpu,                \
4442                                             X86_FEATURE_##feat_name);    \
4443                 vmx_adjust_secondary_exec_control(vmx, exec_control,     \
4444                         SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4445         }                                                                \
4446 })
4447
4448 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4449 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4450         vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4451
4452 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4453         vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4454
4455 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
4456 {
4457         struct kvm_vcpu *vcpu = &vmx->vcpu;
4458
4459         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4460
4461         if (vmx_pt_mode_is_system())
4462                 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4463         if (!cpu_need_virtualize_apic_accesses(vcpu))
4464                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4465         if (vmx->vpid == 0)
4466                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4467         if (!enable_ept) {
4468                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4469                 enable_unrestricted_guest = 0;
4470         }
4471         if (!enable_unrestricted_guest)
4472                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4473         if (kvm_pause_in_guest(vmx->vcpu.kvm))
4474                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4475         if (!kvm_vcpu_apicv_active(vcpu))
4476                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4477                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4478         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4479
4480         /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4481          * in vmx_set_cr4.  */
4482         exec_control &= ~SECONDARY_EXEC_DESC;
4483
4484         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4485            (handle_vmptrld).
4486            We can NOT enable shadow_vmcs here because we don't have yet
4487            a current VMCS12
4488         */
4489         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4490
4491         /*
4492          * PML is enabled/disabled when dirty logging of memsmlots changes, but
4493          * it needs to be set here when dirty logging is already active, e.g.
4494          * if this vCPU was created after dirty logging was enabled.
4495          */
4496         if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4497                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4498
4499         if (cpu_has_vmx_xsaves()) {
4500                 /* Exposing XSAVES only when XSAVE is exposed */
4501                 bool xsaves_enabled =
4502                         boot_cpu_has(X86_FEATURE_XSAVE) &&
4503                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4504                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4505
4506                 vcpu->arch.xsaves_enabled = xsaves_enabled;
4507
4508                 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4509                                                   SECONDARY_EXEC_XSAVES,
4510                                                   xsaves_enabled, false);
4511         }
4512
4513         /*
4514          * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4515          * feature is exposed to the guest.  This creates a virtualization hole
4516          * if both are supported in hardware but only one is exposed to the
4517          * guest, but letting the guest execute RDTSCP or RDPID when either one
4518          * is advertised is preferable to emulating the advertised instruction
4519          * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4520          */
4521         if (cpu_has_vmx_rdtscp()) {
4522                 bool rdpid_or_rdtscp_enabled =
4523                         guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4524                         guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4525
4526                 vmx_adjust_secondary_exec_control(vmx, &exec_control,
4527                                                   SECONDARY_EXEC_ENABLE_RDTSCP,
4528                                                   rdpid_or_rdtscp_enabled, false);
4529         }
4530         vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4531
4532         vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4533         vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4534
4535         vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4536                                     ENABLE_USR_WAIT_PAUSE, false);
4537
4538         if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4539                 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4540
4541         if (!kvm_notify_vmexit_enabled(vcpu->kvm))
4542                 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING;
4543
4544         return exec_control;
4545 }
4546
4547 static inline int vmx_get_pid_table_order(struct kvm *kvm)
4548 {
4549         return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table));
4550 }
4551
4552 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm)
4553 {
4554         struct page *pages;
4555         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4556
4557         if (!irqchip_in_kernel(kvm) || !enable_ipiv)
4558                 return 0;
4559
4560         if (kvm_vmx->pid_table)
4561                 return 0;
4562
4563         pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, vmx_get_pid_table_order(kvm));
4564         if (!pages)
4565                 return -ENOMEM;
4566
4567         kvm_vmx->pid_table = (void *)page_address(pages);
4568         return 0;
4569 }
4570
4571 static int vmx_vcpu_precreate(struct kvm *kvm)
4572 {
4573         return vmx_alloc_ipiv_pid_table(kvm);
4574 }
4575
4576 #define VMX_XSS_EXIT_BITMAP 0
4577
4578 static void init_vmcs(struct vcpu_vmx *vmx)
4579 {
4580         struct kvm *kvm = vmx->vcpu.kvm;
4581         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
4582
4583         if (nested)
4584                 nested_vmx_set_vmcs_shadowing_bitmap();
4585
4586         if (cpu_has_vmx_msr_bitmap())
4587                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4588
4589         vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */
4590
4591         /* Control */
4592         pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4593
4594         exec_controls_set(vmx, vmx_exec_control(vmx));
4595
4596         if (cpu_has_secondary_exec_ctrls())
4597                 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx));
4598
4599         if (cpu_has_tertiary_exec_ctrls())
4600                 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx));
4601
4602         if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) {
4603                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4604                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4605                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4606                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4607
4608                 vmcs_write16(GUEST_INTR_STATUS, 0);
4609
4610                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4611                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4612         }
4613
4614         if (vmx_can_use_ipiv(&vmx->vcpu)) {
4615                 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table));
4616                 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1);
4617         }
4618
4619         if (!kvm_pause_in_guest(kvm)) {
4620                 vmcs_write32(PLE_GAP, ple_gap);
4621                 vmx->ple_window = ple_window;
4622                 vmx->ple_window_dirty = true;
4623         }
4624
4625         if (kvm_notify_vmexit_enabled(kvm))
4626                 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window);
4627
4628         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4629         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4630         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4631
4632         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4633         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4634         vmx_set_constant_host_state(vmx);
4635         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4636         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4637
4638         if (cpu_has_vmx_vmfunc())
4639                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4640
4641         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4642         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4643         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4644         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4645         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4646
4647         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4648                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4649
4650         vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4651
4652         /* 22.2.1, 20.8.1 */
4653         vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4654
4655         vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4656         vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4657
4658         set_cr4_guest_host_mask(vmx);
4659
4660         if (vmx->vpid != 0)
4661                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4662
4663         if (cpu_has_vmx_xsaves())
4664                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4665
4666         if (enable_pml) {
4667                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4668                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4669         }
4670
4671         vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4672
4673         if (vmx_pt_mode_is_host_guest()) {
4674                 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4675                 /* Bit[6~0] are forced to 1, writes are ignored. */
4676                 vmx->pt_desc.guest.output_mask = 0x7F;
4677                 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4678         }
4679
4680         vmcs_write32(GUEST_SYSENTER_CS, 0);
4681         vmcs_writel(GUEST_SYSENTER_ESP, 0);
4682         vmcs_writel(GUEST_SYSENTER_EIP, 0);
4683         vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4684
4685         if (cpu_has_vmx_tpr_shadow()) {
4686                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4687                 if (cpu_need_tpr_shadow(&vmx->vcpu))
4688                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4689                                      __pa(vmx->vcpu.arch.apic->regs));
4690                 vmcs_write32(TPR_THRESHOLD, 0);
4691         }
4692
4693         vmx_setup_uret_msrs(vmx);
4694 }
4695
4696 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
4697 {
4698         struct vcpu_vmx *vmx = to_vmx(vcpu);
4699
4700         init_vmcs(vmx);
4701
4702         if (nested)
4703                 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs));
4704
4705         vcpu_setup_sgx_lepubkeyhash(vcpu);
4706
4707         vmx->nested.posted_intr_nv = -1;
4708         vmx->nested.vmxon_ptr = INVALID_GPA;
4709         vmx->nested.current_vmptr = INVALID_GPA;
4710         vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID;
4711
4712         vcpu->arch.microcode_version = 0x100000000ULL;
4713         vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
4714
4715         /*
4716          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
4717          * or POSTED_INTR_WAKEUP_VECTOR.
4718          */
4719         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
4720         vmx->pi_desc.sn = 1;
4721 }
4722
4723 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4724 {
4725         struct vcpu_vmx *vmx = to_vmx(vcpu);
4726
4727         if (!init_event)
4728                 __vmx_vcpu_reset(vcpu);
4729
4730         vmx->rmode.vm86_active = 0;
4731         vmx->spec_ctrl = 0;
4732
4733         vmx->msr_ia32_umwait_control = 0;
4734
4735         vmx->hv_deadline_tsc = -1;
4736         kvm_set_cr8(vcpu, 0);
4737
4738         vmx_segment_cache_clear(vmx);
4739         kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS);
4740
4741         seg_setup(VCPU_SREG_CS);
4742         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4743         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4744
4745         seg_setup(VCPU_SREG_DS);
4746         seg_setup(VCPU_SREG_ES);
4747         seg_setup(VCPU_SREG_FS);
4748         seg_setup(VCPU_SREG_GS);
4749         seg_setup(VCPU_SREG_SS);
4750
4751         vmcs_write16(GUEST_TR_SELECTOR, 0);
4752         vmcs_writel(GUEST_TR_BASE, 0);
4753         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4754         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4755
4756         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4757         vmcs_writel(GUEST_LDTR_BASE, 0);
4758         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4759         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4760
4761         vmcs_writel(GUEST_GDTR_BASE, 0);
4762         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4763
4764         vmcs_writel(GUEST_IDTR_BASE, 0);
4765         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4766
4767         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4768         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4769         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4770         if (kvm_mpx_supported())
4771                 vmcs_write64(GUEST_BNDCFGS, 0);
4772
4773         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4774
4775         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4776
4777         vpid_sync_context(vmx->vpid);
4778
4779         vmx_update_fb_clear_dis(vcpu, vmx);
4780 }
4781
4782 static void vmx_enable_irq_window(struct kvm_vcpu *vcpu)
4783 {
4784         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4785 }
4786
4787 static void vmx_enable_nmi_window(struct kvm_vcpu *vcpu)
4788 {
4789         if (!enable_vnmi ||
4790             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4791                 vmx_enable_irq_window(vcpu);
4792                 return;
4793         }
4794
4795         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4796 }
4797
4798 static void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
4799 {
4800         struct vcpu_vmx *vmx = to_vmx(vcpu);
4801         uint32_t intr;
4802         int irq = vcpu->arch.interrupt.nr;
4803
4804         trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected);
4805
4806         ++vcpu->stat.irq_injections;
4807         if (vmx->rmode.vm86_active) {
4808                 int inc_eip = 0;
4809                 if (vcpu->arch.interrupt.soft)
4810                         inc_eip = vcpu->arch.event_exit_inst_len;
4811                 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4812                 return;
4813         }
4814         intr = irq | INTR_INFO_VALID_MASK;
4815         if (vcpu->arch.interrupt.soft) {
4816                 intr |= INTR_TYPE_SOFT_INTR;
4817                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4818                              vmx->vcpu.arch.event_exit_inst_len);
4819         } else
4820                 intr |= INTR_TYPE_EXT_INTR;
4821         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4822
4823         vmx_clear_hlt(vcpu);
4824 }
4825
4826 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4827 {
4828         struct vcpu_vmx *vmx = to_vmx(vcpu);
4829
4830         if (!enable_vnmi) {
4831                 /*
4832                  * Tracking the NMI-blocked state in software is built upon
4833                  * finding the next open IRQ window. This, in turn, depends on
4834                  * well-behaving guests: They have to keep IRQs disabled at
4835                  * least as long as the NMI handler runs. Otherwise we may
4836                  * cause NMI nesting, maybe breaking the guest. But as this is
4837                  * highly unlikely, we can live with the residual risk.
4838                  */
4839                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4840                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4841         }
4842
4843         ++vcpu->stat.nmi_injections;
4844         vmx->loaded_vmcs->nmi_known_unmasked = false;
4845
4846         if (vmx->rmode.vm86_active) {
4847                 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4848                 return;
4849         }
4850
4851         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4852                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4853
4854         vmx_clear_hlt(vcpu);
4855 }
4856
4857 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4858 {
4859         struct vcpu_vmx *vmx = to_vmx(vcpu);
4860         bool masked;
4861
4862         if (!enable_vnmi)
4863                 return vmx->loaded_vmcs->soft_vnmi_blocked;
4864         if (vmx->loaded_vmcs->nmi_known_unmasked)
4865                 return false;
4866         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4867         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4868         return masked;
4869 }
4870
4871 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4872 {
4873         struct vcpu_vmx *vmx = to_vmx(vcpu);
4874
4875         if (!enable_vnmi) {
4876                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4877                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4878                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
4879                 }
4880         } else {
4881                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4882                 if (masked)
4883                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4884                                       GUEST_INTR_STATE_NMI);
4885                 else
4886                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4887                                         GUEST_INTR_STATE_NMI);
4888         }
4889 }
4890
4891 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4892 {
4893         if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4894                 return false;
4895
4896         if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4897                 return true;
4898
4899         return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4900                 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4901                  GUEST_INTR_STATE_NMI));
4902 }
4903
4904 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4905 {
4906         if (to_vmx(vcpu)->nested.nested_run_pending)
4907                 return -EBUSY;
4908
4909         /* An NMI must not be injected into L2 if it's supposed to VM-Exit.  */
4910         if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4911                 return -EBUSY;
4912
4913         return !vmx_nmi_blocked(vcpu);
4914 }
4915
4916 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4917 {
4918         if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4919                 return false;
4920
4921         return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4922                (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4923                 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4924 }
4925
4926 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4927 {
4928         if (to_vmx(vcpu)->nested.nested_run_pending)
4929                 return -EBUSY;
4930
4931        /*
4932         * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4933         * e.g. if the IRQ arrived asynchronously after checking nested events.
4934         */
4935         if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4936                 return -EBUSY;
4937
4938         return !vmx_interrupt_blocked(vcpu);
4939 }
4940
4941 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4942 {
4943         void __user *ret;
4944
4945         if (enable_unrestricted_guest)
4946                 return 0;
4947
4948         mutex_lock(&kvm->slots_lock);
4949         ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4950                                       PAGE_SIZE * 3);
4951         mutex_unlock(&kvm->slots_lock);
4952
4953         if (IS_ERR(ret))
4954                 return PTR_ERR(ret);
4955
4956         to_kvm_vmx(kvm)->tss_addr = addr;
4957
4958         return init_rmode_tss(kvm, ret);
4959 }
4960
4961 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4962 {
4963         to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4964         return 0;
4965 }
4966
4967 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4968 {
4969         switch (vec) {
4970         case BP_VECTOR:
4971                 /*
4972                  * Update instruction length as we may reinject the exception
4973                  * from user space while in guest debugging mode.
4974                  */
4975                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4976                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4977                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4978                         return false;
4979                 fallthrough;
4980         case DB_VECTOR:
4981                 return !(vcpu->guest_debug &
4982                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4983         case DE_VECTOR:
4984         case OF_VECTOR:
4985         case BR_VECTOR:
4986         case UD_VECTOR:
4987         case DF_VECTOR:
4988         case SS_VECTOR:
4989         case GP_VECTOR:
4990         case MF_VECTOR:
4991                 return true;
4992         }
4993         return false;
4994 }
4995
4996 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4997                                   int vec, u32 err_code)
4998 {
4999         /*
5000          * Instruction with address size override prefix opcode 0x67
5001          * Cause the #SS fault with 0 error code in VM86 mode.
5002          */
5003         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5004                 if (kvm_emulate_instruction(vcpu, 0)) {
5005                         if (vcpu->arch.halt_request) {
5006                                 vcpu->arch.halt_request = 0;
5007                                 return kvm_emulate_halt_noskip(vcpu);
5008                         }
5009                         return 1;
5010                 }
5011                 return 0;
5012         }
5013
5014         /*
5015          * Forward all other exceptions that are valid in real mode.
5016          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5017          *        the required debugging infrastructure rework.
5018          */
5019         kvm_queue_exception(vcpu, vec);
5020         return 1;
5021 }
5022
5023 static int handle_machine_check(struct kvm_vcpu *vcpu)
5024 {
5025         /* handled by vmx_vcpu_run() */
5026         return 1;
5027 }
5028
5029 /*
5030  * If the host has split lock detection disabled, then #AC is
5031  * unconditionally injected into the guest, which is the pre split lock
5032  * detection behaviour.
5033  *
5034  * If the host has split lock detection enabled then #AC is
5035  * only injected into the guest when:
5036  *  - Guest CPL == 3 (user mode)
5037  *  - Guest has #AC detection enabled in CR0
5038  *  - Guest EFLAGS has AC bit set
5039  */
5040 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
5041 {
5042         if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
5043                 return true;
5044
5045         return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
5046                (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
5047 }
5048
5049 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
5050 {
5051         struct vcpu_vmx *vmx = to_vmx(vcpu);
5052         struct kvm_run *kvm_run = vcpu->run;
5053         u32 intr_info, ex_no, error_code;
5054         unsigned long cr2, dr6;
5055         u32 vect_info;
5056
5057         vect_info = vmx->idt_vectoring_info;
5058         intr_info = vmx_get_intr_info(vcpu);
5059
5060         if (is_machine_check(intr_info) || is_nmi(intr_info))
5061                 return 1; /* handled by handle_exception_nmi_irqoff() */
5062
5063         /*
5064          * Queue the exception here instead of in handle_nm_fault_irqoff().
5065          * This ensures the nested_vmx check is not skipped so vmexit can
5066          * be reflected to L1 (when it intercepts #NM) before reaching this
5067          * point.
5068          */
5069         if (is_nm_fault(intr_info)) {
5070                 kvm_queue_exception(vcpu, NM_VECTOR);
5071                 return 1;
5072         }
5073
5074         if (is_invalid_opcode(intr_info))
5075                 return handle_ud(vcpu);
5076
5077         error_code = 0;
5078         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5079                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5080
5081         if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
5082                 WARN_ON_ONCE(!enable_vmware_backdoor);
5083
5084                 /*
5085                  * VMware backdoor emulation on #GP interception only handles
5086                  * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
5087                  * error code on #GP.
5088                  */
5089                 if (error_code) {
5090                         kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
5091                         return 1;
5092                 }
5093                 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
5094         }
5095
5096         /*
5097          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5098          * MMIO, it is better to report an internal error.
5099          * See the comments in vmx_handle_exit.
5100          */
5101         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5102             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5103                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5104                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5105                 vcpu->run->internal.ndata = 4;
5106                 vcpu->run->internal.data[0] = vect_info;
5107                 vcpu->run->internal.data[1] = intr_info;
5108                 vcpu->run->internal.data[2] = error_code;
5109                 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
5110                 return 0;
5111         }
5112
5113         if (is_page_fault(intr_info)) {
5114                 cr2 = vmx_get_exit_qual(vcpu);
5115                 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
5116                         /*
5117                          * EPT will cause page fault only if we need to
5118                          * detect illegal GPAs.
5119                          */
5120                         WARN_ON_ONCE(!allow_smaller_maxphyaddr);
5121                         kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
5122                         return 1;
5123                 } else
5124                         return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
5125         }
5126
5127         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5128
5129         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5130                 return handle_rmode_exception(vcpu, ex_no, error_code);
5131
5132         switch (ex_no) {
5133         case DB_VECTOR:
5134                 dr6 = vmx_get_exit_qual(vcpu);
5135                 if (!(vcpu->guest_debug &
5136                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5137                         /*
5138                          * If the #DB was due to ICEBP, a.k.a. INT1, skip the
5139                          * instruction.  ICEBP generates a trap-like #DB, but
5140                          * despite its interception control being tied to #DB,
5141                          * is an instruction intercept, i.e. the VM-Exit occurs
5142                          * on the ICEBP itself.  Note, skipping ICEBP also
5143                          * clears STI and MOVSS blocking.
5144                          *
5145                          * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
5146                          * if single-step is enabled in RFLAGS and STI or MOVSS
5147                          * blocking is active, as the CPU doesn't set the bit
5148                          * on VM-Exit due to #DB interception.  VM-Entry has a
5149                          * consistency check that a single-step #DB is pending
5150                          * in this scenario as the previous instruction cannot
5151                          * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV
5152                          * don't modify RFLAGS), therefore the one instruction
5153                          * delay when activating single-step breakpoints must
5154                          * have already expired.  Note, the CPU sets/clears BS
5155                          * as appropriate for all other VM-Exits types.
5156                          */
5157                         if (is_icebp(intr_info))
5158                                 WARN_ON(!skip_emulated_instruction(vcpu));
5159                         else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) &&
5160                                  (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5161                                   (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)))
5162                                 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
5163                                             vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS);
5164
5165                         kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
5166                         return 1;
5167                 }
5168                 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW;
5169                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5170                 fallthrough;
5171         case BP_VECTOR:
5172                 /*
5173                  * Update instruction length as we may reinject #BP from
5174                  * user space while in guest debugging mode. Reading it for
5175                  * #DB as well causes no harm, it is not used in that case.
5176                  */
5177                 vmx->vcpu.arch.event_exit_inst_len =
5178                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5179                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5180                 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5181                 kvm_run->debug.arch.exception = ex_no;
5182                 break;
5183         case AC_VECTOR:
5184                 if (vmx_guest_inject_ac(vcpu)) {
5185                         kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5186                         return 1;
5187                 }
5188
5189                 /*
5190                  * Handle split lock. Depending on detection mode this will
5191                  * either warn and disable split lock detection for this
5192                  * task or force SIGBUS on it.
5193                  */
5194                 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
5195                         return 1;
5196                 fallthrough;
5197         default:
5198                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5199                 kvm_run->ex.exception = ex_no;
5200                 kvm_run->ex.error_code = error_code;
5201                 break;
5202         }
5203         return 0;
5204 }
5205
5206 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
5207 {
5208         ++vcpu->stat.irq_exits;
5209         return 1;
5210 }
5211
5212 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5213 {
5214         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5215         vcpu->mmio_needed = 0;
5216         return 0;
5217 }
5218
5219 static int handle_io(struct kvm_vcpu *vcpu)
5220 {
5221         unsigned long exit_qualification;
5222         int size, in, string;
5223         unsigned port;
5224
5225         exit_qualification = vmx_get_exit_qual(vcpu);
5226         string = (exit_qualification & 16) != 0;
5227
5228         ++vcpu->stat.io_exits;
5229
5230         if (string)
5231                 return kvm_emulate_instruction(vcpu, 0);
5232
5233         port = exit_qualification >> 16;
5234         size = (exit_qualification & 7) + 1;
5235         in = (exit_qualification & 8) != 0;
5236
5237         return kvm_fast_pio(vcpu, size, port, in);
5238 }
5239
5240 static void
5241 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5242 {
5243         /*
5244          * Patch in the VMCALL instruction:
5245          */
5246         hypercall[0] = 0x0f;
5247         hypercall[1] = 0x01;
5248         hypercall[2] = 0xc1;
5249 }
5250
5251 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5252 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5253 {
5254         if (is_guest_mode(vcpu)) {
5255                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5256                 unsigned long orig_val = val;
5257
5258                 /*
5259                  * We get here when L2 changed cr0 in a way that did not change
5260                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
5261                  * but did change L0 shadowed bits. So we first calculate the
5262                  * effective cr0 value that L1 would like to write into the
5263                  * hardware. It consists of the L2-owned bits from the new
5264                  * value combined with the L1-owned bits from L1's guest_cr0.
5265                  */
5266                 val = (val & ~vmcs12->cr0_guest_host_mask) |
5267                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
5268
5269                 if (!nested_guest_cr0_valid(vcpu, val))
5270                         return 1;
5271
5272                 if (kvm_set_cr0(vcpu, val))
5273                         return 1;
5274                 vmcs_writel(CR0_READ_SHADOW, orig_val);
5275                 return 0;
5276         } else {
5277                 if (to_vmx(vcpu)->nested.vmxon &&
5278                     !nested_host_cr0_valid(vcpu, val))
5279                         return 1;
5280
5281                 return kvm_set_cr0(vcpu, val);
5282         }
5283 }
5284
5285 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
5286 {
5287         if (is_guest_mode(vcpu)) {
5288                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5289                 unsigned long orig_val = val;
5290
5291                 /* analogously to handle_set_cr0 */
5292                 val = (val & ~vmcs12->cr4_guest_host_mask) |
5293                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
5294                 if (kvm_set_cr4(vcpu, val))
5295                         return 1;
5296                 vmcs_writel(CR4_READ_SHADOW, orig_val);
5297                 return 0;
5298         } else
5299                 return kvm_set_cr4(vcpu, val);
5300 }
5301
5302 static int handle_desc(struct kvm_vcpu *vcpu)
5303 {
5304         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
5305         return kvm_emulate_instruction(vcpu, 0);
5306 }
5307
5308 static int handle_cr(struct kvm_vcpu *vcpu)
5309 {
5310         unsigned long exit_qualification, val;
5311         int cr;
5312         int reg;
5313         int err;
5314         int ret;
5315
5316         exit_qualification = vmx_get_exit_qual(vcpu);
5317         cr = exit_qualification & 15;
5318         reg = (exit_qualification >> 8) & 15;
5319         switch ((exit_qualification >> 4) & 3) {
5320         case 0: /* mov to cr */
5321                 val = kvm_register_read(vcpu, reg);
5322                 trace_kvm_cr_write(cr, val);
5323                 switch (cr) {
5324                 case 0:
5325                         err = handle_set_cr0(vcpu, val);
5326                         return kvm_complete_insn_gp(vcpu, err);
5327                 case 3:
5328                         WARN_ON_ONCE(enable_unrestricted_guest);
5329
5330                         err = kvm_set_cr3(vcpu, val);
5331                         return kvm_complete_insn_gp(vcpu, err);
5332                 case 4:
5333                         err = handle_set_cr4(vcpu, val);
5334                         return kvm_complete_insn_gp(vcpu, err);
5335                 case 8: {
5336                                 u8 cr8_prev = kvm_get_cr8(vcpu);
5337                                 u8 cr8 = (u8)val;
5338                                 err = kvm_set_cr8(vcpu, cr8);
5339                                 ret = kvm_complete_insn_gp(vcpu, err);
5340                                 if (lapic_in_kernel(vcpu))
5341                                         return ret;
5342                                 if (cr8_prev <= cr8)
5343                                         return ret;
5344                                 /*
5345                                  * TODO: we might be squashing a
5346                                  * KVM_GUESTDBG_SINGLESTEP-triggered
5347                                  * KVM_EXIT_DEBUG here.
5348                                  */
5349                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5350                                 return 0;
5351                         }
5352                 }
5353                 break;
5354         case 2: /* clts */
5355                 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
5356                 return -EIO;
5357         case 1: /*mov from cr*/
5358                 switch (cr) {
5359                 case 3:
5360                         WARN_ON_ONCE(enable_unrestricted_guest);
5361
5362                         val = kvm_read_cr3(vcpu);
5363                         kvm_register_write(vcpu, reg, val);
5364                         trace_kvm_cr_read(cr, val);
5365                         return kvm_skip_emulated_instruction(vcpu);
5366                 case 8:
5367                         val = kvm_get_cr8(vcpu);
5368                         kvm_register_write(vcpu, reg, val);
5369                         trace_kvm_cr_read(cr, val);
5370                         return kvm_skip_emulated_instruction(vcpu);
5371                 }
5372                 break;
5373         case 3: /* lmsw */
5374                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5375                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5376                 kvm_lmsw(vcpu, val);
5377
5378                 return kvm_skip_emulated_instruction(vcpu);
5379         default:
5380                 break;
5381         }
5382         vcpu->run->exit_reason = 0;
5383         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5384                (int)(exit_qualification >> 4) & 3, cr);
5385         return 0;
5386 }
5387
5388 static int handle_dr(struct kvm_vcpu *vcpu)
5389 {
5390         unsigned long exit_qualification;
5391         int dr, dr7, reg;
5392         int err = 1;
5393
5394         exit_qualification = vmx_get_exit_qual(vcpu);
5395         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5396
5397         /* First, if DR does not exist, trigger UD */
5398         if (!kvm_require_dr(vcpu, dr))
5399                 return 1;
5400
5401         if (vmx_get_cpl(vcpu) > 0)
5402                 goto out;
5403
5404         dr7 = vmcs_readl(GUEST_DR7);
5405         if (dr7 & DR7_GD) {
5406                 /*
5407                  * As the vm-exit takes precedence over the debug trap, we
5408                  * need to emulate the latter, either for the host or the
5409                  * guest debugging itself.
5410                  */
5411                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5412                         vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW;
5413                         vcpu->run->debug.arch.dr7 = dr7;
5414                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5415                         vcpu->run->debug.arch.exception = DB_VECTOR;
5416                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5417                         return 0;
5418                 } else {
5419                         kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5420                         return 1;
5421                 }
5422         }
5423
5424         if (vcpu->guest_debug == 0) {
5425                 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5426
5427                 /*
5428                  * No more DR vmexits; force a reload of the debug registers
5429                  * and reenter on this instruction.  The next vmexit will
5430                  * retrieve the full state of the debug registers.
5431                  */
5432                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5433                 return 1;
5434         }
5435
5436         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5437         if (exit_qualification & TYPE_MOV_FROM_DR) {
5438                 unsigned long val;
5439
5440                 kvm_get_dr(vcpu, dr, &val);
5441                 kvm_register_write(vcpu, reg, val);
5442                 err = 0;
5443         } else {
5444                 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg));
5445         }
5446
5447 out:
5448         return kvm_complete_insn_gp(vcpu, err);
5449 }
5450
5451 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5452 {
5453         get_debugreg(vcpu->arch.db[0], 0);
5454         get_debugreg(vcpu->arch.db[1], 1);
5455         get_debugreg(vcpu->arch.db[2], 2);
5456         get_debugreg(vcpu->arch.db[3], 3);
5457         get_debugreg(vcpu->arch.dr6, 6);
5458         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5459
5460         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5461         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5462
5463         /*
5464          * exc_debug expects dr6 to be cleared after it runs, avoid that it sees
5465          * a stale dr6 from the guest.
5466          */
5467         set_debugreg(DR6_RESERVED, 6);
5468 }
5469
5470 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5471 {
5472         vmcs_writel(GUEST_DR7, val);
5473 }
5474
5475 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5476 {
5477         kvm_apic_update_ppr(vcpu);
5478         return 1;
5479 }
5480
5481 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5482 {
5483         exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5484
5485         kvm_make_request(KVM_REQ_EVENT, vcpu);
5486
5487         ++vcpu->stat.irq_window_exits;
5488         return 1;
5489 }
5490
5491 static int handle_invlpg(struct kvm_vcpu *vcpu)
5492 {
5493         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5494
5495         kvm_mmu_invlpg(vcpu, exit_qualification);
5496         return kvm_skip_emulated_instruction(vcpu);
5497 }
5498
5499 static int handle_apic_access(struct kvm_vcpu *vcpu)
5500 {
5501         if (likely(fasteoi)) {
5502                 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5503                 int access_type, offset;
5504
5505                 access_type = exit_qualification & APIC_ACCESS_TYPE;
5506                 offset = exit_qualification & APIC_ACCESS_OFFSET;
5507                 /*
5508                  * Sane guest uses MOV to write EOI, with written value
5509                  * not cared. So make a short-circuit here by avoiding
5510                  * heavy instruction emulation.
5511                  */
5512                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5513                     (offset == APIC_EOI)) {
5514                         kvm_lapic_set_eoi(vcpu);
5515                         return kvm_skip_emulated_instruction(vcpu);
5516                 }
5517         }
5518         return kvm_emulate_instruction(vcpu, 0);
5519 }
5520
5521 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5522 {
5523         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5524         int vector = exit_qualification & 0xff;
5525
5526         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5527         kvm_apic_set_eoi_accelerated(vcpu, vector);
5528         return 1;
5529 }
5530
5531 static int handle_apic_write(struct kvm_vcpu *vcpu)
5532 {
5533         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5534
5535         /*
5536          * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and
5537          * hardware has done any necessary aliasing, offset adjustments, etc...
5538          * for the access.  I.e. the correct value has already been  written to
5539          * the vAPIC page for the correct 16-byte chunk.  KVM needs only to
5540          * retrieve the register value and emulate the access.
5541          */
5542         u32 offset = exit_qualification & 0xff0;
5543
5544         kvm_apic_write_nodecode(vcpu, offset);
5545         return 1;
5546 }
5547
5548 static int handle_task_switch(struct kvm_vcpu *vcpu)
5549 {
5550         struct vcpu_vmx *vmx = to_vmx(vcpu);
5551         unsigned long exit_qualification;
5552         bool has_error_code = false;
5553         u32 error_code = 0;
5554         u16 tss_selector;
5555         int reason, type, idt_v, idt_index;
5556
5557         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5558         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5559         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5560
5561         exit_qualification = vmx_get_exit_qual(vcpu);
5562
5563         reason = (u32)exit_qualification >> 30;
5564         if (reason == TASK_SWITCH_GATE && idt_v) {
5565                 switch (type) {
5566                 case INTR_TYPE_NMI_INTR:
5567                         vcpu->arch.nmi_injected = false;
5568                         vmx_set_nmi_mask(vcpu, true);
5569                         break;
5570                 case INTR_TYPE_EXT_INTR:
5571                 case INTR_TYPE_SOFT_INTR:
5572                         kvm_clear_interrupt_queue(vcpu);
5573                         break;
5574                 case INTR_TYPE_HARD_EXCEPTION:
5575                         if (vmx->idt_vectoring_info &
5576                             VECTORING_INFO_DELIVER_CODE_MASK) {
5577                                 has_error_code = true;
5578                                 error_code =
5579                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
5580                         }
5581                         fallthrough;
5582                 case INTR_TYPE_SOFT_EXCEPTION:
5583                         kvm_clear_exception_queue(vcpu);
5584                         break;
5585                 default:
5586                         break;
5587                 }
5588         }
5589         tss_selector = exit_qualification;
5590
5591         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5592                        type != INTR_TYPE_EXT_INTR &&
5593                        type != INTR_TYPE_NMI_INTR))
5594                 WARN_ON(!skip_emulated_instruction(vcpu));
5595
5596         /*
5597          * TODO: What about debug traps on tss switch?
5598          *       Are we supposed to inject them and update dr6?
5599          */
5600         return kvm_task_switch(vcpu, tss_selector,
5601                                type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5602                                reason, has_error_code, error_code);
5603 }
5604
5605 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5606 {
5607         unsigned long exit_qualification;
5608         gpa_t gpa;
5609         u64 error_code;
5610
5611         exit_qualification = vmx_get_exit_qual(vcpu);
5612
5613         /*
5614          * EPT violation happened while executing iret from NMI,
5615          * "blocked by NMI" bit has to be set before next VM entry.
5616          * There are errata that may cause this bit to not be set:
5617          * AAK134, BY25.
5618          */
5619         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5620                         enable_vnmi &&
5621                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5622                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5623
5624         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5625         trace_kvm_page_fault(vcpu, gpa, exit_qualification);
5626
5627         /* Is it a read fault? */
5628         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5629                      ? PFERR_USER_MASK : 0;
5630         /* Is it a write fault? */
5631         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5632                       ? PFERR_WRITE_MASK : 0;
5633         /* Is it a fetch fault? */
5634         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5635                       ? PFERR_FETCH_MASK : 0;
5636         /* ept page table entry is present? */
5637         error_code |= (exit_qualification & EPT_VIOLATION_RWX_MASK)
5638                       ? PFERR_PRESENT_MASK : 0;
5639
5640         error_code |= (exit_qualification & EPT_VIOLATION_GVA_TRANSLATED) != 0 ?
5641                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5642
5643         vcpu->arch.exit_qualification = exit_qualification;
5644
5645         /*
5646          * Check that the GPA doesn't exceed physical memory limits, as that is
5647          * a guest page fault.  We have to emulate the instruction here, because
5648          * if the illegal address is that of a paging structure, then
5649          * EPT_VIOLATION_ACC_WRITE bit is set.  Alternatively, if supported we
5650          * would also use advanced VM-exit information for EPT violations to
5651          * reconstruct the page fault error code.
5652          */
5653         if (unlikely(allow_smaller_maxphyaddr && kvm_vcpu_is_illegal_gpa(vcpu, gpa)))
5654                 return kvm_emulate_instruction(vcpu, 0);
5655
5656         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5657 }
5658
5659 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5660 {
5661         gpa_t gpa;
5662
5663         if (!vmx_can_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0))
5664                 return 1;
5665
5666         /*
5667          * A nested guest cannot optimize MMIO vmexits, because we have an
5668          * nGPA here instead of the required GPA.
5669          */
5670         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5671         if (!is_guest_mode(vcpu) &&
5672             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5673                 trace_kvm_fast_mmio(gpa);
5674                 return kvm_skip_emulated_instruction(vcpu);
5675         }
5676
5677         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5678 }
5679
5680 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5681 {
5682         if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm))
5683                 return -EIO;
5684
5685         exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5686         ++vcpu->stat.nmi_window_exits;
5687         kvm_make_request(KVM_REQ_EVENT, vcpu);
5688
5689         return 1;
5690 }
5691
5692 static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
5693 {
5694         struct vcpu_vmx *vmx = to_vmx(vcpu);
5695
5696         return vmx->emulation_required && !vmx->rmode.vm86_active &&
5697                (vcpu->arch.exception.pending || vcpu->arch.exception.injected);
5698 }
5699
5700 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5701 {
5702         struct vcpu_vmx *vmx = to_vmx(vcpu);
5703         bool intr_window_requested;
5704         unsigned count = 130;
5705
5706         intr_window_requested = exec_controls_get(vmx) &
5707                                 CPU_BASED_INTR_WINDOW_EXITING;
5708
5709         while (vmx->emulation_required && count-- != 0) {
5710                 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5711                         return handle_interrupt_window(&vmx->vcpu);
5712
5713                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5714                         return 1;
5715
5716                 if (!kvm_emulate_instruction(vcpu, 0))
5717                         return 0;
5718
5719                 if (vmx_emulation_required_with_pending_exception(vcpu)) {
5720                         kvm_prepare_emulation_failure_exit(vcpu);
5721                         return 0;
5722                 }
5723
5724                 if (vcpu->arch.halt_request) {
5725                         vcpu->arch.halt_request = 0;
5726                         return kvm_emulate_halt_noskip(vcpu);
5727                 }
5728
5729                 /*
5730                  * Note, return 1 and not 0, vcpu_run() will invoke
5731                  * xfer_to_guest_mode() which will create a proper return
5732                  * code.
5733                  */
5734                 if (__xfer_to_guest_mode_work_pending())
5735                         return 1;
5736         }
5737
5738         return 1;
5739 }
5740
5741 static int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu)
5742 {
5743         if (vmx_emulation_required_with_pending_exception(vcpu)) {
5744                 kvm_prepare_emulation_failure_exit(vcpu);
5745                 return 0;
5746         }
5747
5748         return 1;
5749 }
5750
5751 static void grow_ple_window(struct kvm_vcpu *vcpu)
5752 {
5753         struct vcpu_vmx *vmx = to_vmx(vcpu);
5754         unsigned int old = vmx->ple_window;
5755
5756         vmx->ple_window = __grow_ple_window(old, ple_window,
5757                                             ple_window_grow,
5758                                             ple_window_max);
5759
5760         if (vmx->ple_window != old) {
5761                 vmx->ple_window_dirty = true;
5762                 trace_kvm_ple_window_update(vcpu->vcpu_id,
5763                                             vmx->ple_window, old);
5764         }
5765 }
5766
5767 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5768 {
5769         struct vcpu_vmx *vmx = to_vmx(vcpu);
5770         unsigned int old = vmx->ple_window;
5771
5772         vmx->ple_window = __shrink_ple_window(old, ple_window,
5773                                               ple_window_shrink,
5774                                               ple_window);
5775
5776         if (vmx->ple_window != old) {
5777                 vmx->ple_window_dirty = true;
5778                 trace_kvm_ple_window_update(vcpu->vcpu_id,
5779                                             vmx->ple_window, old);
5780         }
5781 }
5782
5783 /*
5784  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5785  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5786  */
5787 static int handle_pause(struct kvm_vcpu *vcpu)
5788 {
5789         if (!kvm_pause_in_guest(vcpu->kvm))
5790                 grow_ple_window(vcpu);
5791
5792         /*
5793          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5794          * VM-execution control is ignored if CPL > 0. OTOH, KVM
5795          * never set PAUSE_EXITING and just set PLE if supported,
5796          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5797          */
5798         kvm_vcpu_on_spin(vcpu, true);
5799         return kvm_skip_emulated_instruction(vcpu);
5800 }
5801
5802 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5803 {
5804         return 1;
5805 }
5806
5807 static int handle_invpcid(struct kvm_vcpu *vcpu)
5808 {
5809         u32 vmx_instruction_info;
5810         unsigned long type;
5811         gva_t gva;
5812         struct {
5813                 u64 pcid;
5814                 u64 gla;
5815         } operand;
5816         int gpr_index;
5817
5818         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5819                 kvm_queue_exception(vcpu, UD_VECTOR);
5820                 return 1;
5821         }
5822
5823         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5824         gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info);
5825         type = kvm_register_read(vcpu, gpr_index);
5826
5827         /* According to the Intel instruction reference, the memory operand
5828          * is read even if it isn't needed (e.g., for type==all)
5829          */
5830         if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5831                                 vmx_instruction_info, false,
5832                                 sizeof(operand), &gva))
5833                 return 1;
5834
5835         return kvm_handle_invpcid(vcpu, type, gva);
5836 }
5837
5838 static int handle_pml_full(struct kvm_vcpu *vcpu)
5839 {
5840         unsigned long exit_qualification;
5841
5842         trace_kvm_pml_full(vcpu->vcpu_id);
5843
5844         exit_qualification = vmx_get_exit_qual(vcpu);
5845
5846         /*
5847          * PML buffer FULL happened while executing iret from NMI,
5848          * "blocked by NMI" bit has to be set before next VM entry.
5849          */
5850         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5851                         enable_vnmi &&
5852                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5853                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5854                                 GUEST_INTR_STATE_NMI);
5855
5856         /*
5857          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5858          * here.., and there's no userspace involvement needed for PML.
5859          */
5860         return 1;
5861 }
5862
5863 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5864 {
5865         struct vcpu_vmx *vmx = to_vmx(vcpu);
5866
5867         if (!vmx->req_immediate_exit &&
5868             !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5869                 kvm_lapic_expired_hv_timer(vcpu);
5870                 return EXIT_FASTPATH_REENTER_GUEST;
5871         }
5872
5873         return EXIT_FASTPATH_NONE;
5874 }
5875
5876 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5877 {
5878         handle_fastpath_preemption_timer(vcpu);
5879         return 1;
5880 }
5881
5882 /*
5883  * When nested=0, all VMX instruction VM Exits filter here.  The handlers
5884  * are overwritten by nested_vmx_setup() when nested=1.
5885  */
5886 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5887 {
5888         kvm_queue_exception(vcpu, UD_VECTOR);
5889         return 1;
5890 }
5891
5892 #ifndef CONFIG_X86_SGX_KVM
5893 static int handle_encls(struct kvm_vcpu *vcpu)
5894 {
5895         /*
5896          * SGX virtualization is disabled.  There is no software enable bit for
5897          * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent
5898          * the guest from executing ENCLS (when SGX is supported by hardware).
5899          */
5900         kvm_queue_exception(vcpu, UD_VECTOR);
5901         return 1;
5902 }
5903 #endif /* CONFIG_X86_SGX_KVM */
5904
5905 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu)
5906 {
5907         /*
5908          * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK
5909          * VM-Exits. Unconditionally set the flag here and leave the handling to
5910          * vmx_handle_exit().
5911          */
5912         to_vmx(vcpu)->exit_reason.bus_lock_detected = true;
5913         return 1;
5914 }
5915
5916 static int handle_notify(struct kvm_vcpu *vcpu)
5917 {
5918         unsigned long exit_qual = vmx_get_exit_qual(vcpu);
5919         bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID;
5920
5921         ++vcpu->stat.notify_window_exits;
5922
5923         /*
5924          * Notify VM exit happened while executing iret from NMI,
5925          * "blocked by NMI" bit has to be set before next VM entry.
5926          */
5927         if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI))
5928                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5929                               GUEST_INTR_STATE_NMI);
5930
5931         if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER ||
5932             context_invalid) {
5933                 vcpu->run->exit_reason = KVM_EXIT_NOTIFY;
5934                 vcpu->run->notify.flags = context_invalid ?
5935                                           KVM_NOTIFY_CONTEXT_INVALID : 0;
5936                 return 0;
5937         }
5938
5939         return 1;
5940 }
5941
5942 /*
5943  * The exit handlers return 1 if the exit was handled fully and guest execution
5944  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
5945  * to be done to userspace and return 0.
5946  */
5947 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5948         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception_nmi,
5949         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
5950         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
5951         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
5952         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
5953         [EXIT_REASON_CR_ACCESS]               = handle_cr,
5954         [EXIT_REASON_DR_ACCESS]               = handle_dr,
5955         [EXIT_REASON_CPUID]                   = kvm_emulate_cpuid,
5956         [EXIT_REASON_MSR_READ]                = kvm_emulate_rdmsr,
5957         [EXIT_REASON_MSR_WRITE]               = kvm_emulate_wrmsr,
5958         [EXIT_REASON_INTERRUPT_WINDOW]        = handle_interrupt_window,
5959         [EXIT_REASON_HLT]                     = kvm_emulate_halt,
5960         [EXIT_REASON_INVD]                    = kvm_emulate_invd,
5961         [EXIT_REASON_INVLPG]                  = handle_invlpg,
5962         [EXIT_REASON_RDPMC]                   = kvm_emulate_rdpmc,
5963         [EXIT_REASON_VMCALL]                  = kvm_emulate_hypercall,
5964         [EXIT_REASON_VMCLEAR]                 = handle_vmx_instruction,
5965         [EXIT_REASON_VMLAUNCH]                = handle_vmx_instruction,
5966         [EXIT_REASON_VMPTRLD]                 = handle_vmx_instruction,
5967         [EXIT_REASON_VMPTRST]                 = handle_vmx_instruction,
5968         [EXIT_REASON_VMREAD]                  = handle_vmx_instruction,
5969         [EXIT_REASON_VMRESUME]                = handle_vmx_instruction,
5970         [EXIT_REASON_VMWRITE]                 = handle_vmx_instruction,
5971         [EXIT_REASON_VMOFF]                   = handle_vmx_instruction,
5972         [EXIT_REASON_VMON]                    = handle_vmx_instruction,
5973         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
5974         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
5975         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
5976         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
5977         [EXIT_REASON_WBINVD]                  = kvm_emulate_wbinvd,
5978         [EXIT_REASON_XSETBV]                  = kvm_emulate_xsetbv,
5979         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
5980         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
5981         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
5982         [EXIT_REASON_LDTR_TR]                 = handle_desc,
5983         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
5984         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
5985         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
5986         [EXIT_REASON_MWAIT_INSTRUCTION]       = kvm_emulate_mwait,
5987         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
5988         [EXIT_REASON_MONITOR_INSTRUCTION]     = kvm_emulate_monitor,
5989         [EXIT_REASON_INVEPT]                  = handle_vmx_instruction,
5990         [EXIT_REASON_INVVPID]                 = handle_vmx_instruction,
5991         [EXIT_REASON_RDRAND]                  = kvm_handle_invalid_op,
5992         [EXIT_REASON_RDSEED]                  = kvm_handle_invalid_op,
5993         [EXIT_REASON_PML_FULL]                = handle_pml_full,
5994         [EXIT_REASON_INVPCID]                 = handle_invpcid,
5995         [EXIT_REASON_VMFUNC]                  = handle_vmx_instruction,
5996         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
5997         [EXIT_REASON_ENCLS]                   = handle_encls,
5998         [EXIT_REASON_BUS_LOCK]                = handle_bus_lock_vmexit,
5999         [EXIT_REASON_NOTIFY]                  = handle_notify,
6000 };
6001
6002 static const int kvm_vmx_max_exit_handlers =
6003         ARRAY_SIZE(kvm_vmx_exit_handlers);
6004
6005 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
6006                               u64 *info1, u64 *info2,
6007                               u32 *intr_info, u32 *error_code)
6008 {
6009         struct vcpu_vmx *vmx = to_vmx(vcpu);
6010
6011         *reason = vmx->exit_reason.full;
6012         *info1 = vmx_get_exit_qual(vcpu);
6013         if (!(vmx->exit_reason.failed_vmentry)) {
6014                 *info2 = vmx->idt_vectoring_info;
6015                 *intr_info = vmx_get_intr_info(vcpu);
6016                 if (is_exception_with_error_code(*intr_info))
6017                         *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6018                 else
6019                         *error_code = 0;
6020         } else {
6021                 *info2 = 0;
6022                 *intr_info = 0;
6023                 *error_code = 0;
6024         }
6025 }
6026
6027 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
6028 {
6029         if (vmx->pml_pg) {
6030                 __free_page(vmx->pml_pg);
6031                 vmx->pml_pg = NULL;
6032         }
6033 }
6034
6035 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
6036 {
6037         struct vcpu_vmx *vmx = to_vmx(vcpu);
6038         u64 *pml_buf;
6039         u16 pml_idx;
6040
6041         pml_idx = vmcs_read16(GUEST_PML_INDEX);
6042
6043         /* Do nothing if PML buffer is empty */
6044         if (pml_idx == (PML_ENTITY_NUM - 1))
6045                 return;
6046
6047         /* PML index always points to next available PML buffer entity */
6048         if (pml_idx >= PML_ENTITY_NUM)
6049                 pml_idx = 0;
6050         else
6051                 pml_idx++;
6052
6053         pml_buf = page_address(vmx->pml_pg);
6054         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
6055                 u64 gpa;
6056
6057                 gpa = pml_buf[pml_idx];
6058                 WARN_ON(gpa & (PAGE_SIZE - 1));
6059                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
6060         }
6061
6062         /* reset PML index */
6063         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6064 }
6065
6066 static void vmx_dump_sel(char *name, uint32_t sel)
6067 {
6068         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
6069                name, vmcs_read16(sel),
6070                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
6071                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
6072                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
6073 }
6074
6075 static void vmx_dump_dtsel(char *name, uint32_t limit)
6076 {
6077         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
6078                name, vmcs_read32(limit),
6079                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
6080 }
6081
6082 static void vmx_dump_msrs(char *name, struct vmx_msrs *m)
6083 {
6084         unsigned int i;
6085         struct vmx_msr_entry *e;
6086
6087         pr_err("MSR %s:\n", name);
6088         for (i = 0, e = m->val; i < m->nr; ++i, ++e)
6089                 pr_err("  %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value);
6090 }
6091
6092 void dump_vmcs(struct kvm_vcpu *vcpu)
6093 {
6094         struct vcpu_vmx *vmx = to_vmx(vcpu);
6095         u32 vmentry_ctl, vmexit_ctl;
6096         u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
6097         u64 tertiary_exec_control;
6098         unsigned long cr4;
6099         int efer_slot;
6100
6101         if (!dump_invalid_vmcs) {
6102                 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
6103                 return;
6104         }
6105
6106         vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
6107         vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
6108         cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6109         pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
6110         cr4 = vmcs_readl(GUEST_CR4);
6111
6112         if (cpu_has_secondary_exec_ctrls())
6113                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
6114         else
6115                 secondary_exec_control = 0;
6116
6117         if (cpu_has_tertiary_exec_ctrls())
6118                 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL);
6119         else
6120                 tertiary_exec_control = 0;
6121
6122         pr_err("VMCS %p, last attempted VM-entry on CPU %d\n",
6123                vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu);
6124         pr_err("*** Guest State ***\n");
6125         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6126                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
6127                vmcs_readl(CR0_GUEST_HOST_MASK));
6128         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
6129                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
6130         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
6131         if (cpu_has_vmx_ept()) {
6132                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
6133                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
6134                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
6135                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
6136         }
6137         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
6138                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
6139         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
6140                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
6141         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6142                vmcs_readl(GUEST_SYSENTER_ESP),
6143                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
6144         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
6145         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
6146         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
6147         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
6148         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
6149         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
6150         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
6151         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
6152         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
6153         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
6154         efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
6155         if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
6156                 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
6157         else if (efer_slot >= 0)
6158                 pr_err("EFER= 0x%016llx (autoload)\n",
6159                        vmx->msr_autoload.guest.val[efer_slot].value);
6160         else if (vmentry_ctl & VM_ENTRY_IA32E_MODE)
6161                 pr_err("EFER= 0x%016llx (effective)\n",
6162                        vcpu->arch.efer | (EFER_LMA | EFER_LME));
6163         else
6164                 pr_err("EFER= 0x%016llx (effective)\n",
6165                        vcpu->arch.efer & ~(EFER_LMA | EFER_LME));
6166         if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT)
6167                 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT));
6168         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
6169                vmcs_read64(GUEST_IA32_DEBUGCTL),
6170                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
6171         if (cpu_has_load_perf_global_ctrl() &&
6172             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
6173                 pr_err("PerfGlobCtl = 0x%016llx\n",
6174                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
6175         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
6176                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
6177         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
6178                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
6179                vmcs_read32(GUEST_ACTIVITY_STATE));
6180         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
6181                 pr_err("InterruptStatus = %04x\n",
6182                        vmcs_read16(GUEST_INTR_STATUS));
6183         if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0)
6184                 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest);
6185         if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0)
6186                 vmx_dump_msrs("guest autostore", &vmx->msr_autostore.guest);
6187
6188         pr_err("*** Host State ***\n");
6189         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
6190                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
6191         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
6192                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
6193                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
6194                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
6195                vmcs_read16(HOST_TR_SELECTOR));
6196         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
6197                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
6198                vmcs_readl(HOST_TR_BASE));
6199         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
6200                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
6201         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
6202                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
6203                vmcs_readl(HOST_CR4));
6204         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
6205                vmcs_readl(HOST_IA32_SYSENTER_ESP),
6206                vmcs_read32(HOST_IA32_SYSENTER_CS),
6207                vmcs_readl(HOST_IA32_SYSENTER_EIP));
6208         if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER)
6209                 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER));
6210         if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT)
6211                 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT));
6212         if (cpu_has_load_perf_global_ctrl() &&
6213             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
6214                 pr_err("PerfGlobCtl = 0x%016llx\n",
6215                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
6216         if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0)
6217                 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host);
6218
6219         pr_err("*** Control State ***\n");
6220         pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
6221                cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
6222         pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
6223                pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
6224         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
6225                vmcs_read32(EXCEPTION_BITMAP),
6226                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
6227                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
6228         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
6229                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6230                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
6231                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
6232         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
6233                vmcs_read32(VM_EXIT_INTR_INFO),
6234                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
6235                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
6236         pr_err("        reason=%08x qualification=%016lx\n",
6237                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
6238         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
6239                vmcs_read32(IDT_VECTORING_INFO_FIELD),
6240                vmcs_read32(IDT_VECTORING_ERROR_CODE));
6241         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
6242         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
6243                 pr_err("TSC Multiplier = 0x%016llx\n",
6244                        vmcs_read64(TSC_MULTIPLIER));
6245         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
6246                 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
6247                         u16 status = vmcs_read16(GUEST_INTR_STATUS);
6248                         pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
6249                 }
6250                 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
6251                 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
6252                         pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
6253                 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
6254         }
6255         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
6256                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
6257         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
6258                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
6259         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
6260                 pr_err("PLE Gap=%08x Window=%08x\n",
6261                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
6262         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
6263                 pr_err("Virtual processor ID = 0x%04x\n",
6264                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
6265 }
6266
6267 /*
6268  * The guest has exited.  See if we can fix it or if we need userspace
6269  * assistance.
6270  */
6271 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6272 {
6273         struct vcpu_vmx *vmx = to_vmx(vcpu);
6274         union vmx_exit_reason exit_reason = vmx->exit_reason;
6275         u32 vectoring_info = vmx->idt_vectoring_info;
6276         u16 exit_handler_index;
6277
6278         /*
6279          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
6280          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
6281          * querying dirty_bitmap, we only need to kick all vcpus out of guest
6282          * mode as if vcpus is in root mode, the PML buffer must has been
6283          * flushed already.  Note, PML is never enabled in hardware while
6284          * running L2.
6285          */
6286         if (enable_pml && !is_guest_mode(vcpu))
6287                 vmx_flush_pml_buffer(vcpu);
6288
6289         /*
6290          * KVM should never reach this point with a pending nested VM-Enter.
6291          * More specifically, short-circuiting VM-Entry to emulate L2 due to
6292          * invalid guest state should never happen as that means KVM knowingly
6293          * allowed a nested VM-Enter with an invalid vmcs12.  More below.
6294          */
6295         if (KVM_BUG_ON(vmx->nested.nested_run_pending, vcpu->kvm))
6296                 return -EIO;
6297
6298         if (is_guest_mode(vcpu)) {
6299                 /*
6300                  * PML is never enabled when running L2, bail immediately if a
6301                  * PML full exit occurs as something is horribly wrong.
6302                  */
6303                 if (exit_reason.basic == EXIT_REASON_PML_FULL)
6304                         goto unexpected_vmexit;
6305
6306                 /*
6307                  * The host physical addresses of some pages of guest memory
6308                  * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6309                  * Page). The CPU may write to these pages via their host
6310                  * physical address while L2 is running, bypassing any
6311                  * address-translation-based dirty tracking (e.g. EPT write
6312                  * protection).
6313                  *
6314                  * Mark them dirty on every exit from L2 to prevent them from
6315                  * getting out of sync with dirty tracking.
6316                  */
6317                 nested_mark_vmcs12_pages_dirty(vcpu);
6318
6319                 /*
6320                  * Synthesize a triple fault if L2 state is invalid.  In normal
6321                  * operation, nested VM-Enter rejects any attempt to enter L2
6322                  * with invalid state.  However, those checks are skipped if
6323                  * state is being stuffed via RSM or KVM_SET_NESTED_STATE.  If
6324                  * L2 state is invalid, it means either L1 modified SMRAM state
6325                  * or userspace provided bad state.  Synthesize TRIPLE_FAULT as
6326                  * doing so is architecturally allowed in the RSM case, and is
6327                  * the least awful solution for the userspace case without
6328                  * risking false positives.
6329                  */
6330                 if (vmx->emulation_required) {
6331                         nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0);
6332                         return 1;
6333                 }
6334
6335                 if (nested_vmx_reflect_vmexit(vcpu))
6336                         return 1;
6337         }
6338
6339         /* If guest state is invalid, start emulating.  L2 is handled above. */
6340         if (vmx->emulation_required)
6341                 return handle_invalid_guest_state(vcpu);
6342
6343         if (exit_reason.failed_vmentry) {
6344                 dump_vmcs(vcpu);
6345                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6346                 vcpu->run->fail_entry.hardware_entry_failure_reason
6347                         = exit_reason.full;
6348                 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6349                 return 0;
6350         }
6351
6352         if (unlikely(vmx->fail)) {
6353                 dump_vmcs(vcpu);
6354                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6355                 vcpu->run->fail_entry.hardware_entry_failure_reason
6356                         = vmcs_read32(VM_INSTRUCTION_ERROR);
6357                 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6358                 return 0;
6359         }
6360
6361         /*
6362          * Note:
6363          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6364          * delivery event since it indicates guest is accessing MMIO.
6365          * The vm-exit can be triggered again after return to guest that
6366          * will cause infinite loop.
6367          */
6368         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6369             (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI &&
6370              exit_reason.basic != EXIT_REASON_EPT_VIOLATION &&
6371              exit_reason.basic != EXIT_REASON_PML_FULL &&
6372              exit_reason.basic != EXIT_REASON_APIC_ACCESS &&
6373              exit_reason.basic != EXIT_REASON_TASK_SWITCH &&
6374              exit_reason.basic != EXIT_REASON_NOTIFY)) {
6375                 int ndata = 3;
6376
6377                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6378                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6379                 vcpu->run->internal.data[0] = vectoring_info;
6380                 vcpu->run->internal.data[1] = exit_reason.full;
6381                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6382                 if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) {
6383                         vcpu->run->internal.data[ndata++] =
6384                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6385                 }
6386                 vcpu->run->internal.data[ndata++] = vcpu->arch.last_vmentry_cpu;
6387                 vcpu->run->internal.ndata = ndata;
6388                 return 0;
6389         }
6390
6391         if (unlikely(!enable_vnmi &&
6392                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
6393                 if (!vmx_interrupt_blocked(vcpu)) {
6394                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6395                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6396                            vcpu->arch.nmi_pending) {
6397                         /*
6398                          * This CPU don't support us in finding the end of an
6399                          * NMI-blocked window if the guest runs with IRQs
6400                          * disabled. So we pull the trigger after 1 s of
6401                          * futile waiting, but inform the user about this.
6402                          */
6403                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6404                                "state on VCPU %d after 1 s timeout\n",
6405                                __func__, vcpu->vcpu_id);
6406                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6407                 }
6408         }
6409
6410         if (exit_fastpath != EXIT_FASTPATH_NONE)
6411                 return 1;
6412
6413         if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
6414                 goto unexpected_vmexit;
6415 #ifdef CONFIG_RETPOLINE
6416         if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
6417                 return kvm_emulate_wrmsr(vcpu);
6418         else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER)
6419                 return handle_preemption_timer(vcpu);
6420         else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW)
6421                 return handle_interrupt_window(vcpu);
6422         else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6423                 return handle_external_interrupt(vcpu);
6424         else if (exit_reason.basic == EXIT_REASON_HLT)
6425                 return kvm_emulate_halt(vcpu);
6426         else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG)
6427                 return handle_ept_misconfig(vcpu);
6428 #endif
6429
6430         exit_handler_index = array_index_nospec((u16)exit_reason.basic,
6431                                                 kvm_vmx_max_exit_handlers);
6432         if (!kvm_vmx_exit_handlers[exit_handler_index])
6433                 goto unexpected_vmexit;
6434
6435         return kvm_vmx_exit_handlers[exit_handler_index](vcpu);
6436
6437 unexpected_vmexit:
6438         vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
6439                     exit_reason.full);
6440         dump_vmcs(vcpu);
6441         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6442         vcpu->run->internal.suberror =
6443                         KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6444         vcpu->run->internal.ndata = 2;
6445         vcpu->run->internal.data[0] = exit_reason.full;
6446         vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6447         return 0;
6448 }
6449
6450 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
6451 {
6452         int ret = __vmx_handle_exit(vcpu, exit_fastpath);
6453
6454         /*
6455          * Exit to user space when bus lock detected to inform that there is
6456          * a bus lock in guest.
6457          */
6458         if (to_vmx(vcpu)->exit_reason.bus_lock_detected) {
6459                 if (ret > 0)
6460                         vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK;
6461
6462                 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK;
6463                 return 0;
6464         }
6465         return ret;
6466 }
6467
6468 /*
6469  * Software based L1D cache flush which is used when microcode providing
6470  * the cache control MSR is not loaded.
6471  *
6472  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6473  * flush it is required to read in 64 KiB because the replacement algorithm
6474  * is not exactly LRU. This could be sized at runtime via topology
6475  * information but as all relevant affected CPUs have 32KiB L1D cache size
6476  * there is no point in doing so.
6477  */
6478 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6479 {
6480         int size = PAGE_SIZE << L1D_CACHE_ORDER;
6481
6482         /*
6483          * This code is only executed when the flush mode is 'cond' or
6484          * 'always'
6485          */
6486         if (static_branch_likely(&vmx_l1d_flush_cond)) {
6487                 bool flush_l1d;
6488
6489                 /*
6490                  * Clear the per-vcpu flush bit, it gets set again
6491                  * either from vcpu_run() or from one of the unsafe
6492                  * VMEXIT handlers.
6493                  */
6494                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6495                 vcpu->arch.l1tf_flush_l1d = false;
6496
6497                 /*
6498                  * Clear the per-cpu flush bit, it gets set again from
6499                  * the interrupt handlers.
6500                  */
6501                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6502                 kvm_clear_cpu_l1tf_flush_l1d();
6503
6504                 if (!flush_l1d)
6505                         return;
6506         }
6507
6508         vcpu->stat.l1d_flush++;
6509
6510         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6511                 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6512                 return;
6513         }
6514
6515         asm volatile(
6516                 /* First ensure the pages are in the TLB */
6517                 "xorl   %%eax, %%eax\n"
6518                 ".Lpopulate_tlb:\n\t"
6519                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6520                 "addl   $4096, %%eax\n\t"
6521                 "cmpl   %%eax, %[size]\n\t"
6522                 "jne    .Lpopulate_tlb\n\t"
6523                 "xorl   %%eax, %%eax\n\t"
6524                 "cpuid\n\t"
6525                 /* Now fill the cache */
6526                 "xorl   %%eax, %%eax\n"
6527                 ".Lfill_cache:\n"
6528                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6529                 "addl   $64, %%eax\n\t"
6530                 "cmpl   %%eax, %[size]\n\t"
6531                 "jne    .Lfill_cache\n\t"
6532                 "lfence\n"
6533                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6534                     [size] "r" (size)
6535                 : "eax", "ebx", "ecx", "edx");
6536 }
6537
6538 static void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6539 {
6540         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6541         int tpr_threshold;
6542
6543         if (is_guest_mode(vcpu) &&
6544                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6545                 return;
6546
6547         tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6548         if (is_guest_mode(vcpu))
6549                 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6550         else
6551                 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6552 }
6553
6554 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6555 {
6556         struct vcpu_vmx *vmx = to_vmx(vcpu);
6557         u32 sec_exec_control;
6558
6559         if (!lapic_in_kernel(vcpu))
6560                 return;
6561
6562         if (!flexpriority_enabled &&
6563             !cpu_has_vmx_virtualize_x2apic_mode())
6564                 return;
6565
6566         /* Postpone execution until vmcs01 is the current VMCS. */
6567         if (is_guest_mode(vcpu)) {
6568                 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6569                 return;
6570         }
6571
6572         sec_exec_control = secondary_exec_controls_get(vmx);
6573         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6574                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6575
6576         switch (kvm_get_apic_mode(vcpu)) {
6577         case LAPIC_MODE_INVALID:
6578                 WARN_ONCE(true, "Invalid local APIC state");
6579                 break;
6580         case LAPIC_MODE_DISABLED:
6581                 break;
6582         case LAPIC_MODE_XAPIC:
6583                 if (flexpriority_enabled) {
6584                         sec_exec_control |=
6585                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6586                         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6587
6588                         /*
6589                          * Flush the TLB, reloading the APIC access page will
6590                          * only do so if its physical address has changed, but
6591                          * the guest may have inserted a non-APIC mapping into
6592                          * the TLB while the APIC access page was disabled.
6593                          */
6594                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6595                 }
6596                 break;
6597         case LAPIC_MODE_X2APIC:
6598                 if (cpu_has_vmx_virtualize_x2apic_mode())
6599                         sec_exec_control |=
6600                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6601                 break;
6602         }
6603         secondary_exec_controls_set(vmx, sec_exec_control);
6604
6605         vmx_update_msr_bitmap_x2apic(vcpu);
6606 }
6607
6608 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6609 {
6610         struct page *page;
6611
6612         /* Defer reload until vmcs01 is the current VMCS. */
6613         if (is_guest_mode(vcpu)) {
6614                 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6615                 return;
6616         }
6617
6618         if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6619             SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6620                 return;
6621
6622         page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6623         if (is_error_page(page))
6624                 return;
6625
6626         vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6627         vmx_flush_tlb_current(vcpu);
6628
6629         /*
6630          * Do not pin apic access page in memory, the MMU notifier
6631          * will call us again if it is migrated or swapped out.
6632          */
6633         put_page(page);
6634 }
6635
6636 static void vmx_hwapic_isr_update(int max_isr)
6637 {
6638         u16 status;
6639         u8 old;
6640
6641         if (max_isr == -1)
6642                 max_isr = 0;
6643
6644         status = vmcs_read16(GUEST_INTR_STATUS);
6645         old = status >> 8;
6646         if (max_isr != old) {
6647                 status &= 0xff;
6648                 status |= max_isr << 8;
6649                 vmcs_write16(GUEST_INTR_STATUS, status);
6650         }
6651 }
6652
6653 static void vmx_set_rvi(int vector)
6654 {
6655         u16 status;
6656         u8 old;
6657
6658         if (vector == -1)
6659                 vector = 0;
6660
6661         status = vmcs_read16(GUEST_INTR_STATUS);
6662         old = (u8)status & 0xff;
6663         if ((u8)vector != old) {
6664                 status &= ~0xff;
6665                 status |= (u8)vector;
6666                 vmcs_write16(GUEST_INTR_STATUS, status);
6667         }
6668 }
6669
6670 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6671 {
6672         /*
6673          * When running L2, updating RVI is only relevant when
6674          * vmcs12 virtual-interrupt-delivery enabled.
6675          * However, it can be enabled only when L1 also
6676          * intercepts external-interrupts and in that case
6677          * we should not update vmcs02 RVI but instead intercept
6678          * interrupt. Therefore, do nothing when running L2.
6679          */
6680         if (!is_guest_mode(vcpu))
6681                 vmx_set_rvi(max_irr);
6682 }
6683
6684 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6685 {
6686         struct vcpu_vmx *vmx = to_vmx(vcpu);
6687         int max_irr;
6688         bool got_posted_interrupt;
6689
6690         if (KVM_BUG_ON(!enable_apicv, vcpu->kvm))
6691                 return -EIO;
6692
6693         if (pi_test_on(&vmx->pi_desc)) {
6694                 pi_clear_on(&vmx->pi_desc);
6695                 /*
6696                  * IOMMU can write to PID.ON, so the barrier matters even on UP.
6697                  * But on x86 this is just a compiler barrier anyway.
6698                  */
6699                 smp_mb__after_atomic();
6700                 got_posted_interrupt =
6701                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6702         } else {
6703                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6704                 got_posted_interrupt = false;
6705         }
6706
6707         /*
6708          * Newly recognized interrupts are injected via either virtual interrupt
6709          * delivery (RVI) or KVM_REQ_EVENT.  Virtual interrupt delivery is
6710          * disabled in two cases:
6711          *
6712          * 1) If L2 is running and the vCPU has a new pending interrupt.  If L1
6713          * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a
6714          * VM-Exit to L1.  If L1 doesn't want to exit, the interrupt is injected
6715          * into L2, but KVM doesn't use virtual interrupt delivery to inject
6716          * interrupts into L2, and so KVM_REQ_EVENT is again needed.
6717          *
6718          * 2) If APICv is disabled for this vCPU, assigned devices may still
6719          * attempt to post interrupts.  The posted interrupt vector will cause
6720          * a VM-Exit and the subsequent entry will call sync_pir_to_irr.
6721          */
6722         if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu))
6723                 vmx_set_rvi(max_irr);
6724         else if (got_posted_interrupt)
6725                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6726
6727         return max_irr;
6728 }
6729
6730 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6731 {
6732         if (!kvm_vcpu_apicv_active(vcpu))
6733                 return;
6734
6735         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6736         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6737         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6738         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6739 }
6740
6741 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6742 {
6743         struct vcpu_vmx *vmx = to_vmx(vcpu);
6744
6745         pi_clear_on(&vmx->pi_desc);
6746         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6747 }
6748
6749 void vmx_do_interrupt_nmi_irqoff(unsigned long entry);
6750
6751 static void handle_interrupt_nmi_irqoff(struct kvm_vcpu *vcpu,
6752                                         unsigned long entry)
6753 {
6754         bool is_nmi = entry == (unsigned long)asm_exc_nmi_noist;
6755
6756         kvm_before_interrupt(vcpu, is_nmi ? KVM_HANDLING_NMI : KVM_HANDLING_IRQ);
6757         vmx_do_interrupt_nmi_irqoff(entry);
6758         kvm_after_interrupt(vcpu);
6759 }
6760
6761 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
6762 {
6763         /*
6764          * Save xfd_err to guest_fpu before interrupt is enabled, so the
6765          * MSR value is not clobbered by the host activity before the guest
6766          * has chance to consume it.
6767          *
6768          * Do not blindly read xfd_err here, since this exception might
6769          * be caused by L1 interception on a platform which doesn't
6770          * support xfd at all.
6771          *
6772          * Do it conditionally upon guest_fpu::xfd. xfd_err matters
6773          * only when xfd contains a non-zero value.
6774          *
6775          * Queuing exception is done in vmx_handle_exit. See comment there.
6776          */
6777         if (vcpu->arch.guest_fpu.fpstate->xfd)
6778                 rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
6779 }
6780
6781 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6782 {
6783         const unsigned long nmi_entry = (unsigned long)asm_exc_nmi_noist;
6784         u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6785
6786         /* if exit due to PF check for async PF */
6787         if (is_page_fault(intr_info))
6788                 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6789         /* if exit due to NM, handle before interrupts are enabled */
6790         else if (is_nm_fault(intr_info))
6791                 handle_nm_fault_irqoff(&vmx->vcpu);
6792         /* Handle machine checks before interrupts are enabled */
6793         else if (is_machine_check(intr_info))
6794                 kvm_machine_check();
6795         /* We need to handle NMIs before interrupts are enabled */
6796         else if (is_nmi(intr_info))
6797                 handle_interrupt_nmi_irqoff(&vmx->vcpu, nmi_entry);
6798 }
6799
6800 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6801 {
6802         u32 intr_info = vmx_get_intr_info(vcpu);
6803         unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK;
6804         gate_desc *desc = (gate_desc *)host_idt_base + vector;
6805
6806         if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm,
6807             "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6808                 return;
6809
6810         handle_interrupt_nmi_irqoff(vcpu, gate_offset(desc));
6811         vcpu->arch.at_instruction_boundary = true;
6812 }
6813
6814 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6815 {
6816         struct vcpu_vmx *vmx = to_vmx(vcpu);
6817
6818         if (vmx->emulation_required)
6819                 return;
6820
6821         if (vmx->exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT)
6822                 handle_external_interrupt_irqoff(vcpu);
6823         else if (vmx->exit_reason.basic == EXIT_REASON_EXCEPTION_NMI)
6824                 handle_exception_nmi_irqoff(vmx);
6825 }
6826
6827 /*
6828  * The kvm parameter can be NULL (module initialization, or invocation before
6829  * VM creation). Be sure to check the kvm parameter before using it.
6830  */
6831 static bool vmx_has_emulated_msr(struct kvm *kvm, u32 index)
6832 {
6833         switch (index) {
6834         case MSR_IA32_SMBASE:
6835                 /*
6836                  * We cannot do SMM unless we can run the guest in big
6837                  * real mode.
6838                  */
6839                 return enable_unrestricted_guest || emulate_invalid_guest_state;
6840         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6841                 return nested;
6842         case MSR_AMD64_VIRT_SPEC_CTRL:
6843         case MSR_AMD64_TSC_RATIO:
6844                 /* This is AMD only.  */
6845                 return false;
6846         default:
6847                 return true;
6848         }
6849 }
6850
6851 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6852 {
6853         u32 exit_intr_info;
6854         bool unblock_nmi;
6855         u8 vector;
6856         bool idtv_info_valid;
6857
6858         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6859
6860         if (enable_vnmi) {
6861                 if (vmx->loaded_vmcs->nmi_known_unmasked)
6862                         return;
6863
6864                 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6865                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6866                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6867                 /*
6868                  * SDM 3: 27.7.1.2 (September 2008)
6869                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
6870                  * a guest IRET fault.
6871                  * SDM 3: 23.2.2 (September 2008)
6872                  * Bit 12 is undefined in any of the following cases:
6873                  *  If the VM exit sets the valid bit in the IDT-vectoring
6874                  *   information field.
6875                  *  If the VM exit is due to a double fault.
6876                  */
6877                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6878                     vector != DF_VECTOR && !idtv_info_valid)
6879                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6880                                       GUEST_INTR_STATE_NMI);
6881                 else
6882                         vmx->loaded_vmcs->nmi_known_unmasked =
6883                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6884                                   & GUEST_INTR_STATE_NMI);
6885         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6886                 vmx->loaded_vmcs->vnmi_blocked_time +=
6887                         ktime_to_ns(ktime_sub(ktime_get(),
6888                                               vmx->loaded_vmcs->entry_time));
6889 }
6890
6891 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6892                                       u32 idt_vectoring_info,
6893                                       int instr_len_field,
6894                                       int error_code_field)
6895 {
6896         u8 vector;
6897         int type;
6898         bool idtv_info_valid;
6899
6900         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6901
6902         vcpu->arch.nmi_injected = false;
6903         kvm_clear_exception_queue(vcpu);
6904         kvm_clear_interrupt_queue(vcpu);
6905
6906         if (!idtv_info_valid)
6907                 return;
6908
6909         kvm_make_request(KVM_REQ_EVENT, vcpu);
6910
6911         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6912         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6913
6914         switch (type) {
6915         case INTR_TYPE_NMI_INTR:
6916                 vcpu->arch.nmi_injected = true;
6917                 /*
6918                  * SDM 3: 27.7.1.2 (September 2008)
6919                  * Clear bit "block by NMI" before VM entry if a NMI
6920                  * delivery faulted.
6921                  */
6922                 vmx_set_nmi_mask(vcpu, false);
6923                 break;
6924         case INTR_TYPE_SOFT_EXCEPTION:
6925                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6926                 fallthrough;
6927         case INTR_TYPE_HARD_EXCEPTION:
6928                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6929                         u32 err = vmcs_read32(error_code_field);
6930                         kvm_requeue_exception_e(vcpu, vector, err);
6931                 } else
6932                         kvm_requeue_exception(vcpu, vector);
6933                 break;
6934         case INTR_TYPE_SOFT_INTR:
6935                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6936                 fallthrough;
6937         case INTR_TYPE_EXT_INTR:
6938                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6939                 break;
6940         default:
6941                 break;
6942         }
6943 }
6944
6945 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6946 {
6947         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6948                                   VM_EXIT_INSTRUCTION_LEN,
6949                                   IDT_VECTORING_ERROR_CODE);
6950 }
6951
6952 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6953 {
6954         __vmx_complete_interrupts(vcpu,
6955                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6956                                   VM_ENTRY_INSTRUCTION_LEN,
6957                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
6958
6959         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6960 }
6961
6962 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6963 {
6964         int i, nr_msrs;
6965         struct perf_guest_switch_msr *msrs;
6966         struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu);
6967
6968         pmu->host_cross_mapped_mask = 0;
6969         if (pmu->pebs_enable & pmu->global_ctrl)
6970                 intel_pmu_cross_mapped_check(pmu);
6971
6972         /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */
6973         msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu);
6974         if (!msrs)
6975                 return;
6976
6977         for (i = 0; i < nr_msrs; i++)
6978                 if (msrs[i].host == msrs[i].guest)
6979                         clear_atomic_switch_msr(vmx, msrs[i].msr);
6980                 else
6981                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6982                                         msrs[i].host, false);
6983 }
6984
6985 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6986 {
6987         struct vcpu_vmx *vmx = to_vmx(vcpu);
6988         u64 tscl;
6989         u32 delta_tsc;
6990
6991         if (vmx->req_immediate_exit) {
6992                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6993                 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6994         } else if (vmx->hv_deadline_tsc != -1) {
6995                 tscl = rdtsc();
6996                 if (vmx->hv_deadline_tsc > tscl)
6997                         /* set_hv_timer ensures the delta fits in 32-bits */
6998                         delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6999                                 cpu_preemption_timer_multi);
7000                 else
7001                         delta_tsc = 0;
7002
7003                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
7004                 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
7005         } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
7006                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
7007                 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
7008         }
7009 }
7010
7011 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
7012 {
7013         if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
7014                 vmx->loaded_vmcs->host_state.rsp = host_rsp;
7015                 vmcs_writel(HOST_RSP, host_rsp);
7016         }
7017 }
7018
7019 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx,
7020                                         unsigned int flags)
7021 {
7022         u64 hostval = this_cpu_read(x86_spec_ctrl_current);
7023
7024         if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL))
7025                 return;
7026
7027         if (flags & VMX_RUN_SAVE_SPEC_CTRL)
7028                 vmx->spec_ctrl = __rdmsr(MSR_IA32_SPEC_CTRL);
7029
7030         /*
7031          * If the guest/host SPEC_CTRL values differ, restore the host value.
7032          *
7033          * For legacy IBRS, the IBRS bit always needs to be written after
7034          * transitioning from a less privileged predictor mode, regardless of
7035          * whether the guest/host values differ.
7036          */
7037         if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) ||
7038             vmx->spec_ctrl != hostval)
7039                 native_wrmsrl(MSR_IA32_SPEC_CTRL, hostval);
7040
7041         barrier_nospec();
7042 }
7043
7044 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
7045 {
7046         switch (to_vmx(vcpu)->exit_reason.basic) {
7047         case EXIT_REASON_MSR_WRITE:
7048                 return handle_fastpath_set_msr_irqoff(vcpu);
7049         case EXIT_REASON_PREEMPTION_TIMER:
7050                 return handle_fastpath_preemption_timer(vcpu);
7051         default:
7052                 return EXIT_FASTPATH_NONE;
7053         }
7054 }
7055
7056 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
7057                                         struct vcpu_vmx *vmx,
7058                                         unsigned long flags)
7059 {
7060         guest_state_enter_irqoff();
7061
7062         /* L1D Flush includes CPU buffer clear to mitigate MDS */
7063         if (static_branch_unlikely(&vmx_l1d_should_flush))
7064                 vmx_l1d_flush(vcpu);
7065         else if (static_branch_unlikely(&mds_user_clear))
7066                 mds_clear_cpu_buffers();
7067         else if (static_branch_unlikely(&mmio_stale_data_clear) &&
7068                  kvm_arch_has_assigned_device(vcpu->kvm))
7069                 mds_clear_cpu_buffers();
7070
7071         vmx_disable_fb_clear(vmx);
7072
7073         if (vcpu->arch.cr2 != native_read_cr2())
7074                 native_write_cr2(vcpu->arch.cr2);
7075
7076         vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
7077                                    flags);
7078
7079         vcpu->arch.cr2 = native_read_cr2();
7080
7081         vmx_enable_fb_clear(vmx);
7082
7083         guest_state_exit_irqoff();
7084 }
7085
7086 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
7087 {
7088         struct vcpu_vmx *vmx = to_vmx(vcpu);
7089         unsigned long cr3, cr4;
7090
7091         /* Record the guest's net vcpu time for enforced NMI injections. */
7092         if (unlikely(!enable_vnmi &&
7093                      vmx->loaded_vmcs->soft_vnmi_blocked))
7094                 vmx->loaded_vmcs->entry_time = ktime_get();
7095
7096         /*
7097          * Don't enter VMX if guest state is invalid, let the exit handler
7098          * start emulation until we arrive back to a valid state.  Synthesize a
7099          * consistency check VM-Exit due to invalid guest state and bail.
7100          */
7101         if (unlikely(vmx->emulation_required)) {
7102                 vmx->fail = 0;
7103
7104                 vmx->exit_reason.full = EXIT_REASON_INVALID_STATE;
7105                 vmx->exit_reason.failed_vmentry = 1;
7106                 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1);
7107                 vmx->exit_qualification = ENTRY_FAIL_DEFAULT;
7108                 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2);
7109                 vmx->exit_intr_info = 0;
7110                 return EXIT_FASTPATH_NONE;
7111         }
7112
7113         trace_kvm_entry(vcpu);
7114
7115         if (vmx->ple_window_dirty) {
7116                 vmx->ple_window_dirty = false;
7117                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
7118         }
7119
7120         /*
7121          * We did this in prepare_switch_to_guest, because it needs to
7122          * be within srcu_read_lock.
7123          */
7124         WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
7125
7126         if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
7127                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
7128         if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
7129                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
7130         vcpu->arch.regs_dirty = 0;
7131
7132         /*
7133          * Refresh vmcs.HOST_CR3 if necessary.  This must be done immediately
7134          * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time
7135          * it switches back to the current->mm, which can occur in KVM context
7136          * when switching to a temporary mm to patch kernel code, e.g. if KVM
7137          * toggles a static key while handling a VM-Exit.
7138          */
7139         cr3 = __get_current_cr3_fast();
7140         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
7141                 vmcs_writel(HOST_CR3, cr3);
7142                 vmx->loaded_vmcs->host_state.cr3 = cr3;
7143         }
7144
7145         cr4 = cr4_read_shadow();
7146         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
7147                 vmcs_writel(HOST_CR4, cr4);
7148                 vmx->loaded_vmcs->host_state.cr4 = cr4;
7149         }
7150
7151         /* When KVM_DEBUGREG_WONT_EXIT, dr6 is accessible in guest. */
7152         if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
7153                 set_debugreg(vcpu->arch.dr6, 6);
7154
7155         /* When single-stepping over STI and MOV SS, we must clear the
7156          * corresponding interruptibility bits in the guest state. Otherwise
7157          * vmentry fails as it then expects bit 14 (BS) in pending debug
7158          * exceptions being set, but that's not correct for the guest debugging
7159          * case. */
7160         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
7161                 vmx_set_interrupt_shadow(vcpu, 0);
7162
7163         kvm_load_guest_xsave_state(vcpu);
7164
7165         pt_guest_enter(vmx);
7166
7167         atomic_switch_perf_msrs(vmx);
7168         if (intel_pmu_lbr_is_enabled(vcpu))
7169                 vmx_passthrough_lbr_msrs(vcpu);
7170
7171         if (enable_preemption_timer)
7172                 vmx_update_hv_timer(vcpu);
7173
7174         kvm_wait_lapic_expire(vcpu);
7175
7176         /* The actual VMENTER/EXIT is in the .noinstr.text section. */
7177         vmx_vcpu_enter_exit(vcpu, vmx, __vmx_vcpu_run_flags(vmx));
7178
7179         /* All fields are clean at this point */
7180         if (static_branch_unlikely(&enable_evmcs)) {
7181                 current_evmcs->hv_clean_fields |=
7182                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
7183
7184                 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu);
7185         }
7186
7187         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
7188         if (vmx->host_debugctlmsr)
7189                 update_debugctlmsr(vmx->host_debugctlmsr);
7190
7191 #ifndef CONFIG_X86_64
7192         /*
7193          * The sysexit path does not restore ds/es, so we must set them to
7194          * a reasonable value ourselves.
7195          *
7196          * We can't defer this to vmx_prepare_switch_to_host() since that
7197          * function may be executed in interrupt context, which saves and
7198          * restore segments around it, nullifying its effect.
7199          */
7200         loadsegment(ds, __USER_DS);
7201         loadsegment(es, __USER_DS);
7202 #endif
7203
7204         vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET;
7205
7206         pt_guest_exit(vmx);
7207
7208         kvm_load_host_xsave_state(vcpu);
7209
7210         if (is_guest_mode(vcpu)) {
7211                 /*
7212                  * Track VMLAUNCH/VMRESUME that have made past guest state
7213                  * checking.
7214                  */
7215                 if (vmx->nested.nested_run_pending &&
7216                     !vmx->exit_reason.failed_vmentry)
7217                         ++vcpu->stat.nested_run;
7218
7219                 vmx->nested.nested_run_pending = 0;
7220         }
7221
7222         vmx->idt_vectoring_info = 0;
7223
7224         if (unlikely(vmx->fail)) {
7225                 vmx->exit_reason.full = 0xdead;
7226                 return EXIT_FASTPATH_NONE;
7227         }
7228
7229         vmx->exit_reason.full = vmcs_read32(VM_EXIT_REASON);
7230         if (unlikely((u16)vmx->exit_reason.basic == EXIT_REASON_MCE_DURING_VMENTRY))
7231                 kvm_machine_check();
7232
7233         if (likely(!vmx->exit_reason.failed_vmentry))
7234                 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
7235
7236         trace_kvm_exit(vcpu, KVM_ISA_VMX);
7237
7238         if (unlikely(vmx->exit_reason.failed_vmentry))
7239                 return EXIT_FASTPATH_NONE;
7240
7241         vmx->loaded_vmcs->launched = 1;
7242
7243         vmx_recover_nmi_blocking(vmx);
7244         vmx_complete_interrupts(vmx);
7245
7246         if (is_guest_mode(vcpu))
7247                 return EXIT_FASTPATH_NONE;
7248
7249         return vmx_exit_handlers_fastpath(vcpu);
7250 }
7251
7252 static void vmx_vcpu_free(struct kvm_vcpu *vcpu)
7253 {
7254         struct vcpu_vmx *vmx = to_vmx(vcpu);
7255
7256         if (enable_pml)
7257                 vmx_destroy_pml_buffer(vmx);
7258         free_vpid(vmx->vpid);
7259         nested_vmx_free_vcpu(vcpu);
7260         free_loaded_vmcs(vmx->loaded_vmcs);
7261 }
7262
7263 static int vmx_vcpu_create(struct kvm_vcpu *vcpu)
7264 {
7265         struct vmx_uret_msr *tsx_ctrl;
7266         struct vcpu_vmx *vmx;
7267         int i, err;
7268
7269         BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
7270         vmx = to_vmx(vcpu);
7271
7272         INIT_LIST_HEAD(&vmx->pi_wakeup_list);
7273
7274         err = -ENOMEM;
7275
7276         vmx->vpid = allocate_vpid();
7277
7278         /*
7279          * If PML is turned on, failure on enabling PML just results in failure
7280          * of creating the vcpu, therefore we can simplify PML logic (by
7281          * avoiding dealing with cases, such as enabling PML partially on vcpus
7282          * for the guest), etc.
7283          */
7284         if (enable_pml) {
7285                 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
7286                 if (!vmx->pml_pg)
7287                         goto free_vpid;
7288         }
7289
7290         for (i = 0; i < kvm_nr_uret_msrs; ++i)
7291                 vmx->guest_uret_msrs[i].mask = -1ull;
7292         if (boot_cpu_has(X86_FEATURE_RTM)) {
7293                 /*
7294                  * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception.
7295                  * Keep the host value unchanged to avoid changing CPUID bits
7296                  * under the host kernel's feet.
7297                  */
7298                 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7299                 if (tsx_ctrl)
7300                         tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
7301         }
7302
7303         err = alloc_loaded_vmcs(&vmx->vmcs01);
7304         if (err < 0)
7305                 goto free_pml;
7306
7307         /*
7308          * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a
7309          * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the
7310          * feature only for vmcs01, KVM currently isn't equipped to realize any
7311          * performance benefits from enabling it for vmcs02.
7312          */
7313         if (IS_ENABLED(CONFIG_HYPERV) && static_branch_unlikely(&enable_evmcs) &&
7314             (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
7315                 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs;
7316
7317                 evmcs->hv_enlightenments_control.msr_bitmap = 1;
7318         }
7319
7320         /* The MSR bitmap starts with all ones */
7321         bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7322         bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
7323
7324         vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
7325 #ifdef CONFIG_X86_64
7326         vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
7327         vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW);
7328         vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
7329 #endif
7330         vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
7331         vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
7332         vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
7333         if (kvm_cstate_in_guest(vcpu->kvm)) {
7334                 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R);
7335                 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
7336                 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
7337                 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7338         }
7339
7340         vmx->loaded_vmcs = &vmx->vmcs01;
7341
7342         if (cpu_need_virtualize_apic_accesses(vcpu)) {
7343                 err = alloc_apic_access_page(vcpu->kvm);
7344                 if (err)
7345                         goto free_vmcs;
7346         }
7347
7348         if (enable_ept && !enable_unrestricted_guest) {
7349                 err = init_rmode_identity_map(vcpu->kvm);
7350                 if (err)
7351                         goto free_vmcs;
7352         }
7353
7354         if (vmx_can_use_ipiv(vcpu))
7355                 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id],
7356                            __pa(&vmx->pi_desc) | PID_TABLE_ENTRY_VALID);
7357
7358         return 0;
7359
7360 free_vmcs:
7361         free_loaded_vmcs(vmx->loaded_vmcs);
7362 free_pml:
7363         vmx_destroy_pml_buffer(vmx);
7364 free_vpid:
7365         free_vpid(vmx->vpid);
7366         return err;
7367 }
7368
7369 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
7370 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
7371
7372 static int vmx_vm_init(struct kvm *kvm)
7373 {
7374         if (!ple_gap)
7375                 kvm->arch.pause_in_guest = true;
7376
7377         if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7378                 switch (l1tf_mitigation) {
7379                 case L1TF_MITIGATION_OFF:
7380                 case L1TF_MITIGATION_FLUSH_NOWARN:
7381                         /* 'I explicitly don't care' is set */
7382                         break;
7383                 case L1TF_MITIGATION_FLUSH:
7384                 case L1TF_MITIGATION_FLUSH_NOSMT:
7385                 case L1TF_MITIGATION_FULL:
7386                         /*
7387                          * Warn upon starting the first VM in a potentially
7388                          * insecure environment.
7389                          */
7390                         if (sched_smt_active())
7391                                 pr_warn_once(L1TF_MSG_SMT);
7392                         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7393                                 pr_warn_once(L1TF_MSG_L1D);
7394                         break;
7395                 case L1TF_MITIGATION_FULL_FORCE:
7396                         /* Flush is enforced */
7397                         break;
7398                 }
7399         }
7400         return 0;
7401 }
7402
7403 static int __init vmx_check_processor_compat(void)
7404 {
7405         struct vmcs_config vmcs_conf;
7406         struct vmx_capability vmx_cap;
7407
7408         if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7409             !this_cpu_has(X86_FEATURE_VMX)) {
7410                 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7411                 return -EIO;
7412         }
7413
7414         if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7415                 return -EIO;
7416         if (nested)
7417                 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept);
7418         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7419                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7420                                 smp_processor_id());
7421                 return -EIO;
7422         }
7423         return 0;
7424 }
7425
7426 static u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7427 {
7428         u8 cache;
7429
7430         /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7431          * memory aliases with conflicting memory types and sometimes MCEs.
7432          * We have to be careful as to what are honored and when.
7433          *
7434          * For MMIO, guest CD/MTRR are ignored.  The EPT memory type is set to
7435          * UC.  The effective memory type is UC or WC depending on guest PAT.
7436          * This was historically the source of MCEs and we want to be
7437          * conservative.
7438          *
7439          * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7440          * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored.  The
7441          * EPT memory type is set to WB.  The effective memory type is forced
7442          * WB.
7443          *
7444          * Otherwise, we trust guest.  Guest CD/MTRR/PAT are all honored.  The
7445          * EPT memory type is used to emulate guest CD/MTRR.
7446          */
7447
7448         if (is_mmio)
7449                 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT;
7450
7451         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm))
7452                 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7453
7454         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7455                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7456                         cache = MTRR_TYPE_WRBACK;
7457                 else
7458                         cache = MTRR_TYPE_UNCACHABLE;
7459
7460                 return (cache << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT;
7461         }
7462
7463         return kvm_mtrr_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT;
7464 }
7465
7466 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl)
7467 {
7468         /*
7469          * These bits in the secondary execution controls field
7470          * are dynamic, the others are mostly based on the hypervisor
7471          * architecture and the guest's CPUID.  Do not touch the
7472          * dynamic bits.
7473          */
7474         u32 mask =
7475                 SECONDARY_EXEC_SHADOW_VMCS |
7476                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7477                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7478                 SECONDARY_EXEC_DESC;
7479
7480         u32 cur_ctl = secondary_exec_controls_get(vmx);
7481
7482         secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7483 }
7484
7485 /*
7486  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7487  * (indicating "allowed-1") if they are supported in the guest's CPUID.
7488  */
7489 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7490 {
7491         struct vcpu_vmx *vmx = to_vmx(vcpu);
7492         struct kvm_cpuid_entry2 *entry;
7493
7494         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7495         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7496
7497 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
7498         if (entry && (entry->_reg & (_cpuid_mask)))                     \
7499                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
7500 } while (0)
7501
7502         entry = kvm_find_cpuid_entry(vcpu, 0x1);
7503         cr4_fixed1_update(X86_CR4_VME,        edx, feature_bit(VME));
7504         cr4_fixed1_update(X86_CR4_PVI,        edx, feature_bit(VME));
7505         cr4_fixed1_update(X86_CR4_TSD,        edx, feature_bit(TSC));
7506         cr4_fixed1_update(X86_CR4_DE,         edx, feature_bit(DE));
7507         cr4_fixed1_update(X86_CR4_PSE,        edx, feature_bit(PSE));
7508         cr4_fixed1_update(X86_CR4_PAE,        edx, feature_bit(PAE));
7509         cr4_fixed1_update(X86_CR4_MCE,        edx, feature_bit(MCE));
7510         cr4_fixed1_update(X86_CR4_PGE,        edx, feature_bit(PGE));
7511         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, feature_bit(FXSR));
7512         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7513         cr4_fixed1_update(X86_CR4_VMXE,       ecx, feature_bit(VMX));
7514         cr4_fixed1_update(X86_CR4_SMXE,       ecx, feature_bit(SMX));
7515         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, feature_bit(PCID));
7516         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, feature_bit(XSAVE));
7517
7518         entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0);
7519         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, feature_bit(FSGSBASE));
7520         cr4_fixed1_update(X86_CR4_SMEP,       ebx, feature_bit(SMEP));
7521         cr4_fixed1_update(X86_CR4_SMAP,       ebx, feature_bit(SMAP));
7522         cr4_fixed1_update(X86_CR4_PKE,        ecx, feature_bit(PKU));
7523         cr4_fixed1_update(X86_CR4_UMIP,       ecx, feature_bit(UMIP));
7524         cr4_fixed1_update(X86_CR4_LA57,       ecx, feature_bit(LA57));
7525
7526 #undef cr4_fixed1_update
7527 }
7528
7529 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7530 {
7531         struct vcpu_vmx *vmx = to_vmx(vcpu);
7532         struct kvm_cpuid_entry2 *best = NULL;
7533         int i;
7534
7535         for (i = 0; i < PT_CPUID_LEAVES; i++) {
7536                 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i);
7537                 if (!best)
7538                         return;
7539                 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7540                 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7541                 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7542                 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7543         }
7544
7545         /* Get the number of configurable Address Ranges for filtering */
7546         vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps,
7547                                                 PT_CAP_num_address_ranges);
7548
7549         /* Initialize and clear the no dependency bits */
7550         vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7551                         RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC |
7552                         RTIT_CTL_BRANCH_EN);
7553
7554         /*
7555          * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7556          * will inject an #GP
7557          */
7558         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7559                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7560
7561         /*
7562          * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7563          * PSBFreq can be set
7564          */
7565         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7566                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7567                                 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7568
7569         /*
7570          * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set
7571          */
7572         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7573                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7574                                               RTIT_CTL_MTC_RANGE);
7575
7576         /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7577         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7578                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7579                                                         RTIT_CTL_PTW_EN);
7580
7581         /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7582         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7583                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7584
7585         /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7586         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7587                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7588
7589         /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */
7590         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7591                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7592
7593         /* unmask address range configure area */
7594         for (i = 0; i < vmx->pt_desc.num_address_ranges; i++)
7595                 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7596 }
7597
7598 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7599 {
7600         struct vcpu_vmx *vmx = to_vmx(vcpu);
7601
7602         /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7603         vcpu->arch.xsaves_enabled = false;
7604
7605         vmx_setup_uret_msrs(vmx);
7606
7607         if (cpu_has_secondary_exec_ctrls())
7608                 vmcs_set_secondary_exec_control(vmx,
7609                                                 vmx_secondary_exec_control(vmx));
7610
7611         if (nested_vmx_allowed(vcpu))
7612                 vmx->msr_ia32_feature_control_valid_bits |=
7613                         FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7614                         FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7615         else
7616                 vmx->msr_ia32_feature_control_valid_bits &=
7617                         ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7618                           FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7619
7620         if (nested_vmx_allowed(vcpu))
7621                 nested_vmx_cr_fixed1_bits_update(vcpu);
7622
7623         if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7624                         guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7625                 update_intel_pt_cfg(vcpu);
7626
7627         if (boot_cpu_has(X86_FEATURE_RTM)) {
7628                 struct vmx_uret_msr *msr;
7629                 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL);
7630                 if (msr) {
7631                         bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7632                         vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7633                 }
7634         }
7635
7636         if (kvm_cpu_cap_has(X86_FEATURE_XFD))
7637                 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R,
7638                                           !guest_cpuid_has(vcpu, X86_FEATURE_XFD));
7639
7640
7641         set_cr4_guest_host_mask(vmx);
7642
7643         vmx_write_encls_bitmap(vcpu, NULL);
7644         if (guest_cpuid_has(vcpu, X86_FEATURE_SGX))
7645                 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED;
7646         else
7647                 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED;
7648
7649         if (guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
7650                 vmx->msr_ia32_feature_control_valid_bits |=
7651                         FEAT_CTL_SGX_LC_ENABLED;
7652         else
7653                 vmx->msr_ia32_feature_control_valid_bits &=
7654                         ~FEAT_CTL_SGX_LC_ENABLED;
7655
7656         /* Refresh #PF interception to account for MAXPHYADDR changes. */
7657         vmx_update_exception_bitmap(vcpu);
7658 }
7659
7660 static __init void vmx_set_cpu_caps(void)
7661 {
7662         kvm_set_cpu_caps();
7663
7664         /* CPUID 0x1 */
7665         if (nested)
7666                 kvm_cpu_cap_set(X86_FEATURE_VMX);
7667
7668         /* CPUID 0x7 */
7669         if (kvm_mpx_supported())
7670                 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7671         if (!cpu_has_vmx_invpcid())
7672                 kvm_cpu_cap_clear(X86_FEATURE_INVPCID);
7673         if (vmx_pt_mode_is_host_guest())
7674                 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7675         if (vmx_pebs_supported()) {
7676                 kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
7677                 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
7678         }
7679
7680         if (!enable_pmu)
7681                 kvm_cpu_cap_clear(X86_FEATURE_PDCM);
7682
7683         if (!enable_sgx) {
7684                 kvm_cpu_cap_clear(X86_FEATURE_SGX);
7685                 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC);
7686                 kvm_cpu_cap_clear(X86_FEATURE_SGX1);
7687                 kvm_cpu_cap_clear(X86_FEATURE_SGX2);
7688         }
7689
7690         if (vmx_umip_emulated())
7691                 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7692
7693         /* CPUID 0xD.1 */
7694         kvm_caps.supported_xss = 0;
7695         if (!cpu_has_vmx_xsaves())
7696                 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7697
7698         /* CPUID 0x80000001 and 0x7 (RDPID) */
7699         if (!cpu_has_vmx_rdtscp()) {
7700                 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7701                 kvm_cpu_cap_clear(X86_FEATURE_RDPID);
7702         }
7703
7704         if (cpu_has_vmx_waitpkg())
7705                 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7706 }
7707
7708 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7709 {
7710         to_vmx(vcpu)->req_immediate_exit = true;
7711 }
7712
7713 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7714                                   struct x86_instruction_info *info)
7715 {
7716         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7717         unsigned short port;
7718         bool intercept;
7719         int size;
7720
7721         if (info->intercept == x86_intercept_in ||
7722             info->intercept == x86_intercept_ins) {
7723                 port = info->src_val;
7724                 size = info->dst_bytes;
7725         } else {
7726                 port = info->dst_val;
7727                 size = info->src_bytes;
7728         }
7729
7730         /*
7731          * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7732          * VM-exits depend on the 'unconditional IO exiting' VM-execution
7733          * control.
7734          *
7735          * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7736          */
7737         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7738                 intercept = nested_cpu_has(vmcs12,
7739                                            CPU_BASED_UNCOND_IO_EXITING);
7740         else
7741                 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7742
7743         /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED.  */
7744         return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7745 }
7746
7747 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7748                                struct x86_instruction_info *info,
7749                                enum x86_intercept_stage stage,
7750                                struct x86_exception *exception)
7751 {
7752         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7753
7754         switch (info->intercept) {
7755         /*
7756          * RDPID causes #UD if disabled through secondary execution controls.
7757          * Because it is marked as EmulateOnUD, we need to intercept it here.
7758          * Note, RDPID is hidden behind ENABLE_RDTSCP.
7759          */
7760         case x86_intercept_rdpid:
7761                 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) {
7762                         exception->vector = UD_VECTOR;
7763                         exception->error_code_valid = false;
7764                         return X86EMUL_PROPAGATE_FAULT;
7765                 }
7766                 break;
7767
7768         case x86_intercept_in:
7769         case x86_intercept_ins:
7770         case x86_intercept_out:
7771         case x86_intercept_outs:
7772                 return vmx_check_intercept_io(vcpu, info);
7773
7774         case x86_intercept_lgdt:
7775         case x86_intercept_lidt:
7776         case x86_intercept_lldt:
7777         case x86_intercept_ltr:
7778         case x86_intercept_sgdt:
7779         case x86_intercept_sidt:
7780         case x86_intercept_sldt:
7781         case x86_intercept_str:
7782                 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7783                         return X86EMUL_CONTINUE;
7784
7785                 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED.  */
7786                 break;
7787
7788         /* TODO: check more intercepts... */
7789         default:
7790                 break;
7791         }
7792
7793         return X86EMUL_UNHANDLEABLE;
7794 }
7795
7796 #ifdef CONFIG_X86_64
7797 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7798 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7799                                   u64 divisor, u64 *result)
7800 {
7801         u64 low = a << shift, high = a >> (64 - shift);
7802
7803         /* To avoid the overflow on divq */
7804         if (high >= divisor)
7805                 return 1;
7806
7807         /* Low hold the result, high hold rem which is discarded */
7808         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7809             "rm" (divisor), "0" (low), "1" (high));
7810         *result = low;
7811
7812         return 0;
7813 }
7814
7815 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7816                             bool *expired)
7817 {
7818         struct vcpu_vmx *vmx;
7819         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7820         struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7821
7822         vmx = to_vmx(vcpu);
7823         tscl = rdtsc();
7824         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7825         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7826         lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7827                                                     ktimer->timer_advance_ns);
7828
7829         if (delta_tsc > lapic_timer_advance_cycles)
7830                 delta_tsc -= lapic_timer_advance_cycles;
7831         else
7832                 delta_tsc = 0;
7833
7834         /* Convert to host delta tsc if tsc scaling is enabled */
7835         if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio &&
7836             delta_tsc && u64_shl_div_u64(delta_tsc,
7837                                 kvm_caps.tsc_scaling_ratio_frac_bits,
7838                                 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc))
7839                 return -ERANGE;
7840
7841         /*
7842          * If the delta tsc can't fit in the 32 bit after the multi shift,
7843          * we can't use the preemption timer.
7844          * It's possible that it fits on later vmentries, but checking
7845          * on every vmentry is costly so we just use an hrtimer.
7846          */
7847         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7848                 return -ERANGE;
7849
7850         vmx->hv_deadline_tsc = tscl + delta_tsc;
7851         *expired = !delta_tsc;
7852         return 0;
7853 }
7854
7855 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7856 {
7857         to_vmx(vcpu)->hv_deadline_tsc = -1;
7858 }
7859 #endif
7860
7861 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7862 {
7863         if (!kvm_pause_in_guest(vcpu->kvm))
7864                 shrink_ple_window(vcpu);
7865 }
7866
7867 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu)
7868 {
7869         struct vcpu_vmx *vmx = to_vmx(vcpu);
7870
7871         if (is_guest_mode(vcpu)) {
7872                 vmx->nested.update_vmcs01_cpu_dirty_logging = true;
7873                 return;
7874         }
7875
7876         /*
7877          * Note, cpu_dirty_logging_count can be changed concurrent with this
7878          * code, but in that case another update request will be made and so
7879          * the guest will never run with a stale PML value.
7880          */
7881         if (vcpu->kvm->arch.cpu_dirty_logging_count)
7882                 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7883         else
7884                 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML);
7885 }
7886
7887 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7888 {
7889         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7890                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7891                         FEAT_CTL_LMCE_ENABLED;
7892         else
7893                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7894                         ~FEAT_CTL_LMCE_ENABLED;
7895 }
7896
7897 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7898 {
7899         /* we need a nested vmexit to enter SMM, postpone if run is pending */
7900         if (to_vmx(vcpu)->nested.nested_run_pending)
7901                 return -EBUSY;
7902         return !is_smm(vcpu);
7903 }
7904
7905 static int vmx_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7906 {
7907         struct vcpu_vmx *vmx = to_vmx(vcpu);
7908
7909         /*
7910          * TODO: Implement custom flows for forcing the vCPU out/in of L2 on
7911          * SMI and RSM.  Using the common VM-Exit + VM-Enter routines is wrong
7912          * SMI and RSM only modify state that is saved and restored via SMRAM.
7913          * E.g. most MSRs are left untouched, but many are modified by VM-Exit
7914          * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM.
7915          */
7916         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7917         if (vmx->nested.smm.guest_mode)
7918                 nested_vmx_vmexit(vcpu, -1, 0, 0);
7919
7920         vmx->nested.smm.vmxon = vmx->nested.vmxon;
7921         vmx->nested.vmxon = false;
7922         vmx_clear_hlt(vcpu);
7923         return 0;
7924 }
7925
7926 static int vmx_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7927 {
7928         struct vcpu_vmx *vmx = to_vmx(vcpu);
7929         int ret;
7930
7931         if (vmx->nested.smm.vmxon) {
7932                 vmx->nested.vmxon = true;
7933                 vmx->nested.smm.vmxon = false;
7934         }
7935
7936         if (vmx->nested.smm.guest_mode) {
7937                 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7938                 if (ret)
7939                         return ret;
7940
7941                 vmx->nested.nested_run_pending = 1;
7942                 vmx->nested.smm.guest_mode = false;
7943         }
7944         return 0;
7945 }
7946
7947 static void vmx_enable_smi_window(struct kvm_vcpu *vcpu)
7948 {
7949         /* RSM will cause a vmexit anyway.  */
7950 }
7951
7952 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7953 {
7954         return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu);
7955 }
7956
7957 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7958 {
7959         if (is_guest_mode(vcpu)) {
7960                 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7961
7962                 if (hrtimer_try_to_cancel(timer) == 1)
7963                         hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7964         }
7965 }
7966
7967 static void vmx_hardware_unsetup(void)
7968 {
7969         kvm_set_posted_intr_wakeup_handler(NULL);
7970
7971         if (nested)
7972                 nested_vmx_hardware_unsetup();
7973
7974         free_kvm_area();
7975 }
7976
7977 static bool vmx_check_apicv_inhibit_reasons(enum kvm_apicv_inhibit reason)
7978 {
7979         ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7980                           BIT(APICV_INHIBIT_REASON_ABSENT) |
7981                           BIT(APICV_INHIBIT_REASON_HYPERV) |
7982                           BIT(APICV_INHIBIT_REASON_BLOCKIRQ) |
7983                           BIT(APICV_INHIBIT_REASON_APIC_ID_MODIFIED) |
7984                           BIT(APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
7985
7986         return supported & BIT(reason);
7987 }
7988
7989 static void vmx_vm_destroy(struct kvm *kvm)
7990 {
7991         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
7992
7993         free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm));
7994 }
7995
7996 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7997         .name = "kvm_intel",
7998
7999         .hardware_unsetup = vmx_hardware_unsetup,
8000
8001         .hardware_enable = vmx_hardware_enable,
8002         .hardware_disable = vmx_hardware_disable,
8003         .has_emulated_msr = vmx_has_emulated_msr,
8004
8005         .vm_size = sizeof(struct kvm_vmx),
8006         .vm_init = vmx_vm_init,
8007         .vm_destroy = vmx_vm_destroy,
8008
8009         .vcpu_precreate = vmx_vcpu_precreate,
8010         .vcpu_create = vmx_vcpu_create,
8011         .vcpu_free = vmx_vcpu_free,
8012         .vcpu_reset = vmx_vcpu_reset,
8013
8014         .prepare_switch_to_guest = vmx_prepare_switch_to_guest,
8015         .vcpu_load = vmx_vcpu_load,
8016         .vcpu_put = vmx_vcpu_put,
8017
8018         .update_exception_bitmap = vmx_update_exception_bitmap,
8019         .get_msr_feature = vmx_get_msr_feature,
8020         .get_msr = vmx_get_msr,
8021         .set_msr = vmx_set_msr,
8022         .get_segment_base = vmx_get_segment_base,
8023         .get_segment = vmx_get_segment,
8024         .set_segment = vmx_set_segment,
8025         .get_cpl = vmx_get_cpl,
8026         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
8027         .set_cr0 = vmx_set_cr0,
8028         .is_valid_cr4 = vmx_is_valid_cr4,
8029         .set_cr4 = vmx_set_cr4,
8030         .set_efer = vmx_set_efer,
8031         .get_idt = vmx_get_idt,
8032         .set_idt = vmx_set_idt,
8033         .get_gdt = vmx_get_gdt,
8034         .set_gdt = vmx_set_gdt,
8035         .set_dr7 = vmx_set_dr7,
8036         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
8037         .cache_reg = vmx_cache_reg,
8038         .get_rflags = vmx_get_rflags,
8039         .set_rflags = vmx_set_rflags,
8040         .get_if_flag = vmx_get_if_flag,
8041
8042         .flush_tlb_all = vmx_flush_tlb_all,
8043         .flush_tlb_current = vmx_flush_tlb_current,
8044         .flush_tlb_gva = vmx_flush_tlb_gva,
8045         .flush_tlb_guest = vmx_flush_tlb_guest,
8046
8047         .vcpu_pre_run = vmx_vcpu_pre_run,
8048         .vcpu_run = vmx_vcpu_run,
8049         .handle_exit = vmx_handle_exit,
8050         .skip_emulated_instruction = vmx_skip_emulated_instruction,
8051         .update_emulated_instruction = vmx_update_emulated_instruction,
8052         .set_interrupt_shadow = vmx_set_interrupt_shadow,
8053         .get_interrupt_shadow = vmx_get_interrupt_shadow,
8054         .patch_hypercall = vmx_patch_hypercall,
8055         .inject_irq = vmx_inject_irq,
8056         .inject_nmi = vmx_inject_nmi,
8057         .queue_exception = vmx_queue_exception,
8058         .cancel_injection = vmx_cancel_injection,
8059         .interrupt_allowed = vmx_interrupt_allowed,
8060         .nmi_allowed = vmx_nmi_allowed,
8061         .get_nmi_mask = vmx_get_nmi_mask,
8062         .set_nmi_mask = vmx_set_nmi_mask,
8063         .enable_nmi_window = vmx_enable_nmi_window,
8064         .enable_irq_window = vmx_enable_irq_window,
8065         .update_cr8_intercept = vmx_update_cr8_intercept,
8066         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
8067         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
8068         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
8069         .load_eoi_exitmap = vmx_load_eoi_exitmap,
8070         .apicv_post_state_restore = vmx_apicv_post_state_restore,
8071         .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
8072         .hwapic_irr_update = vmx_hwapic_irr_update,
8073         .hwapic_isr_update = vmx_hwapic_isr_update,
8074         .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
8075         .sync_pir_to_irr = vmx_sync_pir_to_irr,
8076         .deliver_interrupt = vmx_deliver_interrupt,
8077         .dy_apicv_has_pending_interrupt = pi_has_pending_interrupt,
8078
8079         .set_tss_addr = vmx_set_tss_addr,
8080         .set_identity_map_addr = vmx_set_identity_map_addr,
8081         .get_mt_mask = vmx_get_mt_mask,
8082
8083         .get_exit_info = vmx_get_exit_info,
8084
8085         .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
8086
8087         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
8088
8089         .get_l2_tsc_offset = vmx_get_l2_tsc_offset,
8090         .get_l2_tsc_multiplier = vmx_get_l2_tsc_multiplier,
8091         .write_tsc_offset = vmx_write_tsc_offset,
8092         .write_tsc_multiplier = vmx_write_tsc_multiplier,
8093
8094         .load_mmu_pgd = vmx_load_mmu_pgd,
8095
8096         .check_intercept = vmx_check_intercept,
8097         .handle_exit_irqoff = vmx_handle_exit_irqoff,
8098
8099         .request_immediate_exit = vmx_request_immediate_exit,
8100
8101         .sched_in = vmx_sched_in,
8102
8103         .cpu_dirty_log_size = PML_ENTITY_NUM,
8104         .update_cpu_dirty_logging = vmx_update_cpu_dirty_logging,
8105
8106         .nested_ops = &vmx_nested_ops,
8107
8108         .pi_update_irte = vmx_pi_update_irte,
8109         .pi_start_assignment = vmx_pi_start_assignment,
8110
8111 #ifdef CONFIG_X86_64
8112         .set_hv_timer = vmx_set_hv_timer,
8113         .cancel_hv_timer = vmx_cancel_hv_timer,
8114 #endif
8115
8116         .setup_mce = vmx_setup_mce,
8117
8118         .smi_allowed = vmx_smi_allowed,
8119         .enter_smm = vmx_enter_smm,
8120         .leave_smm = vmx_leave_smm,
8121         .enable_smi_window = vmx_enable_smi_window,
8122
8123         .can_emulate_instruction = vmx_can_emulate_instruction,
8124         .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8125         .migrate_timers = vmx_migrate_timers,
8126
8127         .msr_filter_changed = vmx_msr_filter_changed,
8128         .complete_emulated_msr = kvm_complete_insn_gp,
8129
8130         .vcpu_deliver_sipi_vector = kvm_vcpu_deliver_sipi_vector,
8131 };
8132
8133 static unsigned int vmx_handle_intel_pt_intr(void)
8134 {
8135         struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
8136
8137         /* '0' on failure so that the !PT case can use a RET0 static call. */
8138         if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
8139                 return 0;
8140
8141         kvm_make_request(KVM_REQ_PMI, vcpu);
8142         __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
8143                   (unsigned long *)&vcpu->arch.pmu.global_status);
8144         return 1;
8145 }
8146
8147 static __init void vmx_setup_user_return_msrs(void)
8148 {
8149
8150         /*
8151          * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
8152          * will emulate SYSCALL in legacy mode if the vendor string in guest
8153          * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
8154          * support this emulation, MSR_STAR is included in the list for i386,
8155          * but is never loaded into hardware.  MSR_CSTAR is also never loaded
8156          * into hardware and is here purely for emulation purposes.
8157          */
8158         const u32 vmx_uret_msrs_list[] = {
8159         #ifdef CONFIG_X86_64
8160                 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
8161         #endif
8162                 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
8163                 MSR_IA32_TSX_CTRL,
8164         };
8165         int i;
8166
8167         BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS);
8168
8169         for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i)
8170                 kvm_add_user_return_msr(vmx_uret_msrs_list[i]);
8171 }
8172
8173 static void __init vmx_setup_me_spte_mask(void)
8174 {
8175         u64 me_mask = 0;
8176
8177         /*
8178          * kvm_get_shadow_phys_bits() returns shadow_phys_bits.  Use
8179          * the former to avoid exposing shadow_phys_bits.
8180          *
8181          * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to
8182          * shadow_phys_bits.  On MKTME and/or TDX capable systems,
8183          * boot_cpu_data.x86_phys_bits holds the actual physical address
8184          * w/o the KeyID bits, and shadow_phys_bits equals to MAXPHYADDR
8185          * reported by CPUID.  Those bits between are KeyID bits.
8186          */
8187         if (boot_cpu_data.x86_phys_bits != kvm_get_shadow_phys_bits())
8188                 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits,
8189                         kvm_get_shadow_phys_bits() - 1);
8190         /*
8191          * Unlike SME, host kernel doesn't support setting up any
8192          * MKTME KeyID on Intel platforms.  No memory encryption
8193          * bits should be included into the SPTE.
8194          */
8195         kvm_mmu_set_me_spte_mask(0, me_mask);
8196 }
8197
8198 static struct kvm_x86_init_ops vmx_init_ops __initdata;
8199
8200 static __init int hardware_setup(void)
8201 {
8202         unsigned long host_bndcfgs;
8203         struct desc_ptr dt;
8204         int r;
8205
8206         store_idt(&dt);
8207         host_idt_base = dt.address;
8208
8209         vmx_setup_user_return_msrs();
8210
8211         if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8212                 return -EIO;
8213
8214         if (cpu_has_perf_global_ctrl_bug())
8215                 pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
8216                              "does not work properly. Using workaround\n");
8217
8218         if (boot_cpu_has(X86_FEATURE_NX))
8219                 kvm_enable_efer_bits(EFER_NX);
8220
8221         if (boot_cpu_has(X86_FEATURE_MPX)) {
8222                 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8223                 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
8224         }
8225
8226         if (!cpu_has_vmx_mpx())
8227                 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8228                                              XFEATURE_MASK_BNDCSR);
8229
8230         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8231             !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8232                 enable_vpid = 0;
8233
8234         if (!cpu_has_vmx_ept() ||
8235             !cpu_has_vmx_ept_4levels() ||
8236             !cpu_has_vmx_ept_mt_wb() ||
8237             !cpu_has_vmx_invept_global())
8238                 enable_ept = 0;
8239
8240         /* NX support is required for shadow paging. */
8241         if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) {
8242                 pr_err_ratelimited("kvm: NX (Execute Disable) not supported\n");
8243                 return -EOPNOTSUPP;
8244         }
8245
8246         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8247                 enable_ept_ad_bits = 0;
8248
8249         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8250                 enable_unrestricted_guest = 0;
8251
8252         if (!cpu_has_vmx_flexpriority())
8253                 flexpriority_enabled = 0;
8254
8255         if (!cpu_has_virtual_nmis())
8256                 enable_vnmi = 0;
8257
8258         /*
8259          * set_apic_access_page_addr() is used to reload apic access
8260          * page upon invalidation.  No need to do anything if not
8261          * using the APIC_ACCESS_ADDR VMCS field.
8262          */
8263         if (!flexpriority_enabled)
8264                 vmx_x86_ops.set_apic_access_page_addr = NULL;
8265
8266         if (!cpu_has_vmx_tpr_shadow())
8267                 vmx_x86_ops.update_cr8_intercept = NULL;
8268
8269 #if IS_ENABLED(CONFIG_HYPERV)
8270         if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8271             && enable_ept) {
8272                 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8273                 vmx_x86_ops.tlb_remote_flush_with_range =
8274                                 hv_remote_flush_tlb_with_range;
8275         }
8276 #endif
8277
8278         if (!cpu_has_vmx_ple()) {
8279                 ple_gap = 0;
8280                 ple_window = 0;
8281                 ple_window_grow = 0;
8282                 ple_window_max = 0;
8283                 ple_window_shrink = 0;
8284         }
8285
8286         if (!cpu_has_vmx_apicv())
8287                 enable_apicv = 0;
8288         if (!enable_apicv)
8289                 vmx_x86_ops.sync_pir_to_irr = NULL;
8290
8291         if (!enable_apicv || !cpu_has_vmx_ipiv())
8292                 enable_ipiv = false;
8293
8294         if (cpu_has_vmx_tsc_scaling())
8295                 kvm_caps.has_tsc_control = true;
8296
8297         kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8298         kvm_caps.tsc_scaling_ratio_frac_bits = 48;
8299         kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
8300         kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
8301
8302         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8303
8304         if (enable_ept)
8305                 kvm_mmu_set_ept_masks(enable_ept_ad_bits,
8306                                       cpu_has_vmx_ept_execute_only());
8307
8308         /*
8309          * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID
8310          * bits to shadow_zero_check.
8311          */
8312         vmx_setup_me_spte_mask();
8313
8314         kvm_configure_mmu(enable_ept, 0, vmx_get_max_tdp_level(),
8315                           ept_caps_to_lpage_level(vmx_capability.ept));
8316
8317         /*
8318          * Only enable PML when hardware supports PML feature, and both EPT
8319          * and EPT A/D bit features are enabled -- PML depends on them to work.
8320          */
8321         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8322                 enable_pml = 0;
8323
8324         if (!enable_pml)
8325                 vmx_x86_ops.cpu_dirty_log_size = 0;
8326
8327         if (!cpu_has_vmx_preemption_timer())
8328                 enable_preemption_timer = false;
8329
8330         if (enable_preemption_timer) {
8331                 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8332
8333                 cpu_preemption_timer_multi =
8334                         vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8335
8336                 if (tsc_khz)
8337                         use_timer_freq = (u64)tsc_khz * 1000;
8338                 use_timer_freq >>= cpu_preemption_timer_multi;
8339
8340                 /*
8341                  * KVM "disables" the preemption timer by setting it to its max
8342                  * value.  Don't use the timer if it might cause spurious exits
8343                  * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8344                  */
8345                 if (use_timer_freq > 0xffffffffu / 10)
8346                         enable_preemption_timer = false;
8347         }
8348
8349         if (!enable_preemption_timer) {
8350                 vmx_x86_ops.set_hv_timer = NULL;
8351                 vmx_x86_ops.cancel_hv_timer = NULL;
8352                 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8353         }
8354
8355         kvm_caps.supported_mce_cap |= MCG_LMCE_P;
8356         kvm_caps.supported_mce_cap |= MCG_CMCI_P;
8357
8358         if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8359                 return -EINVAL;
8360         if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt())
8361                 pt_mode = PT_MODE_SYSTEM;
8362         if (pt_mode == PT_MODE_HOST_GUEST)
8363                 vmx_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr;
8364         else
8365                 vmx_init_ops.handle_intel_pt_intr = NULL;
8366
8367         setup_default_sgx_lepubkeyhash();
8368
8369         if (nested) {
8370                 nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
8371
8372                 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8373                 if (r)
8374                         return r;
8375         }
8376
8377         vmx_set_cpu_caps();
8378
8379         r = alloc_kvm_area();
8380         if (r && nested)
8381                 nested_vmx_hardware_unsetup();
8382
8383         kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler);
8384
8385         return r;
8386 }
8387
8388 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8389         .cpu_has_kvm_support = cpu_has_kvm_support,
8390         .disabled_by_bios = vmx_disabled_by_bios,
8391         .check_processor_compatibility = vmx_check_processor_compat,
8392         .hardware_setup = hardware_setup,
8393         .handle_intel_pt_intr = NULL,
8394
8395         .runtime_ops = &vmx_x86_ops,
8396         .pmu_ops = &intel_pmu_ops,
8397 };
8398
8399 static void vmx_cleanup_l1d_flush(void)
8400 {
8401         if (vmx_l1d_flush_pages) {
8402                 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8403                 vmx_l1d_flush_pages = NULL;
8404         }
8405         /* Restore state so sysfs ignores VMX */
8406         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8407 }
8408
8409 static void vmx_exit(void)
8410 {
8411 #ifdef CONFIG_KEXEC_CORE
8412         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8413         synchronize_rcu();
8414 #endif
8415
8416         kvm_exit();
8417
8418 #if IS_ENABLED(CONFIG_HYPERV)
8419         if (static_branch_unlikely(&enable_evmcs)) {
8420                 int cpu;
8421                 struct hv_vp_assist_page *vp_ap;
8422                 /*
8423                  * Reset everything to support using non-enlightened VMCS
8424                  * access later (e.g. when we reload the module with
8425                  * enlightened_vmcs=0)
8426                  */
8427                 for_each_online_cpu(cpu) {
8428                         vp_ap = hv_get_vp_assist_page(cpu);
8429
8430                         if (!vp_ap)
8431                                 continue;
8432
8433                         vp_ap->nested_control.features.directhypercall = 0;
8434                         vp_ap->current_nested_vmcs = 0;
8435                         vp_ap->enlighten_vmentry = 0;
8436                 }
8437
8438                 static_branch_disable(&enable_evmcs);
8439         }
8440 #endif
8441         vmx_cleanup_l1d_flush();
8442
8443         allow_smaller_maxphyaddr = false;
8444 }
8445 module_exit(vmx_exit);
8446
8447 static int __init vmx_init(void)
8448 {
8449         int r, cpu;
8450
8451 #if IS_ENABLED(CONFIG_HYPERV)
8452         /*
8453          * Enlightened VMCS usage should be recommended and the host needs
8454          * to support eVMCS v1 or above. We can also disable eVMCS support
8455          * with module parameter.
8456          */
8457         if (enlightened_vmcs &&
8458             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8459             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8460             KVM_EVMCS_VERSION) {
8461
8462                 /* Check that we have assist pages on all online CPUs */
8463                 for_each_online_cpu(cpu) {
8464                         if (!hv_get_vp_assist_page(cpu)) {
8465                                 enlightened_vmcs = false;
8466                                 break;
8467                         }
8468                 }
8469
8470                 if (enlightened_vmcs) {
8471                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8472                         static_branch_enable(&enable_evmcs);
8473                 }
8474
8475                 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8476                         vmx_x86_ops.enable_direct_tlbflush
8477                                 = hv_enable_direct_tlbflush;
8478
8479         } else {
8480                 enlightened_vmcs = false;
8481         }
8482 #endif
8483
8484         r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8485                      __alignof__(struct vcpu_vmx), THIS_MODULE);
8486         if (r)
8487                 return r;
8488
8489         /*
8490          * Must be called after kvm_init() so enable_ept is properly set
8491          * up. Hand the parameter mitigation value in which was stored in
8492          * the pre module init parser. If no parameter was given, it will
8493          * contain 'auto' which will be turned into the default 'cond'
8494          * mitigation mode.
8495          */
8496         r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8497         if (r) {
8498                 vmx_exit();
8499                 return r;
8500         }
8501
8502         vmx_setup_fb_clear_ctrl();
8503
8504         for_each_possible_cpu(cpu) {
8505                 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8506
8507                 pi_init_cpu(cpu);
8508         }
8509
8510 #ifdef CONFIG_KEXEC_CORE
8511         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8512                            crash_vmclear_local_loaded_vmcss);
8513 #endif
8514         vmx_check_vmcs12_offsets();
8515
8516         /*
8517          * Shadow paging doesn't have a (further) performance penalty
8518          * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it
8519          * by default
8520          */
8521         if (!enable_ept)
8522                 allow_smaller_maxphyaddr = true;
8523
8524         return 0;
8525 }
8526 module_init(vmx_init);