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