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