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