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