Merge branch 'x86/urgent' into x86/cleanups
[sfrench/cifs-2.6.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 1;
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 (data & ~kvm_spec_ctrl_valid_bits(vcpu))
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 = 3;
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                 return 0;
4789         }
4790
4791         if (is_page_fault(intr_info)) {
4792                 cr2 = vmx_get_exit_qual(vcpu);
4793                 /* EPT won't cause page fault directly */
4794                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_flags && enable_ept);
4795                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4796         }
4797
4798         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4799
4800         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4801                 return handle_rmode_exception(vcpu, ex_no, error_code);
4802
4803         switch (ex_no) {
4804         case DB_VECTOR:
4805                 dr6 = vmx_get_exit_qual(vcpu);
4806                 if (!(vcpu->guest_debug &
4807                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4808                         if (is_icebp(intr_info))
4809                                 WARN_ON(!skip_emulated_instruction(vcpu));
4810
4811                         kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4812                         return 1;
4813                 }
4814                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
4815                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4816                 /* fall through */
4817         case BP_VECTOR:
4818                 /*
4819                  * Update instruction length as we may reinject #BP from
4820                  * user space while in guest debugging mode. Reading it for
4821                  * #DB as well causes no harm, it is not used in that case.
4822                  */
4823                 vmx->vcpu.arch.event_exit_inst_len =
4824                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4825                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4826                 rip = kvm_rip_read(vcpu);
4827                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4828                 kvm_run->debug.arch.exception = ex_no;
4829                 break;
4830         case AC_VECTOR:
4831                 if (guest_inject_ac(vcpu)) {
4832                         kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4833                         return 1;
4834                 }
4835
4836                 /*
4837                  * Handle split lock. Depending on detection mode this will
4838                  * either warn and disable split lock detection for this
4839                  * task or force SIGBUS on it.
4840                  */
4841                 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4842                         return 1;
4843                 fallthrough;
4844         default:
4845                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4846                 kvm_run->ex.exception = ex_no;
4847                 kvm_run->ex.error_code = error_code;
4848                 break;
4849         }
4850         return 0;
4851 }
4852
4853 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4854 {
4855         ++vcpu->stat.irq_exits;
4856         return 1;
4857 }
4858
4859 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4860 {
4861         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4862         vcpu->mmio_needed = 0;
4863         return 0;
4864 }
4865
4866 static int handle_io(struct kvm_vcpu *vcpu)
4867 {
4868         unsigned long exit_qualification;
4869         int size, in, string;
4870         unsigned port;
4871
4872         exit_qualification = vmx_get_exit_qual(vcpu);
4873         string = (exit_qualification & 16) != 0;
4874
4875         ++vcpu->stat.io_exits;
4876
4877         if (string)
4878                 return kvm_emulate_instruction(vcpu, 0);
4879
4880         port = exit_qualification >> 16;
4881         size = (exit_qualification & 7) + 1;
4882         in = (exit_qualification & 8) != 0;
4883
4884         return kvm_fast_pio(vcpu, size, port, in);
4885 }
4886
4887 static void
4888 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4889 {
4890         /*
4891          * Patch in the VMCALL instruction:
4892          */
4893         hypercall[0] = 0x0f;
4894         hypercall[1] = 0x01;
4895         hypercall[2] = 0xc1;
4896 }
4897
4898 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4899 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4900 {
4901         if (is_guest_mode(vcpu)) {
4902                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4903                 unsigned long orig_val = val;
4904
4905                 /*
4906                  * We get here when L2 changed cr0 in a way that did not change
4907                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4908                  * but did change L0 shadowed bits. So we first calculate the
4909                  * effective cr0 value that L1 would like to write into the
4910                  * hardware. It consists of the L2-owned bits from the new
4911                  * value combined with the L1-owned bits from L1's guest_cr0.
4912                  */
4913                 val = (val & ~vmcs12->cr0_guest_host_mask) |
4914                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4915
4916                 if (!nested_guest_cr0_valid(vcpu, val))
4917                         return 1;
4918
4919                 if (kvm_set_cr0(vcpu, val))
4920                         return 1;
4921                 vmcs_writel(CR0_READ_SHADOW, orig_val);
4922                 return 0;
4923         } else {
4924                 if (to_vmx(vcpu)->nested.vmxon &&
4925                     !nested_host_cr0_valid(vcpu, val))
4926                         return 1;
4927
4928                 return kvm_set_cr0(vcpu, val);
4929         }
4930 }
4931
4932 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4933 {
4934         if (is_guest_mode(vcpu)) {
4935                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4936                 unsigned long orig_val = val;
4937
4938                 /* analogously to handle_set_cr0 */
4939                 val = (val & ~vmcs12->cr4_guest_host_mask) |
4940                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4941                 if (kvm_set_cr4(vcpu, val))
4942                         return 1;
4943                 vmcs_writel(CR4_READ_SHADOW, orig_val);
4944                 return 0;
4945         } else
4946                 return kvm_set_cr4(vcpu, val);
4947 }
4948
4949 static int handle_desc(struct kvm_vcpu *vcpu)
4950 {
4951         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4952         return kvm_emulate_instruction(vcpu, 0);
4953 }
4954
4955 static int handle_cr(struct kvm_vcpu *vcpu)
4956 {
4957         unsigned long exit_qualification, val;
4958         int cr;
4959         int reg;
4960         int err;
4961         int ret;
4962
4963         exit_qualification = vmx_get_exit_qual(vcpu);
4964         cr = exit_qualification & 15;
4965         reg = (exit_qualification >> 8) & 15;
4966         switch ((exit_qualification >> 4) & 3) {
4967         case 0: /* mov to cr */
4968                 val = kvm_register_readl(vcpu, reg);
4969                 trace_kvm_cr_write(cr, val);
4970                 switch (cr) {
4971                 case 0:
4972                         err = handle_set_cr0(vcpu, val);
4973                         return kvm_complete_insn_gp(vcpu, err);
4974                 case 3:
4975                         WARN_ON_ONCE(enable_unrestricted_guest);
4976                         err = kvm_set_cr3(vcpu, val);
4977                         return kvm_complete_insn_gp(vcpu, err);
4978                 case 4:
4979                         err = handle_set_cr4(vcpu, val);
4980                         return kvm_complete_insn_gp(vcpu, err);
4981                 case 8: {
4982                                 u8 cr8_prev = kvm_get_cr8(vcpu);
4983                                 u8 cr8 = (u8)val;
4984                                 err = kvm_set_cr8(vcpu, cr8);
4985                                 ret = kvm_complete_insn_gp(vcpu, err);
4986                                 if (lapic_in_kernel(vcpu))
4987                                         return ret;
4988                                 if (cr8_prev <= cr8)
4989                                         return ret;
4990                                 /*
4991                                  * TODO: we might be squashing a
4992                                  * KVM_GUESTDBG_SINGLESTEP-triggered
4993                                  * KVM_EXIT_DEBUG here.
4994                                  */
4995                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4996                                 return 0;
4997                         }
4998                 }
4999                 break;
5000         case 2: /* clts */
5001                 WARN_ONCE(1, "Guest should always own CR0.TS");
5002                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5003                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5004                 return kvm_skip_emulated_instruction(vcpu);
5005         case 1: /*mov from cr*/
5006                 switch (cr) {
5007                 case 3:
5008                         WARN_ON_ONCE(enable_unrestricted_guest);
5009                         val = kvm_read_cr3(vcpu);
5010                         kvm_register_write(vcpu, reg, val);
5011                         trace_kvm_cr_read(cr, val);
5012                         return kvm_skip_emulated_instruction(vcpu);
5013                 case 8:
5014                         val = kvm_get_cr8(vcpu);
5015                         kvm_register_write(vcpu, reg, val);
5016                         trace_kvm_cr_read(cr, val);
5017                         return kvm_skip_emulated_instruction(vcpu);
5018                 }
5019                 break;
5020         case 3: /* lmsw */
5021                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5022                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5023                 kvm_lmsw(vcpu, val);
5024
5025                 return kvm_skip_emulated_instruction(vcpu);
5026         default:
5027                 break;
5028         }
5029         vcpu->run->exit_reason = 0;
5030         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5031                (int)(exit_qualification >> 4) & 3, cr);
5032         return 0;
5033 }
5034
5035 static int handle_dr(struct kvm_vcpu *vcpu)
5036 {
5037         unsigned long exit_qualification;
5038         int dr, dr7, reg;
5039
5040         exit_qualification = vmx_get_exit_qual(vcpu);
5041         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5042
5043         /* First, if DR does not exist, trigger UD */
5044         if (!kvm_require_dr(vcpu, dr))
5045                 return 1;
5046
5047         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5048         if (!kvm_require_cpl(vcpu, 0))
5049                 return 1;
5050         dr7 = vmcs_readl(GUEST_DR7);
5051         if (dr7 & DR7_GD) {
5052                 /*
5053                  * As the vm-exit takes precedence over the debug trap, we
5054                  * need to emulate the latter, either for the host or the
5055                  * guest debugging itself.
5056                  */
5057                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5058                         vcpu->run->debug.arch.dr6 = DR6_BD | DR6_RTM | DR6_FIXED_1;
5059                         vcpu->run->debug.arch.dr7 = dr7;
5060                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5061                         vcpu->run->debug.arch.exception = DB_VECTOR;
5062                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5063                         return 0;
5064                 } else {
5065                         kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5066                         return 1;
5067                 }
5068         }
5069
5070         if (vcpu->guest_debug == 0) {
5071                 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5072
5073                 /*
5074                  * No more DR vmexits; force a reload of the debug registers
5075                  * and reenter on this instruction.  The next vmexit will
5076                  * retrieve the full state of the debug registers.
5077                  */
5078                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5079                 return 1;
5080         }
5081
5082         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5083         if (exit_qualification & TYPE_MOV_FROM_DR) {
5084                 unsigned long val;
5085
5086                 if (kvm_get_dr(vcpu, dr, &val))
5087                         return 1;
5088                 kvm_register_write(vcpu, reg, val);
5089         } else
5090                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5091                         return 1;
5092
5093         return kvm_skip_emulated_instruction(vcpu);
5094 }
5095
5096 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5097 {
5098         get_debugreg(vcpu->arch.db[0], 0);
5099         get_debugreg(vcpu->arch.db[1], 1);
5100         get_debugreg(vcpu->arch.db[2], 2);
5101         get_debugreg(vcpu->arch.db[3], 3);
5102         get_debugreg(vcpu->arch.dr6, 6);
5103         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5104
5105         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5106         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5107 }
5108
5109 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5110 {
5111         vmcs_writel(GUEST_DR7, val);
5112 }
5113
5114 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5115 {
5116         kvm_apic_update_ppr(vcpu);
5117         return 1;
5118 }
5119
5120 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5121 {
5122         exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5123
5124         kvm_make_request(KVM_REQ_EVENT, vcpu);
5125
5126         ++vcpu->stat.irq_window_exits;
5127         return 1;
5128 }
5129
5130 static int handle_vmcall(struct kvm_vcpu *vcpu)
5131 {
5132         return kvm_emulate_hypercall(vcpu);
5133 }
5134
5135 static int handle_invd(struct kvm_vcpu *vcpu)
5136 {
5137         return kvm_emulate_instruction(vcpu, 0);
5138 }
5139
5140 static int handle_invlpg(struct kvm_vcpu *vcpu)
5141 {
5142         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5143
5144         kvm_mmu_invlpg(vcpu, exit_qualification);
5145         return kvm_skip_emulated_instruction(vcpu);
5146 }
5147
5148 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5149 {
5150         int err;
5151
5152         err = kvm_rdpmc(vcpu);
5153         return kvm_complete_insn_gp(vcpu, err);
5154 }
5155
5156 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5157 {
5158         return kvm_emulate_wbinvd(vcpu);
5159 }
5160
5161 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5162 {
5163         u64 new_bv = kvm_read_edx_eax(vcpu);
5164         u32 index = kvm_rcx_read(vcpu);
5165
5166         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5167                 return kvm_skip_emulated_instruction(vcpu);
5168         return 1;
5169 }
5170
5171 static int handle_apic_access(struct kvm_vcpu *vcpu)
5172 {
5173         if (likely(fasteoi)) {
5174                 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5175                 int access_type, offset;
5176
5177                 access_type = exit_qualification & APIC_ACCESS_TYPE;
5178                 offset = exit_qualification & APIC_ACCESS_OFFSET;
5179                 /*
5180                  * Sane guest uses MOV to write EOI, with written value
5181                  * not cared. So make a short-circuit here by avoiding
5182                  * heavy instruction emulation.
5183                  */
5184                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5185                     (offset == APIC_EOI)) {
5186                         kvm_lapic_set_eoi(vcpu);
5187                         return kvm_skip_emulated_instruction(vcpu);
5188                 }
5189         }
5190         return kvm_emulate_instruction(vcpu, 0);
5191 }
5192
5193 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5194 {
5195         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5196         int vector = exit_qualification & 0xff;
5197
5198         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5199         kvm_apic_set_eoi_accelerated(vcpu, vector);
5200         return 1;
5201 }
5202
5203 static int handle_apic_write(struct kvm_vcpu *vcpu)
5204 {
5205         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5206         u32 offset = exit_qualification & 0xfff;
5207
5208         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5209         kvm_apic_write_nodecode(vcpu, offset);
5210         return 1;
5211 }
5212
5213 static int handle_task_switch(struct kvm_vcpu *vcpu)
5214 {
5215         struct vcpu_vmx *vmx = to_vmx(vcpu);
5216         unsigned long exit_qualification;
5217         bool has_error_code = false;
5218         u32 error_code = 0;
5219         u16 tss_selector;
5220         int reason, type, idt_v, idt_index;
5221
5222         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5223         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5224         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5225
5226         exit_qualification = vmx_get_exit_qual(vcpu);
5227
5228         reason = (u32)exit_qualification >> 30;
5229         if (reason == TASK_SWITCH_GATE && idt_v) {
5230                 switch (type) {
5231                 case INTR_TYPE_NMI_INTR:
5232                         vcpu->arch.nmi_injected = false;
5233                         vmx_set_nmi_mask(vcpu, true);
5234                         break;
5235                 case INTR_TYPE_EXT_INTR:
5236                 case INTR_TYPE_SOFT_INTR:
5237                         kvm_clear_interrupt_queue(vcpu);
5238                         break;
5239                 case INTR_TYPE_HARD_EXCEPTION:
5240                         if (vmx->idt_vectoring_info &
5241                             VECTORING_INFO_DELIVER_CODE_MASK) {
5242                                 has_error_code = true;
5243                                 error_code =
5244                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
5245                         }
5246                         /* fall through */
5247                 case INTR_TYPE_SOFT_EXCEPTION:
5248                         kvm_clear_exception_queue(vcpu);
5249                         break;
5250                 default:
5251                         break;
5252                 }
5253         }
5254         tss_selector = exit_qualification;
5255
5256         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5257                        type != INTR_TYPE_EXT_INTR &&
5258                        type != INTR_TYPE_NMI_INTR))
5259                 WARN_ON(!skip_emulated_instruction(vcpu));
5260
5261         /*
5262          * TODO: What about debug traps on tss switch?
5263          *       Are we supposed to inject them and update dr6?
5264          */
5265         return kvm_task_switch(vcpu, tss_selector,
5266                                type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5267                                reason, has_error_code, error_code);
5268 }
5269
5270 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5271 {
5272         unsigned long exit_qualification;
5273         gpa_t gpa;
5274         u64 error_code;
5275
5276         exit_qualification = vmx_get_exit_qual(vcpu);
5277
5278         /*
5279          * EPT violation happened while executing iret from NMI,
5280          * "blocked by NMI" bit has to be set before next VM entry.
5281          * There are errata that may cause this bit to not be set:
5282          * AAK134, BY25.
5283          */
5284         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5285                         enable_vnmi &&
5286                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5287                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5288
5289         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5290         trace_kvm_page_fault(gpa, exit_qualification);
5291
5292         /* Is it a read fault? */
5293         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5294                      ? PFERR_USER_MASK : 0;
5295         /* Is it a write fault? */
5296         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5297                       ? PFERR_WRITE_MASK : 0;
5298         /* Is it a fetch fault? */
5299         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5300                       ? PFERR_FETCH_MASK : 0;
5301         /* ept page table entry is present? */
5302         error_code |= (exit_qualification &
5303                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5304                         EPT_VIOLATION_EXECUTABLE))
5305                       ? PFERR_PRESENT_MASK : 0;
5306
5307         error_code |= (exit_qualification & 0x100) != 0 ?
5308                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5309
5310         vcpu->arch.exit_qualification = exit_qualification;
5311         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5312 }
5313
5314 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5315 {
5316         gpa_t gpa;
5317
5318         /*
5319          * A nested guest cannot optimize MMIO vmexits, because we have an
5320          * nGPA here instead of the required GPA.
5321          */
5322         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5323         if (!is_guest_mode(vcpu) &&
5324             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5325                 trace_kvm_fast_mmio(gpa);
5326                 return kvm_skip_emulated_instruction(vcpu);
5327         }
5328
5329         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5330 }
5331
5332 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5333 {
5334         WARN_ON_ONCE(!enable_vnmi);
5335         exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5336         ++vcpu->stat.nmi_window_exits;
5337         kvm_make_request(KVM_REQ_EVENT, vcpu);
5338
5339         return 1;
5340 }
5341
5342 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5343 {
5344         struct vcpu_vmx *vmx = to_vmx(vcpu);
5345         bool intr_window_requested;
5346         unsigned count = 130;
5347
5348         intr_window_requested = exec_controls_get(vmx) &
5349                                 CPU_BASED_INTR_WINDOW_EXITING;
5350
5351         while (vmx->emulation_required && count-- != 0) {
5352                 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5353                         return handle_interrupt_window(&vmx->vcpu);
5354
5355                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5356                         return 1;
5357
5358                 if (!kvm_emulate_instruction(vcpu, 0))
5359                         return 0;
5360
5361                 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5362                     vcpu->arch.exception.pending) {
5363                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5364                         vcpu->run->internal.suberror =
5365                                                 KVM_INTERNAL_ERROR_EMULATION;
5366                         vcpu->run->internal.ndata = 0;
5367                         return 0;
5368                 }
5369
5370                 if (vcpu->arch.halt_request) {
5371                         vcpu->arch.halt_request = 0;
5372                         return kvm_vcpu_halt(vcpu);
5373                 }
5374
5375                 /*
5376                  * Note, return 1 and not 0, vcpu_run() is responsible for
5377                  * morphing the pending signal into the proper return code.
5378                  */
5379                 if (signal_pending(current))
5380                         return 1;
5381
5382                 if (need_resched())
5383                         schedule();
5384         }
5385
5386         return 1;
5387 }
5388
5389 static void grow_ple_window(struct kvm_vcpu *vcpu)
5390 {
5391         struct vcpu_vmx *vmx = to_vmx(vcpu);
5392         unsigned int old = vmx->ple_window;
5393
5394         vmx->ple_window = __grow_ple_window(old, ple_window,
5395                                             ple_window_grow,
5396                                             ple_window_max);
5397
5398         if (vmx->ple_window != old) {
5399                 vmx->ple_window_dirty = true;
5400                 trace_kvm_ple_window_update(vcpu->vcpu_id,
5401                                             vmx->ple_window, old);
5402         }
5403 }
5404
5405 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5406 {
5407         struct vcpu_vmx *vmx = to_vmx(vcpu);
5408         unsigned int old = vmx->ple_window;
5409
5410         vmx->ple_window = __shrink_ple_window(old, ple_window,
5411                                               ple_window_shrink,
5412                                               ple_window);
5413
5414         if (vmx->ple_window != old) {
5415                 vmx->ple_window_dirty = true;
5416                 trace_kvm_ple_window_update(vcpu->vcpu_id,
5417                                             vmx->ple_window, old);
5418         }
5419 }
5420
5421 /*
5422  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5423  */
5424 static void wakeup_handler(void)
5425 {
5426         struct kvm_vcpu *vcpu;
5427         int cpu = smp_processor_id();
5428
5429         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5430         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5431                         blocked_vcpu_list) {
5432                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5433
5434                 if (pi_test_on(pi_desc) == 1)
5435                         kvm_vcpu_kick(vcpu);
5436         }
5437         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5438 }
5439
5440 static void vmx_enable_tdp(void)
5441 {
5442         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5443                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5444                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5445                 0ull, VMX_EPT_EXECUTABLE_MASK,
5446                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5447                 VMX_EPT_RWX_MASK, 0ull);
5448
5449         ept_set_mmio_spte_mask();
5450 }
5451
5452 /*
5453  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5454  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5455  */
5456 static int handle_pause(struct kvm_vcpu *vcpu)
5457 {
5458         if (!kvm_pause_in_guest(vcpu->kvm))
5459                 grow_ple_window(vcpu);
5460
5461         /*
5462          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5463          * VM-execution control is ignored if CPL > 0. OTOH, KVM
5464          * never set PAUSE_EXITING and just set PLE if supported,
5465          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5466          */
5467         kvm_vcpu_on_spin(vcpu, true);
5468         return kvm_skip_emulated_instruction(vcpu);
5469 }
5470
5471 static int handle_nop(struct kvm_vcpu *vcpu)
5472 {
5473         return kvm_skip_emulated_instruction(vcpu);
5474 }
5475
5476 static int handle_mwait(struct kvm_vcpu *vcpu)
5477 {
5478         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5479         return handle_nop(vcpu);
5480 }
5481
5482 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5483 {
5484         kvm_queue_exception(vcpu, UD_VECTOR);
5485         return 1;
5486 }
5487
5488 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5489 {
5490         return 1;
5491 }
5492
5493 static int handle_monitor(struct kvm_vcpu *vcpu)
5494 {
5495         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5496         return handle_nop(vcpu);
5497 }
5498
5499 static int handle_invpcid(struct kvm_vcpu *vcpu)
5500 {
5501         u32 vmx_instruction_info;
5502         unsigned long type;
5503         bool pcid_enabled;
5504         gva_t gva;
5505         struct x86_exception e;
5506         unsigned i;
5507         unsigned long roots_to_free = 0;
5508         struct {
5509                 u64 pcid;
5510                 u64 gla;
5511         } operand;
5512         int r;
5513
5514         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5515                 kvm_queue_exception(vcpu, UD_VECTOR);
5516                 return 1;
5517         }
5518
5519         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5520         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5521
5522         if (type > 3) {
5523                 kvm_inject_gp(vcpu, 0);
5524                 return 1;
5525         }
5526
5527         /* According to the Intel instruction reference, the memory operand
5528          * is read even if it isn't needed (e.g., for type==all)
5529          */
5530         if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5531                                 vmx_instruction_info, false,
5532                                 sizeof(operand), &gva))
5533                 return 1;
5534
5535         r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
5536         if (r != X86EMUL_CONTINUE)
5537                 return vmx_handle_memory_failure(vcpu, r, &e);
5538
5539         if (operand.pcid >> 12 != 0) {
5540                 kvm_inject_gp(vcpu, 0);
5541                 return 1;
5542         }
5543
5544         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5545
5546         switch (type) {
5547         case INVPCID_TYPE_INDIV_ADDR:
5548                 if ((!pcid_enabled && (operand.pcid != 0)) ||
5549                     is_noncanonical_address(operand.gla, vcpu)) {
5550                         kvm_inject_gp(vcpu, 0);
5551                         return 1;
5552                 }
5553                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5554                 return kvm_skip_emulated_instruction(vcpu);
5555
5556         case INVPCID_TYPE_SINGLE_CTXT:
5557                 if (!pcid_enabled && (operand.pcid != 0)) {
5558                         kvm_inject_gp(vcpu, 0);
5559                         return 1;
5560                 }
5561
5562                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5563                         kvm_mmu_sync_roots(vcpu);
5564                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
5565                 }
5566
5567                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5568                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
5569                             == operand.pcid)
5570                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5571
5572                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5573                 /*
5574                  * If neither the current cr3 nor any of the prev_roots use the
5575                  * given PCID, then nothing needs to be done here because a
5576                  * resync will happen anyway before switching to any other CR3.
5577                  */
5578
5579                 return kvm_skip_emulated_instruction(vcpu);
5580
5581         case INVPCID_TYPE_ALL_NON_GLOBAL:
5582                 /*
5583                  * Currently, KVM doesn't mark global entries in the shadow
5584                  * page tables, so a non-global flush just degenerates to a
5585                  * global flush. If needed, we could optimize this later by
5586                  * keeping track of global entries in shadow page tables.
5587                  */
5588
5589                 /* fall-through */
5590         case INVPCID_TYPE_ALL_INCL_GLOBAL:
5591                 kvm_mmu_unload(vcpu);
5592                 return kvm_skip_emulated_instruction(vcpu);
5593
5594         default:
5595                 BUG(); /* We have already checked above that type <= 3 */
5596         }
5597 }
5598
5599 static int handle_pml_full(struct kvm_vcpu *vcpu)
5600 {
5601         unsigned long exit_qualification;
5602
5603         trace_kvm_pml_full(vcpu->vcpu_id);
5604
5605         exit_qualification = vmx_get_exit_qual(vcpu);
5606
5607         /*
5608          * PML buffer FULL happened while executing iret from NMI,
5609          * "blocked by NMI" bit has to be set before next VM entry.
5610          */
5611         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5612                         enable_vnmi &&
5613                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5614                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5615                                 GUEST_INTR_STATE_NMI);
5616
5617         /*
5618          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5619          * here.., and there's no userspace involvement needed for PML.
5620          */
5621         return 1;
5622 }
5623
5624 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5625 {
5626         struct vcpu_vmx *vmx = to_vmx(vcpu);
5627
5628         if (!vmx->req_immediate_exit &&
5629             !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5630                 kvm_lapic_expired_hv_timer(vcpu);
5631                 return EXIT_FASTPATH_REENTER_GUEST;
5632         }
5633
5634         return EXIT_FASTPATH_NONE;
5635 }
5636
5637 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5638 {
5639         handle_fastpath_preemption_timer(vcpu);
5640         return 1;
5641 }
5642
5643 /*
5644  * When nested=0, all VMX instruction VM Exits filter here.  The handlers
5645  * are overwritten by nested_vmx_setup() when nested=1.
5646  */
5647 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5648 {
5649         kvm_queue_exception(vcpu, UD_VECTOR);
5650         return 1;
5651 }
5652
5653 static int handle_encls(struct kvm_vcpu *vcpu)
5654 {
5655         /*
5656          * SGX virtualization is not yet supported.  There is no software
5657          * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5658          * to prevent the guest from executing ENCLS.
5659          */
5660         kvm_queue_exception(vcpu, UD_VECTOR);
5661         return 1;
5662 }
5663
5664 /*
5665  * The exit handlers return 1 if the exit was handled fully and guest execution
5666  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
5667  * to be done to userspace and return 0.
5668  */
5669 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5670         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception_nmi,
5671         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
5672         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
5673         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
5674         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
5675         [EXIT_REASON_CR_ACCESS]               = handle_cr,
5676         [EXIT_REASON_DR_ACCESS]               = handle_dr,
5677         [EXIT_REASON_CPUID]                   = kvm_emulate_cpuid,
5678         [EXIT_REASON_MSR_READ]                = kvm_emulate_rdmsr,
5679         [EXIT_REASON_MSR_WRITE]               = kvm_emulate_wrmsr,
5680         [EXIT_REASON_INTERRUPT_WINDOW]        = handle_interrupt_window,
5681         [EXIT_REASON_HLT]                     = kvm_emulate_halt,
5682         [EXIT_REASON_INVD]                    = handle_invd,
5683         [EXIT_REASON_INVLPG]                  = handle_invlpg,
5684         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
5685         [EXIT_REASON_VMCALL]                  = handle_vmcall,
5686         [EXIT_REASON_VMCLEAR]                 = handle_vmx_instruction,
5687         [EXIT_REASON_VMLAUNCH]                = handle_vmx_instruction,
5688         [EXIT_REASON_VMPTRLD]                 = handle_vmx_instruction,
5689         [EXIT_REASON_VMPTRST]                 = handle_vmx_instruction,
5690         [EXIT_REASON_VMREAD]                  = handle_vmx_instruction,
5691         [EXIT_REASON_VMRESUME]                = handle_vmx_instruction,
5692         [EXIT_REASON_VMWRITE]                 = handle_vmx_instruction,
5693         [EXIT_REASON_VMOFF]                   = handle_vmx_instruction,
5694         [EXIT_REASON_VMON]                    = handle_vmx_instruction,
5695         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
5696         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
5697         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
5698         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
5699         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
5700         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
5701         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
5702         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
5703         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
5704         [EXIT_REASON_LDTR_TR]                 = handle_desc,
5705         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
5706         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
5707         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
5708         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
5709         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
5710         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
5711         [EXIT_REASON_INVEPT]                  = handle_vmx_instruction,
5712         [EXIT_REASON_INVVPID]                 = handle_vmx_instruction,
5713         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
5714         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
5715         [EXIT_REASON_PML_FULL]                = handle_pml_full,
5716         [EXIT_REASON_INVPCID]                 = handle_invpcid,
5717         [EXIT_REASON_VMFUNC]                  = handle_vmx_instruction,
5718         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
5719         [EXIT_REASON_ENCLS]                   = handle_encls,
5720 };
5721
5722 static const int kvm_vmx_max_exit_handlers =
5723         ARRAY_SIZE(kvm_vmx_exit_handlers);
5724
5725 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5726 {
5727         *info1 = vmx_get_exit_qual(vcpu);
5728         *info2 = vmx_get_intr_info(vcpu);
5729 }
5730
5731 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5732 {
5733         if (vmx->pml_pg) {
5734                 __free_page(vmx->pml_pg);
5735                 vmx->pml_pg = NULL;
5736         }
5737 }
5738
5739 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5740 {
5741         struct vcpu_vmx *vmx = to_vmx(vcpu);
5742         u64 *pml_buf;
5743         u16 pml_idx;
5744
5745         pml_idx = vmcs_read16(GUEST_PML_INDEX);
5746
5747         /* Do nothing if PML buffer is empty */
5748         if (pml_idx == (PML_ENTITY_NUM - 1))
5749                 return;
5750
5751         /* PML index always points to next available PML buffer entity */
5752         if (pml_idx >= PML_ENTITY_NUM)
5753                 pml_idx = 0;
5754         else
5755                 pml_idx++;
5756
5757         pml_buf = page_address(vmx->pml_pg);
5758         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5759                 u64 gpa;
5760
5761                 gpa = pml_buf[pml_idx];
5762                 WARN_ON(gpa & (PAGE_SIZE - 1));
5763                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5764         }
5765
5766         /* reset PML index */
5767         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5768 }
5769
5770 /*
5771  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5772  * Called before reporting dirty_bitmap to userspace.
5773  */
5774 static void kvm_flush_pml_buffers(struct kvm *kvm)
5775 {
5776         int i;
5777         struct kvm_vcpu *vcpu;
5778         /*
5779          * We only need to kick vcpu out of guest mode here, as PML buffer
5780          * is flushed at beginning of all VMEXITs, and it's obvious that only
5781          * vcpus running in guest are possible to have unflushed GPAs in PML
5782          * buffer.
5783          */
5784         kvm_for_each_vcpu(i, vcpu, kvm)
5785                 kvm_vcpu_kick(vcpu);
5786 }
5787
5788 static void vmx_dump_sel(char *name, uint32_t sel)
5789 {
5790         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5791                name, vmcs_read16(sel),
5792                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5793                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5794                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5795 }
5796
5797 static void vmx_dump_dtsel(char *name, uint32_t limit)
5798 {
5799         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
5800                name, vmcs_read32(limit),
5801                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5802 }
5803
5804 void dump_vmcs(void)
5805 {
5806         u32 vmentry_ctl, vmexit_ctl;
5807         u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5808         unsigned long cr4;
5809         u64 efer;
5810
5811         if (!dump_invalid_vmcs) {
5812                 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5813                 return;
5814         }
5815
5816         vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5817         vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5818         cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5819         pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5820         cr4 = vmcs_readl(GUEST_CR4);
5821         efer = vmcs_read64(GUEST_IA32_EFER);
5822         secondary_exec_control = 0;
5823         if (cpu_has_secondary_exec_ctrls())
5824                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5825
5826         pr_err("*** Guest State ***\n");
5827         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5828                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5829                vmcs_readl(CR0_GUEST_HOST_MASK));
5830         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5831                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5832         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5833         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5834             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5835         {
5836                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
5837                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5838                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
5839                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5840         }
5841         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
5842                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5843         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
5844                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5845         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5846                vmcs_readl(GUEST_SYSENTER_ESP),
5847                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5848         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
5849         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
5850         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
5851         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
5852         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
5853         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
5854         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5855         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5856         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5857         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
5858         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5859             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5860                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
5861                        efer, vmcs_read64(GUEST_IA32_PAT));
5862         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
5863                vmcs_read64(GUEST_IA32_DEBUGCTL),
5864                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5865         if (cpu_has_load_perf_global_ctrl() &&
5866             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5867                 pr_err("PerfGlobCtl = 0x%016llx\n",
5868                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5869         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5870                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5871         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
5872                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5873                vmcs_read32(GUEST_ACTIVITY_STATE));
5874         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5875                 pr_err("InterruptStatus = %04x\n",
5876                        vmcs_read16(GUEST_INTR_STATUS));
5877
5878         pr_err("*** Host State ***\n");
5879         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
5880                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5881         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5882                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5883                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5884                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5885                vmcs_read16(HOST_TR_SELECTOR));
5886         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5887                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5888                vmcs_readl(HOST_TR_BASE));
5889         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5890                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5891         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5892                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5893                vmcs_readl(HOST_CR4));
5894         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5895                vmcs_readl(HOST_IA32_SYSENTER_ESP),
5896                vmcs_read32(HOST_IA32_SYSENTER_CS),
5897                vmcs_readl(HOST_IA32_SYSENTER_EIP));
5898         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5899                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
5900                        vmcs_read64(HOST_IA32_EFER),
5901                        vmcs_read64(HOST_IA32_PAT));
5902         if (cpu_has_load_perf_global_ctrl() &&
5903             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5904                 pr_err("PerfGlobCtl = 0x%016llx\n",
5905                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5906
5907         pr_err("*** Control State ***\n");
5908         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5909                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5910         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5911         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5912                vmcs_read32(EXCEPTION_BITMAP),
5913                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5914                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5915         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5916                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5917                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5918                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5919         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5920                vmcs_read32(VM_EXIT_INTR_INFO),
5921                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5922                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5923         pr_err("        reason=%08x qualification=%016lx\n",
5924                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5925         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5926                vmcs_read32(IDT_VECTORING_INFO_FIELD),
5927                vmcs_read32(IDT_VECTORING_ERROR_CODE));
5928         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5929         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5930                 pr_err("TSC Multiplier = 0x%016llx\n",
5931                        vmcs_read64(TSC_MULTIPLIER));
5932         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5933                 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5934                         u16 status = vmcs_read16(GUEST_INTR_STATUS);
5935                         pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5936                 }
5937                 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5938                 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5939                         pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5940                 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5941         }
5942         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5943                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5944         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5945                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5946         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5947                 pr_err("PLE Gap=%08x Window=%08x\n",
5948                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5949         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5950                 pr_err("Virtual processor ID = 0x%04x\n",
5951                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
5952 }
5953
5954 /*
5955  * The guest has exited.  See if we can fix it or if we need userspace
5956  * assistance.
5957  */
5958 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5959 {
5960         struct vcpu_vmx *vmx = to_vmx(vcpu);
5961         u32 exit_reason = vmx->exit_reason;
5962         u32 vectoring_info = vmx->idt_vectoring_info;
5963
5964         /*
5965          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5966          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5967          * querying dirty_bitmap, we only need to kick all vcpus out of guest
5968          * mode as if vcpus is in root mode, the PML buffer must has been
5969          * flushed already.
5970          */
5971         if (enable_pml)
5972                 vmx_flush_pml_buffer(vcpu);
5973
5974         /*
5975          * We should never reach this point with a pending nested VM-Enter, and
5976          * more specifically emulation of L2 due to invalid guest state (see
5977          * below) should never happen as that means we incorrectly allowed a
5978          * nested VM-Enter with an invalid vmcs12.
5979          */
5980         WARN_ON_ONCE(vmx->nested.nested_run_pending);
5981
5982         /* If guest state is invalid, start emulating */
5983         if (vmx->emulation_required)
5984                 return handle_invalid_guest_state(vcpu);
5985
5986         if (is_guest_mode(vcpu)) {
5987                 /*
5988                  * The host physical addresses of some pages of guest memory
5989                  * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
5990                  * Page). The CPU may write to these pages via their host
5991                  * physical address while L2 is running, bypassing any
5992                  * address-translation-based dirty tracking (e.g. EPT write
5993                  * protection).
5994                  *
5995                  * Mark them dirty on every exit from L2 to prevent them from
5996                  * getting out of sync with dirty tracking.
5997                  */
5998                 nested_mark_vmcs12_pages_dirty(vcpu);
5999
6000                 if (nested_vmx_reflect_vmexit(vcpu))
6001                         return 1;
6002         }
6003
6004         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6005                 dump_vmcs();
6006                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6007                 vcpu->run->fail_entry.hardware_entry_failure_reason
6008                         = exit_reason;
6009                 return 0;
6010         }
6011
6012         if (unlikely(vmx->fail)) {
6013                 dump_vmcs();
6014                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6015                 vcpu->run->fail_entry.hardware_entry_failure_reason
6016                         = vmcs_read32(VM_INSTRUCTION_ERROR);
6017                 return 0;
6018         }
6019
6020         /*
6021          * Note:
6022          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6023          * delivery event since it indicates guest is accessing MMIO.
6024          * The vm-exit can be triggered again after return to guest that
6025          * will cause infinite loop.
6026          */
6027         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6028                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
6029                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
6030                         exit_reason != EXIT_REASON_PML_FULL &&
6031                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
6032                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6033                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6034                 vcpu->run->internal.ndata = 3;
6035                 vcpu->run->internal.data[0] = vectoring_info;
6036                 vcpu->run->internal.data[1] = exit_reason;
6037                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6038                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
6039                         vcpu->run->internal.ndata++;
6040                         vcpu->run->internal.data[3] =
6041                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6042                 }
6043                 return 0;
6044         }
6045
6046         if (unlikely(!enable_vnmi &&
6047                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
6048                 if (!vmx_interrupt_blocked(vcpu)) {
6049                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6050                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6051                            vcpu->arch.nmi_pending) {
6052                         /*
6053                          * This CPU don't support us in finding the end of an
6054                          * NMI-blocked window if the guest runs with IRQs
6055                          * disabled. So we pull the trigger after 1 s of
6056                          * futile waiting, but inform the user about this.
6057                          */
6058                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6059                                "state on VCPU %d after 1 s timeout\n",
6060                                __func__, vcpu->vcpu_id);
6061                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6062                 }
6063         }
6064
6065         if (exit_fastpath != EXIT_FASTPATH_NONE)
6066                 return 1;
6067
6068         if (exit_reason >= kvm_vmx_max_exit_handlers)
6069                 goto unexpected_vmexit;
6070 #ifdef CONFIG_RETPOLINE
6071         if (exit_reason == EXIT_REASON_MSR_WRITE)
6072                 return kvm_emulate_wrmsr(vcpu);
6073         else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
6074                 return handle_preemption_timer(vcpu);
6075         else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
6076                 return handle_interrupt_window(vcpu);
6077         else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6078                 return handle_external_interrupt(vcpu);
6079         else if (exit_reason == EXIT_REASON_HLT)
6080                 return kvm_emulate_halt(vcpu);
6081         else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
6082                 return handle_ept_misconfig(vcpu);
6083 #endif
6084
6085         exit_reason = array_index_nospec(exit_reason,
6086                                          kvm_vmx_max_exit_handlers);
6087         if (!kvm_vmx_exit_handlers[exit_reason])
6088                 goto unexpected_vmexit;
6089
6090         return kvm_vmx_exit_handlers[exit_reason](vcpu);
6091
6092 unexpected_vmexit:
6093         vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n", exit_reason);
6094         dump_vmcs();
6095         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6096         vcpu->run->internal.suberror =
6097                         KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6098         vcpu->run->internal.ndata = 1;
6099         vcpu->run->internal.data[0] = exit_reason;
6100         return 0;
6101 }
6102
6103 /*
6104  * Software based L1D cache flush which is used when microcode providing
6105  * the cache control MSR is not loaded.
6106  *
6107  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6108  * flush it is required to read in 64 KiB because the replacement algorithm
6109  * is not exactly LRU. This could be sized at runtime via topology
6110  * information but as all relevant affected CPUs have 32KiB L1D cache size
6111  * there is no point in doing so.
6112  */
6113 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6114 {
6115         int size = PAGE_SIZE << L1D_CACHE_ORDER;
6116
6117         /*
6118          * This code is only executed when the the flush mode is 'cond' or
6119          * 'always'
6120          */
6121         if (static_branch_likely(&vmx_l1d_flush_cond)) {
6122                 bool flush_l1d;
6123
6124                 /*
6125                  * Clear the per-vcpu flush bit, it gets set again
6126                  * either from vcpu_run() or from one of the unsafe
6127                  * VMEXIT handlers.
6128                  */
6129                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6130                 vcpu->arch.l1tf_flush_l1d = false;
6131
6132                 /*
6133                  * Clear the per-cpu flush bit, it gets set again from
6134                  * the interrupt handlers.
6135                  */
6136                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6137                 kvm_clear_cpu_l1tf_flush_l1d();
6138
6139                 if (!flush_l1d)
6140                         return;
6141         }
6142
6143         vcpu->stat.l1d_flush++;
6144
6145         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6146                 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6147                 return;
6148         }
6149
6150         asm volatile(
6151                 /* First ensure the pages are in the TLB */
6152                 "xorl   %%eax, %%eax\n"
6153                 ".Lpopulate_tlb:\n\t"
6154                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6155                 "addl   $4096, %%eax\n\t"
6156                 "cmpl   %%eax, %[size]\n\t"
6157                 "jne    .Lpopulate_tlb\n\t"
6158                 "xorl   %%eax, %%eax\n\t"
6159                 "cpuid\n\t"
6160                 /* Now fill the cache */
6161                 "xorl   %%eax, %%eax\n"
6162                 ".Lfill_cache:\n"
6163                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6164                 "addl   $64, %%eax\n\t"
6165                 "cmpl   %%eax, %[size]\n\t"
6166                 "jne    .Lfill_cache\n\t"
6167                 "lfence\n"
6168                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6169                     [size] "r" (size)
6170                 : "eax", "ebx", "ecx", "edx");
6171 }
6172
6173 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6174 {
6175         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6176         int tpr_threshold;
6177
6178         if (is_guest_mode(vcpu) &&
6179                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6180                 return;
6181
6182         tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6183         if (is_guest_mode(vcpu))
6184                 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6185         else
6186                 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6187 }
6188
6189 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6190 {
6191         struct vcpu_vmx *vmx = to_vmx(vcpu);
6192         u32 sec_exec_control;
6193
6194         if (!lapic_in_kernel(vcpu))
6195                 return;
6196
6197         if (!flexpriority_enabled &&
6198             !cpu_has_vmx_virtualize_x2apic_mode())
6199                 return;
6200
6201         /* Postpone execution until vmcs01 is the current VMCS. */
6202         if (is_guest_mode(vcpu)) {
6203                 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6204                 return;
6205         }
6206
6207         sec_exec_control = secondary_exec_controls_get(vmx);
6208         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6209                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6210
6211         switch (kvm_get_apic_mode(vcpu)) {
6212         case LAPIC_MODE_INVALID:
6213                 WARN_ONCE(true, "Invalid local APIC state");
6214         case LAPIC_MODE_DISABLED:
6215                 break;
6216         case LAPIC_MODE_XAPIC:
6217                 if (flexpriority_enabled) {
6218                         sec_exec_control |=
6219                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6220                         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6221
6222                         /*
6223                          * Flush the TLB, reloading the APIC access page will
6224                          * only do so if its physical address has changed, but
6225                          * the guest may have inserted a non-APIC mapping into
6226                          * the TLB while the APIC access page was disabled.
6227                          */
6228                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6229                 }
6230                 break;
6231         case LAPIC_MODE_X2APIC:
6232                 if (cpu_has_vmx_virtualize_x2apic_mode())
6233                         sec_exec_control |=
6234                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6235                 break;
6236         }
6237         secondary_exec_controls_set(vmx, sec_exec_control);
6238
6239         vmx_update_msr_bitmap(vcpu);
6240 }
6241
6242 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6243 {
6244         struct page *page;
6245
6246         /* Defer reload until vmcs01 is the current VMCS. */
6247         if (is_guest_mode(vcpu)) {
6248                 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6249                 return;
6250         }
6251
6252         if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6253             SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6254                 return;
6255
6256         page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6257         if (is_error_page(page))
6258                 return;
6259
6260         vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6261         vmx_flush_tlb_current(vcpu);
6262
6263         /*
6264          * Do not pin apic access page in memory, the MMU notifier
6265          * will call us again if it is migrated or swapped out.
6266          */
6267         put_page(page);
6268 }
6269
6270 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6271 {
6272         u16 status;
6273         u8 old;
6274
6275         if (max_isr == -1)
6276                 max_isr = 0;
6277
6278         status = vmcs_read16(GUEST_INTR_STATUS);
6279         old = status >> 8;
6280         if (max_isr != old) {
6281                 status &= 0xff;
6282                 status |= max_isr << 8;
6283                 vmcs_write16(GUEST_INTR_STATUS, status);
6284         }
6285 }
6286
6287 static void vmx_set_rvi(int vector)
6288 {
6289         u16 status;
6290         u8 old;
6291
6292         if (vector == -1)
6293                 vector = 0;
6294
6295         status = vmcs_read16(GUEST_INTR_STATUS);
6296         old = (u8)status & 0xff;
6297         if ((u8)vector != old) {
6298                 status &= ~0xff;
6299                 status |= (u8)vector;
6300                 vmcs_write16(GUEST_INTR_STATUS, status);
6301         }
6302 }
6303
6304 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6305 {
6306         /*
6307          * When running L2, updating RVI is only relevant when
6308          * vmcs12 virtual-interrupt-delivery enabled.
6309          * However, it can be enabled only when L1 also
6310          * intercepts external-interrupts and in that case
6311          * we should not update vmcs02 RVI but instead intercept
6312          * interrupt. Therefore, do nothing when running L2.
6313          */
6314         if (!is_guest_mode(vcpu))
6315                 vmx_set_rvi(max_irr);
6316 }
6317
6318 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6319 {
6320         struct vcpu_vmx *vmx = to_vmx(vcpu);
6321         int max_irr;
6322         bool max_irr_updated;
6323
6324         WARN_ON(!vcpu->arch.apicv_active);
6325         if (pi_test_on(&vmx->pi_desc)) {
6326                 pi_clear_on(&vmx->pi_desc);
6327                 /*
6328                  * IOMMU can write to PID.ON, so the barrier matters even on UP.
6329                  * But on x86 this is just a compiler barrier anyway.
6330                  */
6331                 smp_mb__after_atomic();
6332                 max_irr_updated =
6333                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6334
6335                 /*
6336                  * If we are running L2 and L1 has a new pending interrupt
6337                  * which can be injected, we should re-evaluate
6338                  * what should be done with this new L1 interrupt.
6339                  * If L1 intercepts external-interrupts, we should
6340                  * exit from L2 to L1. Otherwise, interrupt should be
6341                  * delivered directly to L2.
6342                  */
6343                 if (is_guest_mode(vcpu) && max_irr_updated) {
6344                         if (nested_exit_on_intr(vcpu))
6345                                 kvm_vcpu_exiting_guest_mode(vcpu);
6346                         else
6347                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6348                 }
6349         } else {
6350                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6351         }
6352         vmx_hwapic_irr_update(vcpu, max_irr);
6353         return max_irr;
6354 }
6355
6356 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6357 {
6358         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6359
6360         return pi_test_on(pi_desc) ||
6361                 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6362 }
6363
6364 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6365 {
6366         if (!kvm_vcpu_apicv_active(vcpu))
6367                 return;
6368
6369         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6370         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6371         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6372         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6373 }
6374
6375 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6376 {
6377         struct vcpu_vmx *vmx = to_vmx(vcpu);
6378
6379         pi_clear_on(&vmx->pi_desc);
6380         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6381 }
6382
6383 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6384 {
6385         u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6386
6387         /* if exit due to PF check for async PF */
6388         if (is_page_fault(intr_info)) {
6389                 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6390         /* Handle machine checks before interrupts are enabled */
6391         } else if (is_machine_check(intr_info)) {
6392                 kvm_machine_check();
6393         /* We need to handle NMIs before interrupts are enabled */
6394         } else if (is_nmi(intr_info)) {
6395                 kvm_before_interrupt(&vmx->vcpu);
6396                 asm("int $2");
6397                 kvm_after_interrupt(&vmx->vcpu);
6398         }
6399 }
6400
6401 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6402 {
6403         unsigned int vector;
6404         unsigned long entry;
6405 #ifdef CONFIG_X86_64
6406         unsigned long tmp;
6407 #endif
6408         gate_desc *desc;
6409         u32 intr_info = vmx_get_intr_info(vcpu);
6410
6411         if (WARN_ONCE(!is_external_intr(intr_info),
6412             "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6413                 return;
6414
6415         vector = intr_info & INTR_INFO_VECTOR_MASK;
6416         desc = (gate_desc *)host_idt_base + vector;
6417         entry = gate_offset(desc);
6418
6419         kvm_before_interrupt(vcpu);
6420
6421         asm volatile(
6422 #ifdef CONFIG_X86_64
6423                 "mov %%rsp, %[sp]\n\t"
6424                 "and $-16, %%rsp\n\t"
6425                 "push %[ss]\n\t"
6426                 "push %[sp]\n\t"
6427 #endif
6428                 "pushf\n\t"
6429                 "push %[cs]\n\t"
6430                 CALL_NOSPEC
6431                 :
6432 #ifdef CONFIG_X86_64
6433                 [sp]"=&r"(tmp),
6434 #endif
6435                 ASM_CALL_CONSTRAINT
6436                 :
6437                 [thunk_target]"r"(entry),
6438 #ifdef CONFIG_X86_64
6439                 [ss]"i"(__KERNEL_DS),
6440 #endif
6441                 [cs]"i"(__KERNEL_CS)
6442         );
6443
6444         kvm_after_interrupt(vcpu);
6445 }
6446 STACK_FRAME_NON_STANDARD(handle_external_interrupt_irqoff);
6447
6448 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6449 {
6450         struct vcpu_vmx *vmx = to_vmx(vcpu);
6451
6452         if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6453                 handle_external_interrupt_irqoff(vcpu);
6454         else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6455                 handle_exception_nmi_irqoff(vmx);
6456 }
6457
6458 static bool vmx_has_emulated_msr(u32 index)
6459 {
6460         switch (index) {
6461         case MSR_IA32_SMBASE:
6462                 /*
6463                  * We cannot do SMM unless we can run the guest in big
6464                  * real mode.
6465                  */
6466                 return enable_unrestricted_guest || emulate_invalid_guest_state;
6467         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6468                 return nested;
6469         case MSR_AMD64_VIRT_SPEC_CTRL:
6470                 /* This is AMD only.  */
6471                 return false;
6472         default:
6473                 return true;
6474         }
6475 }
6476
6477 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6478 {
6479         u32 exit_intr_info;
6480         bool unblock_nmi;
6481         u8 vector;
6482         bool idtv_info_valid;
6483
6484         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6485
6486         if (enable_vnmi) {
6487                 if (vmx->loaded_vmcs->nmi_known_unmasked)
6488                         return;
6489
6490                 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6491                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6492                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6493                 /*
6494                  * SDM 3: 27.7.1.2 (September 2008)
6495                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
6496                  * a guest IRET fault.
6497                  * SDM 3: 23.2.2 (September 2008)
6498                  * Bit 12 is undefined in any of the following cases:
6499                  *  If the VM exit sets the valid bit in the IDT-vectoring
6500                  *   information field.
6501                  *  If the VM exit is due to a double fault.
6502                  */
6503                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6504                     vector != DF_VECTOR && !idtv_info_valid)
6505                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6506                                       GUEST_INTR_STATE_NMI);
6507                 else
6508                         vmx->loaded_vmcs->nmi_known_unmasked =
6509                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6510                                   & GUEST_INTR_STATE_NMI);
6511         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6512                 vmx->loaded_vmcs->vnmi_blocked_time +=
6513                         ktime_to_ns(ktime_sub(ktime_get(),
6514                                               vmx->loaded_vmcs->entry_time));
6515 }
6516
6517 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6518                                       u32 idt_vectoring_info,
6519                                       int instr_len_field,
6520                                       int error_code_field)
6521 {
6522         u8 vector;
6523         int type;
6524         bool idtv_info_valid;
6525
6526         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6527
6528         vcpu->arch.nmi_injected = false;
6529         kvm_clear_exception_queue(vcpu);
6530         kvm_clear_interrupt_queue(vcpu);
6531
6532         if (!idtv_info_valid)
6533                 return;
6534
6535         kvm_make_request(KVM_REQ_EVENT, vcpu);
6536
6537         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6538         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6539
6540         switch (type) {
6541         case INTR_TYPE_NMI_INTR:
6542                 vcpu->arch.nmi_injected = true;
6543                 /*
6544                  * SDM 3: 27.7.1.2 (September 2008)
6545                  * Clear bit "block by NMI" before VM entry if a NMI
6546                  * delivery faulted.
6547                  */
6548                 vmx_set_nmi_mask(vcpu, false);
6549                 break;
6550         case INTR_TYPE_SOFT_EXCEPTION:
6551                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6552                 /* fall through */
6553         case INTR_TYPE_HARD_EXCEPTION:
6554                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6555                         u32 err = vmcs_read32(error_code_field);
6556                         kvm_requeue_exception_e(vcpu, vector, err);
6557                 } else
6558                         kvm_requeue_exception(vcpu, vector);
6559                 break;
6560         case INTR_TYPE_SOFT_INTR:
6561                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6562                 /* fall through */
6563         case INTR_TYPE_EXT_INTR:
6564                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6565                 break;
6566         default:
6567                 break;
6568         }
6569 }
6570
6571 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6572 {
6573         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6574                                   VM_EXIT_INSTRUCTION_LEN,
6575                                   IDT_VECTORING_ERROR_CODE);
6576 }
6577
6578 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6579 {
6580         __vmx_complete_interrupts(vcpu,
6581                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6582                                   VM_ENTRY_INSTRUCTION_LEN,
6583                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
6584
6585         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6586 }
6587
6588 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6589 {
6590         int i, nr_msrs;
6591         struct perf_guest_switch_msr *msrs;
6592
6593         msrs = perf_guest_get_msrs(&nr_msrs);
6594
6595         if (!msrs)
6596                 return;
6597
6598         for (i = 0; i < nr_msrs; i++)
6599                 if (msrs[i].host == msrs[i].guest)
6600                         clear_atomic_switch_msr(vmx, msrs[i].msr);
6601                 else
6602                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6603                                         msrs[i].host, false);
6604 }
6605
6606 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6607 {
6608         struct vcpu_vmx *vmx = to_vmx(vcpu);
6609         u64 tscl;
6610         u32 delta_tsc;
6611
6612         if (vmx->req_immediate_exit) {
6613                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6614                 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6615         } else if (vmx->hv_deadline_tsc != -1) {
6616                 tscl = rdtsc();
6617                 if (vmx->hv_deadline_tsc > tscl)
6618                         /* set_hv_timer ensures the delta fits in 32-bits */
6619                         delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6620                                 cpu_preemption_timer_multi);
6621                 else
6622                         delta_tsc = 0;
6623
6624                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6625                 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6626         } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6627                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6628                 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6629         }
6630 }
6631
6632 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6633 {
6634         if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6635                 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6636                 vmcs_writel(HOST_RSP, host_rsp);
6637         }
6638 }
6639
6640 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6641 {
6642         switch (to_vmx(vcpu)->exit_reason) {
6643         case EXIT_REASON_MSR_WRITE:
6644                 return handle_fastpath_set_msr_irqoff(vcpu);
6645         case EXIT_REASON_PREEMPTION_TIMER:
6646                 return handle_fastpath_preemption_timer(vcpu);
6647         default:
6648                 return EXIT_FASTPATH_NONE;
6649         }
6650 }
6651
6652 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6653
6654 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6655 {
6656         fastpath_t exit_fastpath;
6657         struct vcpu_vmx *vmx = to_vmx(vcpu);
6658         unsigned long cr3, cr4;
6659
6660 reenter_guest:
6661         /* Record the guest's net vcpu time for enforced NMI injections. */
6662         if (unlikely(!enable_vnmi &&
6663                      vmx->loaded_vmcs->soft_vnmi_blocked))
6664                 vmx->loaded_vmcs->entry_time = ktime_get();
6665
6666         /* Don't enter VMX if guest state is invalid, let the exit handler
6667            start emulation until we arrive back to a valid state */
6668         if (vmx->emulation_required)
6669                 return EXIT_FASTPATH_NONE;
6670
6671         if (vmx->ple_window_dirty) {
6672                 vmx->ple_window_dirty = false;
6673                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6674         }
6675
6676         /*
6677          * We did this in prepare_switch_to_guest, because it needs to
6678          * be within srcu_read_lock.
6679          */
6680         WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6681
6682         if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6683                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6684         if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6685                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6686
6687         cr3 = __get_current_cr3_fast();
6688         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6689                 vmcs_writel(HOST_CR3, cr3);
6690                 vmx->loaded_vmcs->host_state.cr3 = cr3;
6691         }
6692
6693         cr4 = cr4_read_shadow();
6694         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6695                 vmcs_writel(HOST_CR4, cr4);
6696                 vmx->loaded_vmcs->host_state.cr4 = cr4;
6697         }
6698
6699         /* When single-stepping over STI and MOV SS, we must clear the
6700          * corresponding interruptibility bits in the guest state. Otherwise
6701          * vmentry fails as it then expects bit 14 (BS) in pending debug
6702          * exceptions being set, but that's not correct for the guest debugging
6703          * case. */
6704         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6705                 vmx_set_interrupt_shadow(vcpu, 0);
6706
6707         kvm_load_guest_xsave_state(vcpu);
6708
6709         pt_guest_enter(vmx);
6710
6711         atomic_switch_perf_msrs(vmx);
6712
6713         if (enable_preemption_timer)
6714                 vmx_update_hv_timer(vcpu);
6715
6716         if (lapic_in_kernel(vcpu) &&
6717                 vcpu->arch.apic->lapic_timer.timer_advance_ns)
6718                 kvm_wait_lapic_expire(vcpu);
6719
6720         /*
6721          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6722          * it's non-zero. Since vmentry is serialising on affected CPUs, there
6723          * is no need to worry about the conditional branch over the wrmsr
6724          * being speculatively taken.
6725          */
6726         x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6727
6728         /* L1D Flush includes CPU buffer clear to mitigate MDS */
6729         if (static_branch_unlikely(&vmx_l1d_should_flush))
6730                 vmx_l1d_flush(vcpu);
6731         else if (static_branch_unlikely(&mds_user_clear))
6732                 mds_clear_cpu_buffers();
6733
6734         if (vcpu->arch.cr2 != read_cr2())
6735                 write_cr2(vcpu->arch.cr2);
6736
6737         vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6738                                    vmx->loaded_vmcs->launched);
6739
6740         vcpu->arch.cr2 = read_cr2();
6741
6742         /*
6743          * We do not use IBRS in the kernel. If this vCPU has used the
6744          * SPEC_CTRL MSR it may have left it on; save the value and
6745          * turn it off. This is much more efficient than blindly adding
6746          * it to the atomic save/restore list. Especially as the former
6747          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6748          *
6749          * For non-nested case:
6750          * If the L01 MSR bitmap does not intercept the MSR, then we need to
6751          * save it.
6752          *
6753          * For nested case:
6754          * If the L02 MSR bitmap does not intercept the MSR, then we need to
6755          * save it.
6756          */
6757         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6758                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6759
6760         x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6761
6762         /* All fields are clean at this point */
6763         if (static_branch_unlikely(&enable_evmcs))
6764                 current_evmcs->hv_clean_fields |=
6765                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6766
6767         if (static_branch_unlikely(&enable_evmcs))
6768                 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6769
6770         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6771         if (vmx->host_debugctlmsr)
6772                 update_debugctlmsr(vmx->host_debugctlmsr);
6773
6774 #ifndef CONFIG_X86_64
6775         /*
6776          * The sysexit path does not restore ds/es, so we must set them to
6777          * a reasonable value ourselves.
6778          *
6779          * We can't defer this to vmx_prepare_switch_to_host() since that
6780          * function may be executed in interrupt context, which saves and
6781          * restore segments around it, nullifying its effect.
6782          */
6783         loadsegment(ds, __USER_DS);
6784         loadsegment(es, __USER_DS);
6785 #endif
6786
6787         vmx_register_cache_reset(vcpu);
6788
6789         pt_guest_exit(vmx);
6790
6791         kvm_load_host_xsave_state(vcpu);
6792
6793         vmx->nested.nested_run_pending = 0;
6794         vmx->idt_vectoring_info = 0;
6795
6796         if (unlikely(vmx->fail)) {
6797                 vmx->exit_reason = 0xdead;
6798                 return EXIT_FASTPATH_NONE;
6799         }
6800
6801         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6802         if (unlikely((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY))
6803                 kvm_machine_check();
6804
6805         trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6806
6807         if (unlikely(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6808                 return EXIT_FASTPATH_NONE;
6809
6810         vmx->loaded_vmcs->launched = 1;
6811         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6812
6813         vmx_recover_nmi_blocking(vmx);
6814         vmx_complete_interrupts(vmx);
6815
6816         if (is_guest_mode(vcpu))
6817                 return EXIT_FASTPATH_NONE;
6818
6819         exit_fastpath = vmx_exit_handlers_fastpath(vcpu);
6820         if (exit_fastpath == EXIT_FASTPATH_REENTER_GUEST) {
6821                 if (!kvm_vcpu_exit_request(vcpu)) {
6822                         /*
6823                          * FIXME: this goto should be a loop in vcpu_enter_guest,
6824                          * but it would incur the cost of a retpoline for now.
6825                          * Revisit once static calls are available.
6826                          */
6827                         if (vcpu->arch.apicv_active)
6828                                 vmx_sync_pir_to_irr(vcpu);
6829                         goto reenter_guest;
6830                 }
6831                 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
6832         }
6833
6834         return exit_fastpath;
6835 }
6836
6837 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6838 {
6839         struct vcpu_vmx *vmx = to_vmx(vcpu);
6840
6841         if (enable_pml)
6842                 vmx_destroy_pml_buffer(vmx);
6843         free_vpid(vmx->vpid);
6844         nested_vmx_free_vcpu(vcpu);
6845         free_loaded_vmcs(vmx->loaded_vmcs);
6846 }
6847
6848 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6849 {
6850         struct vcpu_vmx *vmx;
6851         unsigned long *msr_bitmap;
6852         int i, cpu, err;
6853
6854         BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6855         vmx = to_vmx(vcpu);
6856
6857         err = -ENOMEM;
6858
6859         vmx->vpid = allocate_vpid();
6860
6861         /*
6862          * If PML is turned on, failure on enabling PML just results in failure
6863          * of creating the vcpu, therefore we can simplify PML logic (by
6864          * avoiding dealing with cases, such as enabling PML partially on vcpus
6865          * for the guest), etc.
6866          */
6867         if (enable_pml) {
6868                 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6869                 if (!vmx->pml_pg)
6870                         goto free_vpid;
6871         }
6872
6873         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) != NR_SHARED_MSRS);
6874
6875         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6876                 u32 index = vmx_msr_index[i];
6877                 u32 data_low, data_high;
6878                 int j = vmx->nmsrs;
6879
6880                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6881                         continue;
6882                 if (wrmsr_safe(index, data_low, data_high) < 0)
6883                         continue;
6884
6885                 vmx->guest_msrs[j].index = i;
6886                 vmx->guest_msrs[j].data = 0;
6887                 switch (index) {
6888                 case MSR_IA32_TSX_CTRL:
6889                         /*
6890                          * No need to pass TSX_CTRL_CPUID_CLEAR through, so
6891                          * let's avoid changing CPUID bits under the host
6892                          * kernel's feet.
6893                          */
6894                         vmx->guest_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6895                         break;
6896                 default:
6897                         vmx->guest_msrs[j].mask = -1ull;
6898                         break;
6899                 }
6900                 ++vmx->nmsrs;
6901         }
6902
6903         err = alloc_loaded_vmcs(&vmx->vmcs01);
6904         if (err < 0)
6905                 goto free_pml;
6906
6907         msr_bitmap = vmx->vmcs01.msr_bitmap;
6908         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6909         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6910         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6911         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6912         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6913         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6914         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6915         if (kvm_cstate_in_guest(vcpu->kvm)) {
6916                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6917                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6918                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6919                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
6920         }
6921         vmx->msr_bitmap_mode = 0;
6922
6923         vmx->loaded_vmcs = &vmx->vmcs01;
6924         cpu = get_cpu();
6925         vmx_vcpu_load(vcpu, cpu);
6926         vcpu->cpu = cpu;
6927         init_vmcs(vmx);
6928         vmx_vcpu_put(vcpu);
6929         put_cpu();
6930         if (cpu_need_virtualize_apic_accesses(vcpu)) {
6931                 err = alloc_apic_access_page(vcpu->kvm);
6932                 if (err)
6933                         goto free_vmcs;
6934         }
6935
6936         if (enable_ept && !enable_unrestricted_guest) {
6937                 err = init_rmode_identity_map(vcpu->kvm);
6938                 if (err)
6939                         goto free_vmcs;
6940         }
6941
6942         if (nested)
6943                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
6944                                            vmx_capability.ept);
6945         else
6946                 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
6947
6948         vmx->nested.posted_intr_nv = -1;
6949         vmx->nested.current_vmptr = -1ull;
6950
6951         vcpu->arch.microcode_version = 0x100000000ULL;
6952         vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
6953
6954         /*
6955          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
6956          * or POSTED_INTR_WAKEUP_VECTOR.
6957          */
6958         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
6959         vmx->pi_desc.sn = 1;
6960
6961         vmx->ept_pointer = INVALID_PAGE;
6962
6963         return 0;
6964
6965 free_vmcs:
6966         free_loaded_vmcs(vmx->loaded_vmcs);
6967 free_pml:
6968         vmx_destroy_pml_buffer(vmx);
6969 free_vpid:
6970         free_vpid(vmx->vpid);
6971         return err;
6972 }
6973
6974 #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"
6975 #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"
6976
6977 static int vmx_vm_init(struct kvm *kvm)
6978 {
6979         spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
6980
6981         if (!ple_gap)
6982                 kvm->arch.pause_in_guest = true;
6983
6984         if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
6985                 switch (l1tf_mitigation) {
6986                 case L1TF_MITIGATION_OFF:
6987                 case L1TF_MITIGATION_FLUSH_NOWARN:
6988                         /* 'I explicitly don't care' is set */
6989                         break;
6990                 case L1TF_MITIGATION_FLUSH:
6991                 case L1TF_MITIGATION_FLUSH_NOSMT:
6992                 case L1TF_MITIGATION_FULL:
6993                         /*
6994                          * Warn upon starting the first VM in a potentially
6995                          * insecure environment.
6996                          */
6997                         if (sched_smt_active())
6998                                 pr_warn_once(L1TF_MSG_SMT);
6999                         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7000                                 pr_warn_once(L1TF_MSG_L1D);
7001                         break;
7002                 case L1TF_MITIGATION_FULL_FORCE:
7003                         /* Flush is enforced */
7004                         break;
7005                 }
7006         }
7007         kvm_apicv_init(kvm, enable_apicv);
7008         return 0;
7009 }
7010
7011 static int __init vmx_check_processor_compat(void)
7012 {
7013         struct vmcs_config vmcs_conf;
7014         struct vmx_capability vmx_cap;
7015
7016         if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7017             !this_cpu_has(X86_FEATURE_VMX)) {
7018                 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7019                 return -EIO;
7020         }
7021
7022         if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7023                 return -EIO;
7024         if (nested)
7025                 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7026         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7027                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7028                                 smp_processor_id());
7029                 return -EIO;
7030         }
7031         return 0;
7032 }
7033
7034 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7035 {
7036         u8 cache;
7037         u64 ipat = 0;
7038
7039         /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7040          * memory aliases with conflicting memory types and sometimes MCEs.
7041          * We have to be careful as to what are honored and when.
7042          *
7043          * For MMIO, guest CD/MTRR are ignored.  The EPT memory type is set to
7044          * UC.  The effective memory type is UC or WC depending on guest PAT.
7045          * This was historically the source of MCEs and we want to be
7046          * conservative.
7047          *
7048          * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7049          * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored.  The
7050          * EPT memory type is set to WB.  The effective memory type is forced
7051          * WB.
7052          *
7053          * Otherwise, we trust guest.  Guest CD/MTRR/PAT are all honored.  The
7054          * EPT memory type is used to emulate guest CD/MTRR.
7055          */
7056
7057         if (is_mmio) {
7058                 cache = MTRR_TYPE_UNCACHABLE;
7059                 goto exit;
7060         }
7061
7062         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7063                 ipat = VMX_EPT_IPAT_BIT;
7064                 cache = MTRR_TYPE_WRBACK;
7065                 goto exit;
7066         }
7067
7068         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7069                 ipat = VMX_EPT_IPAT_BIT;
7070                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7071                         cache = MTRR_TYPE_WRBACK;
7072                 else
7073                         cache = MTRR_TYPE_UNCACHABLE;
7074                 goto exit;
7075         }
7076
7077         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7078
7079 exit:
7080         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7081 }
7082
7083 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7084 {
7085         /*
7086          * These bits in the secondary execution controls field
7087          * are dynamic, the others are mostly based on the hypervisor
7088          * architecture and the guest's CPUID.  Do not touch the
7089          * dynamic bits.
7090          */
7091         u32 mask =
7092                 SECONDARY_EXEC_SHADOW_VMCS |
7093                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7094                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7095                 SECONDARY_EXEC_DESC;
7096
7097         u32 new_ctl = vmx->secondary_exec_control;
7098         u32 cur_ctl = secondary_exec_controls_get(vmx);
7099
7100         secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7101 }
7102
7103 /*
7104  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7105  * (indicating "allowed-1") if they are supported in the guest's CPUID.
7106  */
7107 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7108 {
7109         struct vcpu_vmx *vmx = to_vmx(vcpu);
7110         struct kvm_cpuid_entry2 *entry;
7111
7112         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7113         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7114
7115 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
7116         if (entry && (entry->_reg & (_cpuid_mask)))                     \
7117                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
7118 } while (0)
7119
7120         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7121         cr4_fixed1_update(X86_CR4_VME,        edx, feature_bit(VME));
7122         cr4_fixed1_update(X86_CR4_PVI,        edx, feature_bit(VME));
7123         cr4_fixed1_update(X86_CR4_TSD,        edx, feature_bit(TSC));
7124         cr4_fixed1_update(X86_CR4_DE,         edx, feature_bit(DE));
7125         cr4_fixed1_update(X86_CR4_PSE,        edx, feature_bit(PSE));
7126         cr4_fixed1_update(X86_CR4_PAE,        edx, feature_bit(PAE));
7127         cr4_fixed1_update(X86_CR4_MCE,        edx, feature_bit(MCE));
7128         cr4_fixed1_update(X86_CR4_PGE,        edx, feature_bit(PGE));
7129         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, feature_bit(FXSR));
7130         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7131         cr4_fixed1_update(X86_CR4_VMXE,       ecx, feature_bit(VMX));
7132         cr4_fixed1_update(X86_CR4_SMXE,       ecx, feature_bit(SMX));
7133         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, feature_bit(PCID));
7134         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, feature_bit(XSAVE));
7135
7136         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7137         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, feature_bit(FSGSBASE));
7138         cr4_fixed1_update(X86_CR4_SMEP,       ebx, feature_bit(SMEP));
7139         cr4_fixed1_update(X86_CR4_SMAP,       ebx, feature_bit(SMAP));
7140         cr4_fixed1_update(X86_CR4_PKE,        ecx, feature_bit(PKU));
7141         cr4_fixed1_update(X86_CR4_UMIP,       ecx, feature_bit(UMIP));
7142         cr4_fixed1_update(X86_CR4_LA57,       ecx, feature_bit(LA57));
7143
7144 #undef cr4_fixed1_update
7145 }
7146
7147 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7148 {
7149         struct vcpu_vmx *vmx = to_vmx(vcpu);
7150
7151         if (kvm_mpx_supported()) {
7152                 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7153
7154                 if (mpx_enabled) {
7155                         vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7156                         vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7157                 } else {
7158                         vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7159                         vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7160                 }
7161         }
7162 }
7163
7164 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7165 {
7166         struct vcpu_vmx *vmx = to_vmx(vcpu);
7167         struct kvm_cpuid_entry2 *best = NULL;
7168         int i;
7169
7170         for (i = 0; i < PT_CPUID_LEAVES; i++) {
7171                 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7172                 if (!best)
7173                         return;
7174                 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7175                 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7176                 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7177                 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7178         }
7179
7180         /* Get the number of configurable Address Ranges for filtering */
7181         vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7182                                                 PT_CAP_num_address_ranges);
7183
7184         /* Initialize and clear the no dependency bits */
7185         vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7186                         RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7187
7188         /*
7189          * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7190          * will inject an #GP
7191          */
7192         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7193                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7194
7195         /*
7196          * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7197          * PSBFreq can be set
7198          */
7199         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7200                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7201                                 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7202
7203         /*
7204          * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7205          * MTCFreq can be set
7206          */
7207         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7208                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7209                                 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7210
7211         /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7212         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7213                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7214                                                         RTIT_CTL_PTW_EN);
7215
7216         /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7217         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7218                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7219
7220         /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7221         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7222                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7223
7224         /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7225         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7226                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7227
7228         /* unmask address range configure area */
7229         for (i = 0; i < vmx->pt_desc.addr_range; i++)
7230                 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7231 }
7232
7233 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
7234 {
7235         struct vcpu_vmx *vmx = to_vmx(vcpu);
7236
7237         /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7238         vcpu->arch.xsaves_enabled = false;
7239
7240         if (cpu_has_secondary_exec_ctrls()) {
7241                 vmx_compute_secondary_exec_control(vmx);
7242                 vmcs_set_secondary_exec_control(vmx);
7243         }
7244
7245         if (nested_vmx_allowed(vcpu))
7246                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7247                         FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7248                         FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7249         else
7250                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7251                         ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7252                           FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7253
7254         if (nested_vmx_allowed(vcpu)) {
7255                 nested_vmx_cr_fixed1_bits_update(vcpu);
7256                 nested_vmx_entry_exit_ctls_update(vcpu);
7257         }
7258
7259         if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7260                         guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7261                 update_intel_pt_cfg(vcpu);
7262
7263         if (boot_cpu_has(X86_FEATURE_RTM)) {
7264                 struct shared_msr_entry *msr;
7265                 msr = find_msr_entry(vmx, MSR_IA32_TSX_CTRL);
7266                 if (msr) {
7267                         bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7268                         vmx_set_guest_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7269                 }
7270         }
7271 }
7272
7273 static __init void vmx_set_cpu_caps(void)
7274 {
7275         kvm_set_cpu_caps();
7276
7277         /* CPUID 0x1 */
7278         if (nested)
7279                 kvm_cpu_cap_set(X86_FEATURE_VMX);
7280
7281         /* CPUID 0x7 */
7282         if (kvm_mpx_supported())
7283                 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7284         if (cpu_has_vmx_invpcid())
7285                 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7286         if (vmx_pt_mode_is_host_guest())
7287                 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7288
7289         if (vmx_umip_emulated())
7290                 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7291
7292         /* CPUID 0xD.1 */
7293         supported_xss = 0;
7294         if (!vmx_xsaves_supported())
7295                 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7296
7297         /* CPUID 0x80000001 */
7298         if (!cpu_has_vmx_rdtscp())
7299                 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7300
7301         if (vmx_waitpkg_supported())
7302                 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7303 }
7304
7305 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7306 {
7307         to_vmx(vcpu)->req_immediate_exit = true;
7308 }
7309
7310 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7311                                   struct x86_instruction_info *info)
7312 {
7313         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7314         unsigned short port;
7315         bool intercept;
7316         int size;
7317
7318         if (info->intercept == x86_intercept_in ||
7319             info->intercept == x86_intercept_ins) {
7320                 port = info->src_val;
7321                 size = info->dst_bytes;
7322         } else {
7323                 port = info->dst_val;
7324                 size = info->src_bytes;
7325         }
7326
7327         /*
7328          * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7329          * VM-exits depend on the 'unconditional IO exiting' VM-execution
7330          * control.
7331          *
7332          * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7333          */
7334         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7335                 intercept = nested_cpu_has(vmcs12,
7336                                            CPU_BASED_UNCOND_IO_EXITING);
7337         else
7338                 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7339
7340         /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED.  */
7341         return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7342 }
7343
7344 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7345                                struct x86_instruction_info *info,
7346                                enum x86_intercept_stage stage,
7347                                struct x86_exception *exception)
7348 {
7349         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7350
7351         switch (info->intercept) {
7352         /*
7353          * RDPID causes #UD if disabled through secondary execution controls.
7354          * Because it is marked as EmulateOnUD, we need to intercept it here.
7355          */
7356         case x86_intercept_rdtscp:
7357                 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7358                         exception->vector = UD_VECTOR;
7359                         exception->error_code_valid = false;
7360                         return X86EMUL_PROPAGATE_FAULT;
7361                 }
7362                 break;
7363
7364         case x86_intercept_in:
7365         case x86_intercept_ins:
7366         case x86_intercept_out:
7367         case x86_intercept_outs:
7368                 return vmx_check_intercept_io(vcpu, info);
7369
7370         case x86_intercept_lgdt:
7371         case x86_intercept_lidt:
7372         case x86_intercept_lldt:
7373         case x86_intercept_ltr:
7374         case x86_intercept_sgdt:
7375         case x86_intercept_sidt:
7376         case x86_intercept_sldt:
7377         case x86_intercept_str:
7378                 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7379                         return X86EMUL_CONTINUE;
7380
7381                 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED.  */
7382                 break;
7383
7384         /* TODO: check more intercepts... */
7385         default:
7386                 break;
7387         }
7388
7389         return X86EMUL_UNHANDLEABLE;
7390 }
7391
7392 #ifdef CONFIG_X86_64
7393 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7394 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7395                                   u64 divisor, u64 *result)
7396 {
7397         u64 low = a << shift, high = a >> (64 - shift);
7398
7399         /* To avoid the overflow on divq */
7400         if (high >= divisor)
7401                 return 1;
7402
7403         /* Low hold the result, high hold rem which is discarded */
7404         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7405             "rm" (divisor), "0" (low), "1" (high));
7406         *result = low;
7407
7408         return 0;
7409 }
7410
7411 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7412                             bool *expired)
7413 {
7414         struct vcpu_vmx *vmx;
7415         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7416         struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7417
7418         vmx = to_vmx(vcpu);
7419         tscl = rdtsc();
7420         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7421         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7422         lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7423                                                     ktimer->timer_advance_ns);
7424
7425         if (delta_tsc > lapic_timer_advance_cycles)
7426                 delta_tsc -= lapic_timer_advance_cycles;
7427         else
7428                 delta_tsc = 0;
7429
7430         /* Convert to host delta tsc if tsc scaling is enabled */
7431         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7432             delta_tsc && u64_shl_div_u64(delta_tsc,
7433                                 kvm_tsc_scaling_ratio_frac_bits,
7434                                 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7435                 return -ERANGE;
7436
7437         /*
7438          * If the delta tsc can't fit in the 32 bit after the multi shift,
7439          * we can't use the preemption timer.
7440          * It's possible that it fits on later vmentries, but checking
7441          * on every vmentry is costly so we just use an hrtimer.
7442          */
7443         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7444                 return -ERANGE;
7445
7446         vmx->hv_deadline_tsc = tscl + delta_tsc;
7447         *expired = !delta_tsc;
7448         return 0;
7449 }
7450
7451 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7452 {
7453         to_vmx(vcpu)->hv_deadline_tsc = -1;
7454 }
7455 #endif
7456
7457 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7458 {
7459         if (!kvm_pause_in_guest(vcpu->kvm))
7460                 shrink_ple_window(vcpu);
7461 }
7462
7463 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7464                                      struct kvm_memory_slot *slot)
7465 {
7466         if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7467                 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7468         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7469 }
7470
7471 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7472                                        struct kvm_memory_slot *slot)
7473 {
7474         kvm_mmu_slot_set_dirty(kvm, slot);
7475 }
7476
7477 static void vmx_flush_log_dirty(struct kvm *kvm)
7478 {
7479         kvm_flush_pml_buffers(kvm);
7480 }
7481
7482 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu, gpa_t gpa)
7483 {
7484         struct vmcs12 *vmcs12;
7485         struct vcpu_vmx *vmx = to_vmx(vcpu);
7486         gpa_t dst;
7487
7488         if (is_guest_mode(vcpu)) {
7489                 WARN_ON_ONCE(vmx->nested.pml_full);
7490
7491                 /*
7492                  * Check if PML is enabled for the nested guest.
7493                  * Whether eptp bit 6 is set is already checked
7494                  * as part of A/D emulation.
7495                  */
7496                 vmcs12 = get_vmcs12(vcpu);
7497                 if (!nested_cpu_has_pml(vmcs12))
7498                         return 0;
7499
7500                 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
7501                         vmx->nested.pml_full = true;
7502                         return 1;
7503                 }
7504
7505                 gpa &= ~0xFFFull;
7506                 dst = vmcs12->pml_address + sizeof(u64) * vmcs12->guest_pml_index;
7507
7508                 if (kvm_write_guest_page(vcpu->kvm, gpa_to_gfn(dst), &gpa,
7509                                          offset_in_page(dst), sizeof(gpa)))
7510                         return 0;
7511
7512                 vmcs12->guest_pml_index--;
7513         }
7514
7515         return 0;
7516 }
7517
7518 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7519                                            struct kvm_memory_slot *memslot,
7520                                            gfn_t offset, unsigned long mask)
7521 {
7522         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7523 }
7524
7525 static void __pi_post_block(struct kvm_vcpu *vcpu)
7526 {
7527         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7528         struct pi_desc old, new;
7529         unsigned int dest;
7530
7531         do {
7532                 old.control = new.control = pi_desc->control;
7533                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7534                      "Wakeup handler not enabled while the VCPU is blocked\n");
7535
7536                 dest = cpu_physical_id(vcpu->cpu);
7537
7538                 if (x2apic_enabled())
7539                         new.ndst = dest;
7540                 else
7541                         new.ndst = (dest << 8) & 0xFF00;
7542
7543                 /* set 'NV' to 'notification vector' */
7544                 new.nv = POSTED_INTR_VECTOR;
7545         } while (cmpxchg64(&pi_desc->control, old.control,
7546                            new.control) != old.control);
7547
7548         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7549                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7550                 list_del(&vcpu->blocked_vcpu_list);
7551                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7552                 vcpu->pre_pcpu = -1;
7553         }
7554 }
7555
7556 /*
7557  * This routine does the following things for vCPU which is going
7558  * to be blocked if VT-d PI is enabled.
7559  * - Store the vCPU to the wakeup list, so when interrupts happen
7560  *   we can find the right vCPU to wake up.
7561  * - Change the Posted-interrupt descriptor as below:
7562  *      'NDST' <-- vcpu->pre_pcpu
7563  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7564  * - If 'ON' is set during this process, which means at least one
7565  *   interrupt is posted for this vCPU, we cannot block it, in
7566  *   this case, return 1, otherwise, return 0.
7567  *
7568  */
7569 static int pi_pre_block(struct kvm_vcpu *vcpu)
7570 {
7571         unsigned int dest;
7572         struct pi_desc old, new;
7573         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7574
7575         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7576                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
7577                 !kvm_vcpu_apicv_active(vcpu))
7578                 return 0;
7579
7580         WARN_ON(irqs_disabled());
7581         local_irq_disable();
7582         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7583                 vcpu->pre_pcpu = vcpu->cpu;
7584                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7585                 list_add_tail(&vcpu->blocked_vcpu_list,
7586                               &per_cpu(blocked_vcpu_on_cpu,
7587                                        vcpu->pre_pcpu));
7588                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7589         }
7590
7591         do {
7592                 old.control = new.control = pi_desc->control;
7593
7594                 WARN((pi_desc->sn == 1),
7595                      "Warning: SN field of posted-interrupts "
7596                      "is set before blocking\n");
7597
7598                 /*
7599                  * Since vCPU can be preempted during this process,
7600                  * vcpu->cpu could be different with pre_pcpu, we
7601                  * need to set pre_pcpu as the destination of wakeup
7602                  * notification event, then we can find the right vCPU
7603                  * to wakeup in wakeup handler if interrupts happen
7604                  * when the vCPU is in blocked state.
7605                  */
7606                 dest = cpu_physical_id(vcpu->pre_pcpu);
7607
7608                 if (x2apic_enabled())
7609                         new.ndst = dest;
7610                 else
7611                         new.ndst = (dest << 8) & 0xFF00;
7612
7613                 /* set 'NV' to 'wakeup vector' */
7614                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7615         } while (cmpxchg64(&pi_desc->control, old.control,
7616                            new.control) != old.control);
7617
7618         /* We should not block the vCPU if an interrupt is posted for it.  */
7619         if (pi_test_on(pi_desc) == 1)
7620                 __pi_post_block(vcpu);
7621
7622         local_irq_enable();
7623         return (vcpu->pre_pcpu == -1);
7624 }
7625
7626 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7627 {
7628         if (pi_pre_block(vcpu))
7629                 return 1;
7630
7631         if (kvm_lapic_hv_timer_in_use(vcpu))
7632                 kvm_lapic_switch_to_sw_timer(vcpu);
7633
7634         return 0;
7635 }
7636
7637 static void pi_post_block(struct kvm_vcpu *vcpu)
7638 {
7639         if (vcpu->pre_pcpu == -1)
7640                 return;
7641
7642         WARN_ON(irqs_disabled());
7643         local_irq_disable();
7644         __pi_post_block(vcpu);
7645         local_irq_enable();
7646 }
7647
7648 static void vmx_post_block(struct kvm_vcpu *vcpu)
7649 {
7650         if (kvm_x86_ops.set_hv_timer)
7651                 kvm_lapic_switch_to_hv_timer(vcpu);
7652
7653         pi_post_block(vcpu);
7654 }
7655
7656 /*
7657  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7658  *
7659  * @kvm: kvm
7660  * @host_irq: host irq of the interrupt
7661  * @guest_irq: gsi of the interrupt
7662  * @set: set or unset PI
7663  * returns 0 on success, < 0 on failure
7664  */
7665 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7666                               uint32_t guest_irq, bool set)
7667 {
7668         struct kvm_kernel_irq_routing_entry *e;
7669         struct kvm_irq_routing_table *irq_rt;
7670         struct kvm_lapic_irq irq;
7671         struct kvm_vcpu *vcpu;
7672         struct vcpu_data vcpu_info;
7673         int idx, ret = 0;
7674
7675         if (!kvm_arch_has_assigned_device(kvm) ||
7676                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7677                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7678                 return 0;
7679
7680         idx = srcu_read_lock(&kvm->irq_srcu);
7681         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7682         if (guest_irq >= irq_rt->nr_rt_entries ||
7683             hlist_empty(&irq_rt->map[guest_irq])) {
7684                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7685                              guest_irq, irq_rt->nr_rt_entries);
7686                 goto out;
7687         }
7688
7689         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7690                 if (e->type != KVM_IRQ_ROUTING_MSI)
7691                         continue;
7692                 /*
7693                  * VT-d PI cannot support posting multicast/broadcast
7694                  * interrupts to a vCPU, we still use interrupt remapping
7695                  * for these kind of interrupts.
7696                  *
7697                  * For lowest-priority interrupts, we only support
7698                  * those with single CPU as the destination, e.g. user
7699                  * configures the interrupts via /proc/irq or uses
7700                  * irqbalance to make the interrupts single-CPU.
7701                  *
7702                  * We will support full lowest-priority interrupt later.
7703                  *
7704                  * In addition, we can only inject generic interrupts using
7705                  * the PI mechanism, refuse to route others through it.
7706                  */
7707
7708                 kvm_set_msi_irq(kvm, e, &irq);
7709                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7710                     !kvm_irq_is_postable(&irq)) {
7711                         /*
7712                          * Make sure the IRTE is in remapped mode if
7713                          * we don't handle it in posted mode.
7714                          */
7715                         ret = irq_set_vcpu_affinity(host_irq, NULL);
7716                         if (ret < 0) {
7717                                 printk(KERN_INFO
7718                                    "failed to back to remapped mode, irq: %u\n",
7719                                    host_irq);
7720                                 goto out;
7721                         }
7722
7723                         continue;
7724                 }
7725
7726                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7727                 vcpu_info.vector = irq.vector;
7728
7729                 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7730                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7731
7732                 if (set)
7733                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7734                 else
7735                         ret = irq_set_vcpu_affinity(host_irq, NULL);
7736
7737                 if (ret < 0) {
7738                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
7739                                         __func__);
7740                         goto out;
7741                 }
7742         }
7743
7744         ret = 0;
7745 out:
7746         srcu_read_unlock(&kvm->irq_srcu, idx);
7747         return ret;
7748 }
7749
7750 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7751 {
7752         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7753                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7754                         FEAT_CTL_LMCE_ENABLED;
7755         else
7756                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7757                         ~FEAT_CTL_LMCE_ENABLED;
7758 }
7759
7760 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7761 {
7762         /* we need a nested vmexit to enter SMM, postpone if run is pending */
7763         if (to_vmx(vcpu)->nested.nested_run_pending)
7764                 return -EBUSY;
7765         return !is_smm(vcpu);
7766 }
7767
7768 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7769 {
7770         struct vcpu_vmx *vmx = to_vmx(vcpu);
7771
7772         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7773         if (vmx->nested.smm.guest_mode)
7774                 nested_vmx_vmexit(vcpu, -1, 0, 0);
7775
7776         vmx->nested.smm.vmxon = vmx->nested.vmxon;
7777         vmx->nested.vmxon = false;
7778         vmx_clear_hlt(vcpu);
7779         return 0;
7780 }
7781
7782 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7783 {
7784         struct vcpu_vmx *vmx = to_vmx(vcpu);
7785         int ret;
7786
7787         if (vmx->nested.smm.vmxon) {
7788                 vmx->nested.vmxon = true;
7789                 vmx->nested.smm.vmxon = false;
7790         }
7791
7792         if (vmx->nested.smm.guest_mode) {
7793                 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7794                 if (ret)
7795                         return ret;
7796
7797                 vmx->nested.smm.guest_mode = false;
7798         }
7799         return 0;
7800 }
7801
7802 static void enable_smi_window(struct kvm_vcpu *vcpu)
7803 {
7804         /* RSM will cause a vmexit anyway.  */
7805 }
7806
7807 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7808 {
7809         return false;
7810 }
7811
7812 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7813 {
7814         return to_vmx(vcpu)->nested.vmxon;
7815 }
7816
7817 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7818 {
7819         if (is_guest_mode(vcpu)) {
7820                 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7821
7822                 if (hrtimer_try_to_cancel(timer) == 1)
7823                         hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7824         }
7825 }
7826
7827 static void hardware_unsetup(void)
7828 {
7829         if (nested)
7830                 nested_vmx_hardware_unsetup();
7831
7832         free_kvm_area();
7833 }
7834
7835 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7836 {
7837         ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7838                           BIT(APICV_INHIBIT_REASON_HYPERV);
7839
7840         return supported & BIT(bit);
7841 }
7842
7843 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7844         .hardware_unsetup = hardware_unsetup,
7845
7846         .hardware_enable = hardware_enable,
7847         .hardware_disable = hardware_disable,
7848         .cpu_has_accelerated_tpr = report_flexpriority,
7849         .has_emulated_msr = vmx_has_emulated_msr,
7850
7851         .vm_size = sizeof(struct kvm_vmx),
7852         .vm_init = vmx_vm_init,
7853
7854         .vcpu_create = vmx_create_vcpu,
7855         .vcpu_free = vmx_free_vcpu,
7856         .vcpu_reset = vmx_vcpu_reset,
7857
7858         .prepare_guest_switch = vmx_prepare_switch_to_guest,
7859         .vcpu_load = vmx_vcpu_load,
7860         .vcpu_put = vmx_vcpu_put,
7861
7862         .update_bp_intercept = update_exception_bitmap,
7863         .get_msr_feature = vmx_get_msr_feature,
7864         .get_msr = vmx_get_msr,
7865         .set_msr = vmx_set_msr,
7866         .get_segment_base = vmx_get_segment_base,
7867         .get_segment = vmx_get_segment,
7868         .set_segment = vmx_set_segment,
7869         .get_cpl = vmx_get_cpl,
7870         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7871         .set_cr0 = vmx_set_cr0,
7872         .set_cr4 = vmx_set_cr4,
7873         .set_efer = vmx_set_efer,
7874         .get_idt = vmx_get_idt,
7875         .set_idt = vmx_set_idt,
7876         .get_gdt = vmx_get_gdt,
7877         .set_gdt = vmx_set_gdt,
7878         .set_dr7 = vmx_set_dr7,
7879         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7880         .cache_reg = vmx_cache_reg,
7881         .get_rflags = vmx_get_rflags,
7882         .set_rflags = vmx_set_rflags,
7883
7884         .tlb_flush_all = vmx_flush_tlb_all,
7885         .tlb_flush_current = vmx_flush_tlb_current,
7886         .tlb_flush_gva = vmx_flush_tlb_gva,
7887         .tlb_flush_guest = vmx_flush_tlb_guest,
7888
7889         .run = vmx_vcpu_run,
7890         .handle_exit = vmx_handle_exit,
7891         .skip_emulated_instruction = vmx_skip_emulated_instruction,
7892         .update_emulated_instruction = vmx_update_emulated_instruction,
7893         .set_interrupt_shadow = vmx_set_interrupt_shadow,
7894         .get_interrupt_shadow = vmx_get_interrupt_shadow,
7895         .patch_hypercall = vmx_patch_hypercall,
7896         .set_irq = vmx_inject_irq,
7897         .set_nmi = vmx_inject_nmi,
7898         .queue_exception = vmx_queue_exception,
7899         .cancel_injection = vmx_cancel_injection,
7900         .interrupt_allowed = vmx_interrupt_allowed,
7901         .nmi_allowed = vmx_nmi_allowed,
7902         .get_nmi_mask = vmx_get_nmi_mask,
7903         .set_nmi_mask = vmx_set_nmi_mask,
7904         .enable_nmi_window = enable_nmi_window,
7905         .enable_irq_window = enable_irq_window,
7906         .update_cr8_intercept = update_cr8_intercept,
7907         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7908         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7909         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7910         .load_eoi_exitmap = vmx_load_eoi_exitmap,
7911         .apicv_post_state_restore = vmx_apicv_post_state_restore,
7912         .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7913         .hwapic_irr_update = vmx_hwapic_irr_update,
7914         .hwapic_isr_update = vmx_hwapic_isr_update,
7915         .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7916         .sync_pir_to_irr = vmx_sync_pir_to_irr,
7917         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7918         .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7919
7920         .set_tss_addr = vmx_set_tss_addr,
7921         .set_identity_map_addr = vmx_set_identity_map_addr,
7922         .get_tdp_level = vmx_get_tdp_level,
7923         .get_mt_mask = vmx_get_mt_mask,
7924
7925         .get_exit_info = vmx_get_exit_info,
7926
7927         .cpuid_update = vmx_cpuid_update,
7928
7929         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7930
7931         .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7932
7933         .load_mmu_pgd = vmx_load_mmu_pgd,
7934
7935         .check_intercept = vmx_check_intercept,
7936         .handle_exit_irqoff = vmx_handle_exit_irqoff,
7937
7938         .request_immediate_exit = vmx_request_immediate_exit,
7939
7940         .sched_in = vmx_sched_in,
7941
7942         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7943         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7944         .flush_log_dirty = vmx_flush_log_dirty,
7945         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7946         .write_log_dirty = vmx_write_pml_buffer,
7947
7948         .pre_block = vmx_pre_block,
7949         .post_block = vmx_post_block,
7950
7951         .pmu_ops = &intel_pmu_ops,
7952         .nested_ops = &vmx_nested_ops,
7953
7954         .update_pi_irte = vmx_update_pi_irte,
7955
7956 #ifdef CONFIG_X86_64
7957         .set_hv_timer = vmx_set_hv_timer,
7958         .cancel_hv_timer = vmx_cancel_hv_timer,
7959 #endif
7960
7961         .setup_mce = vmx_setup_mce,
7962
7963         .smi_allowed = vmx_smi_allowed,
7964         .pre_enter_smm = vmx_pre_enter_smm,
7965         .pre_leave_smm = vmx_pre_leave_smm,
7966         .enable_smi_window = enable_smi_window,
7967
7968         .need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
7969         .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
7970         .migrate_timers = vmx_migrate_timers,
7971 };
7972
7973 static __init int hardware_setup(void)
7974 {
7975         unsigned long host_bndcfgs;
7976         struct desc_ptr dt;
7977         int r, i, ept_lpage_level;
7978
7979         store_idt(&dt);
7980         host_idt_base = dt.address;
7981
7982         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7983                 kvm_define_shared_msr(i, vmx_msr_index[i]);
7984
7985         if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
7986                 return -EIO;
7987
7988         if (boot_cpu_has(X86_FEATURE_NX))
7989                 kvm_enable_efer_bits(EFER_NX);
7990
7991         if (boot_cpu_has(X86_FEATURE_MPX)) {
7992                 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7993                 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7994         }
7995
7996         if (!cpu_has_vmx_mpx())
7997                 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
7998                                     XFEATURE_MASK_BNDCSR);
7999
8000         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8001             !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8002                 enable_vpid = 0;
8003
8004         if (!cpu_has_vmx_ept() ||
8005             !cpu_has_vmx_ept_4levels() ||
8006             !cpu_has_vmx_ept_mt_wb() ||
8007             !cpu_has_vmx_invept_global())
8008                 enable_ept = 0;
8009
8010         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8011                 enable_ept_ad_bits = 0;
8012
8013         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8014                 enable_unrestricted_guest = 0;
8015
8016         if (!cpu_has_vmx_flexpriority())
8017                 flexpriority_enabled = 0;
8018
8019         if (!cpu_has_virtual_nmis())
8020                 enable_vnmi = 0;
8021
8022         /*
8023          * set_apic_access_page_addr() is used to reload apic access
8024          * page upon invalidation.  No need to do anything if not
8025          * using the APIC_ACCESS_ADDR VMCS field.
8026          */
8027         if (!flexpriority_enabled)
8028                 vmx_x86_ops.set_apic_access_page_addr = NULL;
8029
8030         if (!cpu_has_vmx_tpr_shadow())
8031                 vmx_x86_ops.update_cr8_intercept = NULL;
8032
8033 #if IS_ENABLED(CONFIG_HYPERV)
8034         if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8035             && enable_ept) {
8036                 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8037                 vmx_x86_ops.tlb_remote_flush_with_range =
8038                                 hv_remote_flush_tlb_with_range;
8039         }
8040 #endif
8041
8042         if (!cpu_has_vmx_ple()) {
8043                 ple_gap = 0;
8044                 ple_window = 0;
8045                 ple_window_grow = 0;
8046                 ple_window_max = 0;
8047                 ple_window_shrink = 0;
8048         }
8049
8050         if (!cpu_has_vmx_apicv()) {
8051                 enable_apicv = 0;
8052                 vmx_x86_ops.sync_pir_to_irr = NULL;
8053         }
8054
8055         if (cpu_has_vmx_tsc_scaling()) {
8056                 kvm_has_tsc_control = true;
8057                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8058                 kvm_tsc_scaling_ratio_frac_bits = 48;
8059         }
8060
8061         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8062
8063         if (enable_ept)
8064                 vmx_enable_tdp();
8065
8066         if (!enable_ept)
8067                 ept_lpage_level = 0;
8068         else if (cpu_has_vmx_ept_1g_page())
8069                 ept_lpage_level = PG_LEVEL_1G;
8070         else if (cpu_has_vmx_ept_2m_page())
8071                 ept_lpage_level = PG_LEVEL_2M;
8072         else
8073                 ept_lpage_level = PG_LEVEL_4K;
8074         kvm_configure_mmu(enable_ept, ept_lpage_level);
8075
8076         /*
8077          * Only enable PML when hardware supports PML feature, and both EPT
8078          * and EPT A/D bit features are enabled -- PML depends on them to work.
8079          */
8080         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8081                 enable_pml = 0;
8082
8083         if (!enable_pml) {
8084                 vmx_x86_ops.slot_enable_log_dirty = NULL;
8085                 vmx_x86_ops.slot_disable_log_dirty = NULL;
8086                 vmx_x86_ops.flush_log_dirty = NULL;
8087                 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
8088         }
8089
8090         if (!cpu_has_vmx_preemption_timer())
8091                 enable_preemption_timer = false;
8092
8093         if (enable_preemption_timer) {
8094                 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8095                 u64 vmx_msr;
8096
8097                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8098                 cpu_preemption_timer_multi =
8099                         vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8100
8101                 if (tsc_khz)
8102                         use_timer_freq = (u64)tsc_khz * 1000;
8103                 use_timer_freq >>= cpu_preemption_timer_multi;
8104
8105                 /*
8106                  * KVM "disables" the preemption timer by setting it to its max
8107                  * value.  Don't use the timer if it might cause spurious exits
8108                  * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8109                  */
8110                 if (use_timer_freq > 0xffffffffu / 10)
8111                         enable_preemption_timer = false;
8112         }
8113
8114         if (!enable_preemption_timer) {
8115                 vmx_x86_ops.set_hv_timer = NULL;
8116                 vmx_x86_ops.cancel_hv_timer = NULL;
8117                 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8118         }
8119
8120         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8121
8122         kvm_mce_cap_supported |= MCG_LMCE_P;
8123
8124         if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8125                 return -EINVAL;
8126         if (!enable_ept || !cpu_has_vmx_intel_pt())
8127                 pt_mode = PT_MODE_SYSTEM;
8128
8129         if (nested) {
8130                 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
8131                                            vmx_capability.ept);
8132
8133                 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8134                 if (r)
8135                         return r;
8136         }
8137
8138         vmx_set_cpu_caps();
8139
8140         r = alloc_kvm_area();
8141         if (r)
8142                 nested_vmx_hardware_unsetup();
8143         return r;
8144 }
8145
8146 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8147         .cpu_has_kvm_support = cpu_has_kvm_support,
8148         .disabled_by_bios = vmx_disabled_by_bios,
8149         .check_processor_compatibility = vmx_check_processor_compat,
8150         .hardware_setup = hardware_setup,
8151
8152         .runtime_ops = &vmx_x86_ops,
8153 };
8154
8155 static void vmx_cleanup_l1d_flush(void)
8156 {
8157         if (vmx_l1d_flush_pages) {
8158                 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8159                 vmx_l1d_flush_pages = NULL;
8160         }
8161         /* Restore state so sysfs ignores VMX */
8162         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8163 }
8164
8165 static void vmx_exit(void)
8166 {
8167 #ifdef CONFIG_KEXEC_CORE
8168         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8169         synchronize_rcu();
8170 #endif
8171
8172         kvm_exit();
8173
8174 #if IS_ENABLED(CONFIG_HYPERV)
8175         if (static_branch_unlikely(&enable_evmcs)) {
8176                 int cpu;
8177                 struct hv_vp_assist_page *vp_ap;
8178                 /*
8179                  * Reset everything to support using non-enlightened VMCS
8180                  * access later (e.g. when we reload the module with
8181                  * enlightened_vmcs=0)
8182                  */
8183                 for_each_online_cpu(cpu) {
8184                         vp_ap = hv_get_vp_assist_page(cpu);
8185
8186                         if (!vp_ap)
8187                                 continue;
8188
8189                         vp_ap->nested_control.features.directhypercall = 0;
8190                         vp_ap->current_nested_vmcs = 0;
8191                         vp_ap->enlighten_vmentry = 0;
8192                 }
8193
8194                 static_branch_disable(&enable_evmcs);
8195         }
8196 #endif
8197         vmx_cleanup_l1d_flush();
8198 }
8199 module_exit(vmx_exit);
8200
8201 static int __init vmx_init(void)
8202 {
8203         int r, cpu;
8204
8205 #if IS_ENABLED(CONFIG_HYPERV)
8206         /*
8207          * Enlightened VMCS usage should be recommended and the host needs
8208          * to support eVMCS v1 or above. We can also disable eVMCS support
8209          * with module parameter.
8210          */
8211         if (enlightened_vmcs &&
8212             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8213             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8214             KVM_EVMCS_VERSION) {
8215                 int cpu;
8216
8217                 /* Check that we have assist pages on all online CPUs */
8218                 for_each_online_cpu(cpu) {
8219                         if (!hv_get_vp_assist_page(cpu)) {
8220                                 enlightened_vmcs = false;
8221                                 break;
8222                         }
8223                 }
8224
8225                 if (enlightened_vmcs) {
8226                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8227                         static_branch_enable(&enable_evmcs);
8228                 }
8229
8230                 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8231                         vmx_x86_ops.enable_direct_tlbflush
8232                                 = hv_enable_direct_tlbflush;
8233
8234         } else {
8235                 enlightened_vmcs = false;
8236         }
8237 #endif
8238
8239         r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8240                      __alignof__(struct vcpu_vmx), THIS_MODULE);
8241         if (r)
8242                 return r;
8243
8244         /*
8245          * Must be called after kvm_init() so enable_ept is properly set
8246          * up. Hand the parameter mitigation value in which was stored in
8247          * the pre module init parser. If no parameter was given, it will
8248          * contain 'auto' which will be turned into the default 'cond'
8249          * mitigation mode.
8250          */
8251         r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8252         if (r) {
8253                 vmx_exit();
8254                 return r;
8255         }
8256
8257         for_each_possible_cpu(cpu) {
8258                 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8259                 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
8260                 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
8261         }
8262
8263 #ifdef CONFIG_KEXEC_CORE
8264         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8265                            crash_vmclear_local_loaded_vmcss);
8266 #endif
8267         vmx_check_vmcs12_offsets();
8268
8269         return 0;
8270 }
8271 module_init(vmx_init);