791baa73e5786ba60100b282f7c99fa752d9b0ee
[linux-2.6-microblaze.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 (!vmx_need_pf_intercept(vcpu))
784                 eb &= ~(1u << PF_VECTOR);
785
786         /* When we are running a nested L2 guest and L1 specified for it a
787          * certain exception bitmap, we must trap the same exceptions and pass
788          * them to L1. When running L2, we will only handle the exceptions
789          * specified above if L1 did not want them.
790          */
791         if (is_guest_mode(vcpu))
792                 eb |= get_vmcs12(vcpu)->exception_bitmap;
793
794         vmcs_write32(EXCEPTION_BITMAP, eb);
795 }
796
797 /*
798  * Check if MSR is intercepted for currently loaded MSR bitmap.
799  */
800 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
801 {
802         unsigned long *msr_bitmap;
803         int f = sizeof(unsigned long);
804
805         if (!cpu_has_vmx_msr_bitmap())
806                 return true;
807
808         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
809
810         if (msr <= 0x1fff) {
811                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
812         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
813                 msr &= 0x1fff;
814                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
815         }
816
817         return true;
818 }
819
820 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
821                 unsigned long entry, unsigned long exit)
822 {
823         vm_entry_controls_clearbit(vmx, entry);
824         vm_exit_controls_clearbit(vmx, exit);
825 }
826
827 int vmx_find_msr_index(struct vmx_msrs *m, u32 msr)
828 {
829         unsigned int i;
830
831         for (i = 0; i < m->nr; ++i) {
832                 if (m->val[i].index == msr)
833                         return i;
834         }
835         return -ENOENT;
836 }
837
838 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
839 {
840         int i;
841         struct msr_autoload *m = &vmx->msr_autoload;
842
843         switch (msr) {
844         case MSR_EFER:
845                 if (cpu_has_load_ia32_efer()) {
846                         clear_atomic_switch_msr_special(vmx,
847                                         VM_ENTRY_LOAD_IA32_EFER,
848                                         VM_EXIT_LOAD_IA32_EFER);
849                         return;
850                 }
851                 break;
852         case MSR_CORE_PERF_GLOBAL_CTRL:
853                 if (cpu_has_load_perf_global_ctrl()) {
854                         clear_atomic_switch_msr_special(vmx,
855                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
856                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
857                         return;
858                 }
859                 break;
860         }
861         i = vmx_find_msr_index(&m->guest, msr);
862         if (i < 0)
863                 goto skip_guest;
864         --m->guest.nr;
865         m->guest.val[i] = m->guest.val[m->guest.nr];
866         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
867
868 skip_guest:
869         i = vmx_find_msr_index(&m->host, msr);
870         if (i < 0)
871                 return;
872
873         --m->host.nr;
874         m->host.val[i] = m->host.val[m->host.nr];
875         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
876 }
877
878 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
879                 unsigned long entry, unsigned long exit,
880                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
881                 u64 guest_val, u64 host_val)
882 {
883         vmcs_write64(guest_val_vmcs, guest_val);
884         if (host_val_vmcs != HOST_IA32_EFER)
885                 vmcs_write64(host_val_vmcs, host_val);
886         vm_entry_controls_setbit(vmx, entry);
887         vm_exit_controls_setbit(vmx, exit);
888 }
889
890 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
891                                   u64 guest_val, u64 host_val, bool entry_only)
892 {
893         int i, j = 0;
894         struct msr_autoload *m = &vmx->msr_autoload;
895
896         switch (msr) {
897         case MSR_EFER:
898                 if (cpu_has_load_ia32_efer()) {
899                         add_atomic_switch_msr_special(vmx,
900                                         VM_ENTRY_LOAD_IA32_EFER,
901                                         VM_EXIT_LOAD_IA32_EFER,
902                                         GUEST_IA32_EFER,
903                                         HOST_IA32_EFER,
904                                         guest_val, host_val);
905                         return;
906                 }
907                 break;
908         case MSR_CORE_PERF_GLOBAL_CTRL:
909                 if (cpu_has_load_perf_global_ctrl()) {
910                         add_atomic_switch_msr_special(vmx,
911                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
912                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
913                                         GUEST_IA32_PERF_GLOBAL_CTRL,
914                                         HOST_IA32_PERF_GLOBAL_CTRL,
915                                         guest_val, host_val);
916                         return;
917                 }
918                 break;
919         case MSR_IA32_PEBS_ENABLE:
920                 /* PEBS needs a quiescent period after being disabled (to write
921                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
922                  * provide that period, so a CPU could write host's record into
923                  * guest's memory.
924                  */
925                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
926         }
927
928         i = vmx_find_msr_index(&m->guest, msr);
929         if (!entry_only)
930                 j = vmx_find_msr_index(&m->host, msr);
931
932         if ((i < 0 && m->guest.nr == NR_LOADSTORE_MSRS) ||
933                 (j < 0 &&  m->host.nr == NR_LOADSTORE_MSRS)) {
934                 printk_once(KERN_WARNING "Not enough msr switch entries. "
935                                 "Can't add msr %x\n", msr);
936                 return;
937         }
938         if (i < 0) {
939                 i = m->guest.nr++;
940                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
941         }
942         m->guest.val[i].index = msr;
943         m->guest.val[i].value = guest_val;
944
945         if (entry_only)
946                 return;
947
948         if (j < 0) {
949                 j = m->host.nr++;
950                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
951         }
952         m->host.val[j].index = msr;
953         m->host.val[j].value = host_val;
954 }
955
956 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
957 {
958         u64 guest_efer = vmx->vcpu.arch.efer;
959         u64 ignore_bits = 0;
960
961         /* Shadow paging assumes NX to be available.  */
962         if (!enable_ept)
963                 guest_efer |= EFER_NX;
964
965         /*
966          * LMA and LME handled by hardware; SCE meaningless outside long mode.
967          */
968         ignore_bits |= EFER_SCE;
969 #ifdef CONFIG_X86_64
970         ignore_bits |= EFER_LMA | EFER_LME;
971         /* SCE is meaningful only in long mode on Intel */
972         if (guest_efer & EFER_LMA)
973                 ignore_bits &= ~(u64)EFER_SCE;
974 #endif
975
976         /*
977          * On EPT, we can't emulate NX, so we must switch EFER atomically.
978          * On CPUs that support "load IA32_EFER", always switch EFER
979          * atomically, since it's faster than switching it manually.
980          */
981         if (cpu_has_load_ia32_efer() ||
982             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
983                 if (!(guest_efer & EFER_LMA))
984                         guest_efer &= ~EFER_LME;
985                 if (guest_efer != host_efer)
986                         add_atomic_switch_msr(vmx, MSR_EFER,
987                                               guest_efer, host_efer, false);
988                 else
989                         clear_atomic_switch_msr(vmx, MSR_EFER);
990                 return false;
991         } else {
992                 clear_atomic_switch_msr(vmx, MSR_EFER);
993
994                 guest_efer &= ~ignore_bits;
995                 guest_efer |= host_efer & ignore_bits;
996
997                 vmx->guest_msrs[efer_offset].data = guest_efer;
998                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
999
1000                 return true;
1001         }
1002 }
1003
1004 #ifdef CONFIG_X86_32
1005 /*
1006  * On 32-bit kernels, VM exits still load the FS and GS bases from the
1007  * VMCS rather than the segment table.  KVM uses this helper to figure
1008  * out the current bases to poke them into the VMCS before entry.
1009  */
1010 static unsigned long segment_base(u16 selector)
1011 {
1012         struct desc_struct *table;
1013         unsigned long v;
1014
1015         if (!(selector & ~SEGMENT_RPL_MASK))
1016                 return 0;
1017
1018         table = get_current_gdt_ro();
1019
1020         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1021                 u16 ldt_selector = kvm_read_ldt();
1022
1023                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1024                         return 0;
1025
1026                 table = (struct desc_struct *)segment_base(ldt_selector);
1027         }
1028         v = get_desc_base(&table[selector >> 3]);
1029         return v;
1030 }
1031 #endif
1032
1033 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1034 {
1035         return vmx_pt_mode_is_host_guest() &&
1036                !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1037 }
1038
1039 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1040 {
1041         u32 i;
1042
1043         wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1044         wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1045         wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1046         wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1047         for (i = 0; i < addr_range; i++) {
1048                 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1049                 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1050         }
1051 }
1052
1053 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1054 {
1055         u32 i;
1056
1057         rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1058         rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1059         rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1060         rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1061         for (i = 0; i < addr_range; i++) {
1062                 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1063                 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1064         }
1065 }
1066
1067 static void pt_guest_enter(struct vcpu_vmx *vmx)
1068 {
1069         if (vmx_pt_mode_is_system())
1070                 return;
1071
1072         /*
1073          * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1074          * Save host state before VM entry.
1075          */
1076         rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1077         if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1078                 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1079                 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1080                 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1081         }
1082 }
1083
1084 static void pt_guest_exit(struct vcpu_vmx *vmx)
1085 {
1086         if (vmx_pt_mode_is_system())
1087                 return;
1088
1089         if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1090                 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1091                 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1092         }
1093
1094         /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1095         wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1096 }
1097
1098 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1099                         unsigned long fs_base, unsigned long gs_base)
1100 {
1101         if (unlikely(fs_sel != host->fs_sel)) {
1102                 if (!(fs_sel & 7))
1103                         vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1104                 else
1105                         vmcs_write16(HOST_FS_SELECTOR, 0);
1106                 host->fs_sel = fs_sel;
1107         }
1108         if (unlikely(gs_sel != host->gs_sel)) {
1109                 if (!(gs_sel & 7))
1110                         vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1111                 else
1112                         vmcs_write16(HOST_GS_SELECTOR, 0);
1113                 host->gs_sel = gs_sel;
1114         }
1115         if (unlikely(fs_base != host->fs_base)) {
1116                 vmcs_writel(HOST_FS_BASE, fs_base);
1117                 host->fs_base = fs_base;
1118         }
1119         if (unlikely(gs_base != host->gs_base)) {
1120                 vmcs_writel(HOST_GS_BASE, gs_base);
1121                 host->gs_base = gs_base;
1122         }
1123 }
1124
1125 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1126 {
1127         struct vcpu_vmx *vmx = to_vmx(vcpu);
1128         struct vmcs_host_state *host_state;
1129 #ifdef CONFIG_X86_64
1130         int cpu = raw_smp_processor_id();
1131 #endif
1132         unsigned long fs_base, gs_base;
1133         u16 fs_sel, gs_sel;
1134         int i;
1135
1136         vmx->req_immediate_exit = false;
1137
1138         /*
1139          * Note that guest MSRs to be saved/restored can also be changed
1140          * when guest state is loaded. This happens when guest transitions
1141          * to/from long-mode by setting MSR_EFER.LMA.
1142          */
1143         if (!vmx->guest_msrs_ready) {
1144                 vmx->guest_msrs_ready = true;
1145                 for (i = 0; i < vmx->save_nmsrs; ++i)
1146                         kvm_set_shared_msr(vmx->guest_msrs[i].index,
1147                                            vmx->guest_msrs[i].data,
1148                                            vmx->guest_msrs[i].mask);
1149
1150         }
1151
1152         if (vmx->nested.need_vmcs12_to_shadow_sync)
1153                 nested_sync_vmcs12_to_shadow(vcpu);
1154
1155         if (vmx->guest_state_loaded)
1156                 return;
1157
1158         host_state = &vmx->loaded_vmcs->host_state;
1159
1160         /*
1161          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1162          * allow segment selectors with cpl > 0 or ti == 1.
1163          */
1164         host_state->ldt_sel = kvm_read_ldt();
1165
1166 #ifdef CONFIG_X86_64
1167         savesegment(ds, host_state->ds_sel);
1168         savesegment(es, host_state->es_sel);
1169
1170         gs_base = cpu_kernelmode_gs_base(cpu);
1171         if (likely(is_64bit_mm(current->mm))) {
1172                 save_fsgs_for_kvm();
1173                 fs_sel = current->thread.fsindex;
1174                 gs_sel = current->thread.gsindex;
1175                 fs_base = current->thread.fsbase;
1176                 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1177         } else {
1178                 savesegment(fs, fs_sel);
1179                 savesegment(gs, gs_sel);
1180                 fs_base = read_msr(MSR_FS_BASE);
1181                 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1182         }
1183
1184         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1185 #else
1186         savesegment(fs, fs_sel);
1187         savesegment(gs, gs_sel);
1188         fs_base = segment_base(fs_sel);
1189         gs_base = segment_base(gs_sel);
1190 #endif
1191
1192         vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1193         vmx->guest_state_loaded = true;
1194 }
1195
1196 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1197 {
1198         struct vmcs_host_state *host_state;
1199
1200         if (!vmx->guest_state_loaded)
1201                 return;
1202
1203         host_state = &vmx->loaded_vmcs->host_state;
1204
1205         ++vmx->vcpu.stat.host_state_reload;
1206
1207 #ifdef CONFIG_X86_64
1208         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1209 #endif
1210         if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1211                 kvm_load_ldt(host_state->ldt_sel);
1212 #ifdef CONFIG_X86_64
1213                 load_gs_index(host_state->gs_sel);
1214 #else
1215                 loadsegment(gs, host_state->gs_sel);
1216 #endif
1217         }
1218         if (host_state->fs_sel & 7)
1219                 loadsegment(fs, host_state->fs_sel);
1220 #ifdef CONFIG_X86_64
1221         if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1222                 loadsegment(ds, host_state->ds_sel);
1223                 loadsegment(es, host_state->es_sel);
1224         }
1225 #endif
1226         invalidate_tss_limit();
1227 #ifdef CONFIG_X86_64
1228         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1229 #endif
1230         load_fixmap_gdt(raw_smp_processor_id());
1231         vmx->guest_state_loaded = false;
1232         vmx->guest_msrs_ready = false;
1233 }
1234
1235 #ifdef CONFIG_X86_64
1236 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1237 {
1238         preempt_disable();
1239         if (vmx->guest_state_loaded)
1240                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1241         preempt_enable();
1242         return vmx->msr_guest_kernel_gs_base;
1243 }
1244
1245 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1246 {
1247         preempt_disable();
1248         if (vmx->guest_state_loaded)
1249                 wrmsrl(MSR_KERNEL_GS_BASE, data);
1250         preempt_enable();
1251         vmx->msr_guest_kernel_gs_base = data;
1252 }
1253 #endif
1254
1255 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1256 {
1257         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1258         struct pi_desc old, new;
1259         unsigned int dest;
1260
1261         /*
1262          * In case of hot-plug or hot-unplug, we may have to undo
1263          * vmx_vcpu_pi_put even if there is no assigned device.  And we
1264          * always keep PI.NDST up to date for simplicity: it makes the
1265          * code easier, and CPU migration is not a fast path.
1266          */
1267         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1268                 return;
1269
1270         /*
1271          * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
1272          * PI.NDST: pi_post_block is the one expected to change PID.NDST and the
1273          * wakeup handler expects the vCPU to be on the blocked_vcpu_list that
1274          * matches PI.NDST. Otherwise, a vcpu may not be able to be woken up
1275          * correctly.
1276          */
1277         if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR || vcpu->cpu == cpu) {
1278                 pi_clear_sn(pi_desc);
1279                 goto after_clear_sn;
1280         }
1281
1282         /* The full case.  */
1283         do {
1284                 old.control = new.control = pi_desc->control;
1285
1286                 dest = cpu_physical_id(cpu);
1287
1288                 if (x2apic_enabled())
1289                         new.ndst = dest;
1290                 else
1291                         new.ndst = (dest << 8) & 0xFF00;
1292
1293                 new.sn = 0;
1294         } while (cmpxchg64(&pi_desc->control, old.control,
1295                            new.control) != old.control);
1296
1297 after_clear_sn:
1298
1299         /*
1300          * Clear SN before reading the bitmap.  The VT-d firmware
1301          * writes the bitmap and reads SN atomically (5.2.3 in the
1302          * spec), so it doesn't really have a memory barrier that
1303          * pairs with this, but we cannot do that and we need one.
1304          */
1305         smp_mb__after_atomic();
1306
1307         if (!pi_is_pir_empty(pi_desc))
1308                 pi_set_on(pi_desc);
1309 }
1310
1311 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1312                         struct loaded_vmcs *buddy)
1313 {
1314         struct vcpu_vmx *vmx = to_vmx(vcpu);
1315         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1316         struct vmcs *prev;
1317
1318         if (!already_loaded) {
1319                 loaded_vmcs_clear(vmx->loaded_vmcs);
1320                 local_irq_disable();
1321
1322                 /*
1323                  * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1324                  * this cpu's percpu list, otherwise it may not yet be deleted
1325                  * from its previous cpu's percpu list.  Pairs with the
1326                  * smb_wmb() in __loaded_vmcs_clear().
1327                  */
1328                 smp_rmb();
1329
1330                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1331                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1332                 local_irq_enable();
1333         }
1334
1335         prev = per_cpu(current_vmcs, cpu);
1336         if (prev != vmx->loaded_vmcs->vmcs) {
1337                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1338                 vmcs_load(vmx->loaded_vmcs->vmcs);
1339
1340                 /*
1341                  * No indirect branch prediction barrier needed when switching
1342                  * the active VMCS within a guest, e.g. on nested VM-Enter.
1343                  * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1344                  */
1345                 if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1346                         indirect_branch_prediction_barrier();
1347         }
1348
1349         if (!already_loaded) {
1350                 void *gdt = get_current_gdt_ro();
1351                 unsigned long sysenter_esp;
1352
1353                 /*
1354                  * Flush all EPTP/VPID contexts, the new pCPU may have stale
1355                  * TLB entries from its previous association with the vCPU.
1356                  */
1357                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1358
1359                 /*
1360                  * Linux uses per-cpu TSS and GDT, so set these when switching
1361                  * processors.  See 22.2.4.
1362                  */
1363                 vmcs_writel(HOST_TR_BASE,
1364                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1365                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
1366
1367                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1368                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1369
1370                 vmx->loaded_vmcs->cpu = cpu;
1371         }
1372
1373         /* Setup TSC multiplier */
1374         if (kvm_has_tsc_control &&
1375             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1376                 decache_tsc_multiplier(vmx);
1377 }
1378
1379 /*
1380  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1381  * vcpu mutex is already taken.
1382  */
1383 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1384 {
1385         struct vcpu_vmx *vmx = to_vmx(vcpu);
1386
1387         vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1388
1389         vmx_vcpu_pi_load(vcpu, cpu);
1390
1391         vmx->host_debugctlmsr = get_debugctlmsr();
1392 }
1393
1394 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1395 {
1396         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1397
1398         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1399                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
1400                 !kvm_vcpu_apicv_active(vcpu))
1401                 return;
1402
1403         /* Set SN when the vCPU is preempted */
1404         if (vcpu->preempted)
1405                 pi_set_sn(pi_desc);
1406 }
1407
1408 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1409 {
1410         vmx_vcpu_pi_put(vcpu);
1411
1412         vmx_prepare_switch_to_host(to_vmx(vcpu));
1413 }
1414
1415 static bool emulation_required(struct kvm_vcpu *vcpu)
1416 {
1417         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1418 }
1419
1420 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1421 {
1422         struct vcpu_vmx *vmx = to_vmx(vcpu);
1423         unsigned long rflags, save_rflags;
1424
1425         if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1426                 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1427                 rflags = vmcs_readl(GUEST_RFLAGS);
1428                 if (vmx->rmode.vm86_active) {
1429                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1430                         save_rflags = vmx->rmode.save_rflags;
1431                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1432                 }
1433                 vmx->rflags = rflags;
1434         }
1435         return vmx->rflags;
1436 }
1437
1438 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1439 {
1440         struct vcpu_vmx *vmx = to_vmx(vcpu);
1441         unsigned long old_rflags;
1442
1443         if (enable_unrestricted_guest) {
1444                 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1445                 vmx->rflags = rflags;
1446                 vmcs_writel(GUEST_RFLAGS, rflags);
1447                 return;
1448         }
1449
1450         old_rflags = vmx_get_rflags(vcpu);
1451         vmx->rflags = rflags;
1452         if (vmx->rmode.vm86_active) {
1453                 vmx->rmode.save_rflags = rflags;
1454                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1455         }
1456         vmcs_writel(GUEST_RFLAGS, rflags);
1457
1458         if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1459                 vmx->emulation_required = emulation_required(vcpu);
1460 }
1461
1462 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1463 {
1464         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1465         int ret = 0;
1466
1467         if (interruptibility & GUEST_INTR_STATE_STI)
1468                 ret |= KVM_X86_SHADOW_INT_STI;
1469         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1470                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1471
1472         return ret;
1473 }
1474
1475 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1476 {
1477         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1478         u32 interruptibility = interruptibility_old;
1479
1480         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1481
1482         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1483                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1484         else if (mask & KVM_X86_SHADOW_INT_STI)
1485                 interruptibility |= GUEST_INTR_STATE_STI;
1486
1487         if ((interruptibility != interruptibility_old))
1488                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1489 }
1490
1491 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1492 {
1493         struct vcpu_vmx *vmx = to_vmx(vcpu);
1494         unsigned long value;
1495
1496         /*
1497          * Any MSR write that attempts to change bits marked reserved will
1498          * case a #GP fault.
1499          */
1500         if (data & vmx->pt_desc.ctl_bitmask)
1501                 return 1;
1502
1503         /*
1504          * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1505          * result in a #GP unless the same write also clears TraceEn.
1506          */
1507         if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1508                 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1509                 return 1;
1510
1511         /*
1512          * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1513          * and FabricEn would cause #GP, if
1514          * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1515          */
1516         if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1517                 !(data & RTIT_CTL_FABRIC_EN) &&
1518                 !intel_pt_validate_cap(vmx->pt_desc.caps,
1519                                         PT_CAP_single_range_output))
1520                 return 1;
1521
1522         /*
1523          * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1524          * utilize encodings marked reserved will casue a #GP fault.
1525          */
1526         value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1527         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1528                         !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1529                         RTIT_CTL_MTC_RANGE_OFFSET, &value))
1530                 return 1;
1531         value = intel_pt_validate_cap(vmx->pt_desc.caps,
1532                                                 PT_CAP_cycle_thresholds);
1533         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1534                         !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1535                         RTIT_CTL_CYC_THRESH_OFFSET, &value))
1536                 return 1;
1537         value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1538         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1539                         !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1540                         RTIT_CTL_PSB_FREQ_OFFSET, &value))
1541                 return 1;
1542
1543         /*
1544          * If ADDRx_CFG is reserved or the encodings is >2 will
1545          * cause a #GP fault.
1546          */
1547         value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1548         if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1549                 return 1;
1550         value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1551         if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1552                 return 1;
1553         value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1554         if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1555                 return 1;
1556         value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1557         if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1558                 return 1;
1559
1560         return 0;
1561 }
1562
1563 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1564 {
1565         unsigned long rip, orig_rip;
1566
1567         /*
1568          * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1569          * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1570          * set when EPT misconfig occurs.  In practice, real hardware updates
1571          * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1572          * (namely Hyper-V) don't set it due to it being undefined behavior,
1573          * i.e. we end up advancing IP with some random value.
1574          */
1575         if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1576             to_vmx(vcpu)->exit_reason != EXIT_REASON_EPT_MISCONFIG) {
1577                 orig_rip = kvm_rip_read(vcpu);
1578                 rip = orig_rip + vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1579 #ifdef CONFIG_X86_64
1580                 /*
1581                  * We need to mask out the high 32 bits of RIP if not in 64-bit
1582                  * mode, but just finding out that we are in 64-bit mode is
1583                  * quite expensive.  Only do it if there was a carry.
1584                  */
1585                 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1586                         rip = (u32)rip;
1587 #endif
1588                 kvm_rip_write(vcpu, rip);
1589         } else {
1590                 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1591                         return 0;
1592         }
1593
1594         /* skipping an emulated instruction also counts */
1595         vmx_set_interrupt_shadow(vcpu, 0);
1596
1597         return 1;
1598 }
1599
1600 /*
1601  * Handles kvm_read/write_guest_virt*() result and either injects #PF or returns
1602  * KVM_EXIT_INTERNAL_ERROR for cases not currently handled by KVM. Return value
1603  * indicates whether exit to userspace is needed.
1604  */
1605 int vmx_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
1606                               struct x86_exception *e)
1607 {
1608         if (r == X86EMUL_PROPAGATE_FAULT) {
1609                 kvm_inject_emulated_page_fault(vcpu, e);
1610                 return 1;
1611         }
1612
1613         /*
1614          * In case kvm_read/write_guest_virt*() failed with X86EMUL_IO_NEEDED
1615          * while handling a VMX instruction KVM could've handled the request
1616          * correctly by exiting to userspace and performing I/O but there
1617          * doesn't seem to be a real use-case behind such requests, just return
1618          * KVM_EXIT_INTERNAL_ERROR for now.
1619          */
1620         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1621         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
1622         vcpu->run->internal.ndata = 0;
1623
1624         return 0;
1625 }
1626
1627 /*
1628  * Recognizes a pending MTF VM-exit and records the nested state for later
1629  * delivery.
1630  */
1631 static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1632 {
1633         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1634         struct vcpu_vmx *vmx = to_vmx(vcpu);
1635
1636         if (!is_guest_mode(vcpu))
1637                 return;
1638
1639         /*
1640          * Per the SDM, MTF takes priority over debug-trap exceptions besides
1641          * T-bit traps. As instruction emulation is completed (i.e. at the
1642          * instruction boundary), any #DB exception pending delivery must be a
1643          * debug-trap. Record the pending MTF state to be delivered in
1644          * vmx_check_nested_events().
1645          */
1646         if (nested_cpu_has_mtf(vmcs12) &&
1647             (!vcpu->arch.exception.pending ||
1648              vcpu->arch.exception.nr == DB_VECTOR))
1649                 vmx->nested.mtf_pending = true;
1650         else
1651                 vmx->nested.mtf_pending = false;
1652 }
1653
1654 static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1655 {
1656         vmx_update_emulated_instruction(vcpu);
1657         return skip_emulated_instruction(vcpu);
1658 }
1659
1660 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1661 {
1662         /*
1663          * Ensure that we clear the HLT state in the VMCS.  We don't need to
1664          * explicitly skip the instruction because if the HLT state is set,
1665          * then the instruction is already executing and RIP has already been
1666          * advanced.
1667          */
1668         if (kvm_hlt_in_guest(vcpu->kvm) &&
1669                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1670                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1671 }
1672
1673 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1674 {
1675         struct vcpu_vmx *vmx = to_vmx(vcpu);
1676         unsigned nr = vcpu->arch.exception.nr;
1677         bool has_error_code = vcpu->arch.exception.has_error_code;
1678         u32 error_code = vcpu->arch.exception.error_code;
1679         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1680
1681         kvm_deliver_exception_payload(vcpu);
1682
1683         if (has_error_code) {
1684                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1685                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1686         }
1687
1688         if (vmx->rmode.vm86_active) {
1689                 int inc_eip = 0;
1690                 if (kvm_exception_is_soft(nr))
1691                         inc_eip = vcpu->arch.event_exit_inst_len;
1692                 kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1693                 return;
1694         }
1695
1696         WARN_ON_ONCE(vmx->emulation_required);
1697
1698         if (kvm_exception_is_soft(nr)) {
1699                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1700                              vmx->vcpu.arch.event_exit_inst_len);
1701                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1702         } else
1703                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1704
1705         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1706
1707         vmx_clear_hlt(vcpu);
1708 }
1709
1710 /*
1711  * Swap MSR entry in host/guest MSR entry array.
1712  */
1713 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1714 {
1715         struct shared_msr_entry tmp;
1716
1717         tmp = vmx->guest_msrs[to];
1718         vmx->guest_msrs[to] = vmx->guest_msrs[from];
1719         vmx->guest_msrs[from] = tmp;
1720 }
1721
1722 /*
1723  * Set up the vmcs to automatically save and restore system
1724  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1725  * mode, as fiddling with msrs is very expensive.
1726  */
1727 static void setup_msrs(struct vcpu_vmx *vmx)
1728 {
1729         int save_nmsrs, index;
1730
1731         save_nmsrs = 0;
1732 #ifdef CONFIG_X86_64
1733         /*
1734          * The SYSCALL MSRs are only needed on long mode guests, and only
1735          * when EFER.SCE is set.
1736          */
1737         if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1738                 index = __find_msr_index(vmx, MSR_STAR);
1739                 if (index >= 0)
1740                         move_msr_up(vmx, index, save_nmsrs++);
1741                 index = __find_msr_index(vmx, MSR_LSTAR);
1742                 if (index >= 0)
1743                         move_msr_up(vmx, index, save_nmsrs++);
1744                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1745                 if (index >= 0)
1746                         move_msr_up(vmx, index, save_nmsrs++);
1747         }
1748 #endif
1749         index = __find_msr_index(vmx, MSR_EFER);
1750         if (index >= 0 && update_transition_efer(vmx, index))
1751                 move_msr_up(vmx, index, save_nmsrs++);
1752         index = __find_msr_index(vmx, MSR_TSC_AUX);
1753         if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1754                 move_msr_up(vmx, index, save_nmsrs++);
1755         index = __find_msr_index(vmx, MSR_IA32_TSX_CTRL);
1756         if (index >= 0)
1757                 move_msr_up(vmx, index, save_nmsrs++);
1758
1759         vmx->save_nmsrs = save_nmsrs;
1760         vmx->guest_msrs_ready = false;
1761
1762         if (cpu_has_vmx_msr_bitmap())
1763                 vmx_update_msr_bitmap(&vmx->vcpu);
1764 }
1765
1766 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1767 {
1768         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1769         u64 g_tsc_offset = 0;
1770
1771         /*
1772          * We're here if L1 chose not to trap WRMSR to TSC. According
1773          * to the spec, this should set L1's TSC; The offset that L1
1774          * set for L2 remains unchanged, and still needs to be added
1775          * to the newly set TSC to get L2's TSC.
1776          */
1777         if (is_guest_mode(vcpu) &&
1778             (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
1779                 g_tsc_offset = vmcs12->tsc_offset;
1780
1781         trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1782                                    vcpu->arch.tsc_offset - g_tsc_offset,
1783                                    offset);
1784         vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1785         return offset + g_tsc_offset;
1786 }
1787
1788 /*
1789  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1790  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1791  * all guests if the "nested" module option is off, and can also be disabled
1792  * for a single guest by disabling its VMX cpuid bit.
1793  */
1794 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1795 {
1796         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1797 }
1798
1799 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1800                                                  uint64_t val)
1801 {
1802         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1803
1804         return !(val & ~valid_bits);
1805 }
1806
1807 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1808 {
1809         switch (msr->index) {
1810         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1811                 if (!nested)
1812                         return 1;
1813                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1814         case MSR_IA32_PERF_CAPABILITIES:
1815                 msr->data = vmx_get_perf_capabilities();
1816                 return 0;
1817         default:
1818                 return KVM_MSR_RET_INVALID;
1819         }
1820 }
1821
1822 /*
1823  * Reads an msr value (of 'msr_index') into 'pdata'.
1824  * Returns 0 on success, non-0 otherwise.
1825  * Assumes vcpu_load() was already called.
1826  */
1827 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1828 {
1829         struct vcpu_vmx *vmx = to_vmx(vcpu);
1830         struct shared_msr_entry *msr;
1831         u32 index;
1832
1833         switch (msr_info->index) {
1834 #ifdef CONFIG_X86_64
1835         case MSR_FS_BASE:
1836                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1837                 break;
1838         case MSR_GS_BASE:
1839                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1840                 break;
1841         case MSR_KERNEL_GS_BASE:
1842                 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1843                 break;
1844 #endif
1845         case MSR_EFER:
1846                 return kvm_get_msr_common(vcpu, msr_info);
1847         case MSR_IA32_TSX_CTRL:
1848                 if (!msr_info->host_initiated &&
1849                     !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1850                         return 1;
1851                 goto find_shared_msr;
1852         case MSR_IA32_UMWAIT_CONTROL:
1853                 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1854                         return 1;
1855
1856                 msr_info->data = vmx->msr_ia32_umwait_control;
1857                 break;
1858         case MSR_IA32_SPEC_CTRL:
1859                 if (!msr_info->host_initiated &&
1860                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1861                         return 1;
1862
1863                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1864                 break;
1865         case MSR_IA32_SYSENTER_CS:
1866                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1867                 break;
1868         case MSR_IA32_SYSENTER_EIP:
1869                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1870                 break;
1871         case MSR_IA32_SYSENTER_ESP:
1872                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1873                 break;
1874         case MSR_IA32_BNDCFGS:
1875                 if (!kvm_mpx_supported() ||
1876                     (!msr_info->host_initiated &&
1877                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1878                         return 1;
1879                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1880                 break;
1881         case MSR_IA32_MCG_EXT_CTL:
1882                 if (!msr_info->host_initiated &&
1883                     !(vmx->msr_ia32_feature_control &
1884                       FEAT_CTL_LMCE_ENABLED))
1885                         return 1;
1886                 msr_info->data = vcpu->arch.mcg_ext_ctl;
1887                 break;
1888         case MSR_IA32_FEAT_CTL:
1889                 msr_info->data = vmx->msr_ia32_feature_control;
1890                 break;
1891         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1892                 if (!nested_vmx_allowed(vcpu))
1893                         return 1;
1894                 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1895                                     &msr_info->data))
1896                         return 1;
1897                 /*
1898                  * Enlightened VMCS v1 doesn't have certain fields, but buggy
1899                  * Hyper-V versions are still trying to use corresponding
1900                  * features when they are exposed. Filter out the essential
1901                  * minimum.
1902                  */
1903                 if (!msr_info->host_initiated &&
1904                     vmx->nested.enlightened_vmcs_enabled)
1905                         nested_evmcs_filter_control_msr(msr_info->index,
1906                                                         &msr_info->data);
1907                 break;
1908         case MSR_IA32_RTIT_CTL:
1909                 if (!vmx_pt_mode_is_host_guest())
1910                         return 1;
1911                 msr_info->data = vmx->pt_desc.guest.ctl;
1912                 break;
1913         case MSR_IA32_RTIT_STATUS:
1914                 if (!vmx_pt_mode_is_host_guest())
1915                         return 1;
1916                 msr_info->data = vmx->pt_desc.guest.status;
1917                 break;
1918         case MSR_IA32_RTIT_CR3_MATCH:
1919                 if (!vmx_pt_mode_is_host_guest() ||
1920                         !intel_pt_validate_cap(vmx->pt_desc.caps,
1921                                                 PT_CAP_cr3_filtering))
1922                         return 1;
1923                 msr_info->data = vmx->pt_desc.guest.cr3_match;
1924                 break;
1925         case MSR_IA32_RTIT_OUTPUT_BASE:
1926                 if (!vmx_pt_mode_is_host_guest() ||
1927                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1928                                         PT_CAP_topa_output) &&
1929                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1930                                         PT_CAP_single_range_output)))
1931                         return 1;
1932                 msr_info->data = vmx->pt_desc.guest.output_base;
1933                 break;
1934         case MSR_IA32_RTIT_OUTPUT_MASK:
1935                 if (!vmx_pt_mode_is_host_guest() ||
1936                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1937                                         PT_CAP_topa_output) &&
1938                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1939                                         PT_CAP_single_range_output)))
1940                         return 1;
1941                 msr_info->data = vmx->pt_desc.guest.output_mask;
1942                 break;
1943         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1944                 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1945                 if (!vmx_pt_mode_is_host_guest() ||
1946                         (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1947                                         PT_CAP_num_address_ranges)))
1948                         return 1;
1949                 if (index % 2)
1950                         msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1951                 else
1952                         msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1953                 break;
1954         case MSR_TSC_AUX:
1955                 if (!msr_info->host_initiated &&
1956                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1957                         return 1;
1958                 goto find_shared_msr;
1959         default:
1960         find_shared_msr:
1961                 msr = find_msr_entry(vmx, msr_info->index);
1962                 if (msr) {
1963                         msr_info->data = msr->data;
1964                         break;
1965                 }
1966                 return kvm_get_msr_common(vcpu, msr_info);
1967         }
1968
1969         return 0;
1970 }
1971
1972 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1973                                                     u64 data)
1974 {
1975 #ifdef CONFIG_X86_64
1976         if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1977                 return (u32)data;
1978 #endif
1979         return (unsigned long)data;
1980 }
1981
1982 /*
1983  * Writes msr value into the appropriate "register".
1984  * Returns 0 on success, non-0 otherwise.
1985  * Assumes vcpu_load() was already called.
1986  */
1987 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1988 {
1989         struct vcpu_vmx *vmx = to_vmx(vcpu);
1990         struct shared_msr_entry *msr;
1991         int ret = 0;
1992         u32 msr_index = msr_info->index;
1993         u64 data = msr_info->data;
1994         u32 index;
1995
1996         switch (msr_index) {
1997         case MSR_EFER:
1998                 ret = kvm_set_msr_common(vcpu, msr_info);
1999                 break;
2000 #ifdef CONFIG_X86_64
2001         case MSR_FS_BASE:
2002                 vmx_segment_cache_clear(vmx);
2003                 vmcs_writel(GUEST_FS_BASE, data);
2004                 break;
2005         case MSR_GS_BASE:
2006                 vmx_segment_cache_clear(vmx);
2007                 vmcs_writel(GUEST_GS_BASE, data);
2008                 break;
2009         case MSR_KERNEL_GS_BASE:
2010                 vmx_write_guest_kernel_gs_base(vmx, data);
2011                 break;
2012 #endif
2013         case MSR_IA32_SYSENTER_CS:
2014                 if (is_guest_mode(vcpu))
2015                         get_vmcs12(vcpu)->guest_sysenter_cs = data;
2016                 vmcs_write32(GUEST_SYSENTER_CS, data);
2017                 break;
2018         case MSR_IA32_SYSENTER_EIP:
2019                 if (is_guest_mode(vcpu)) {
2020                         data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2021                         get_vmcs12(vcpu)->guest_sysenter_eip = data;
2022                 }
2023                 vmcs_writel(GUEST_SYSENTER_EIP, data);
2024                 break;
2025         case MSR_IA32_SYSENTER_ESP:
2026                 if (is_guest_mode(vcpu)) {
2027                         data = nested_vmx_truncate_sysenter_addr(vcpu, data);
2028                         get_vmcs12(vcpu)->guest_sysenter_esp = data;
2029                 }
2030                 vmcs_writel(GUEST_SYSENTER_ESP, data);
2031                 break;
2032         case MSR_IA32_DEBUGCTLMSR:
2033                 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2034                                                 VM_EXIT_SAVE_DEBUG_CONTROLS)
2035                         get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2036
2037                 ret = kvm_set_msr_common(vcpu, msr_info);
2038                 break;
2039
2040         case MSR_IA32_BNDCFGS:
2041                 if (!kvm_mpx_supported() ||
2042                     (!msr_info->host_initiated &&
2043                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2044                         return 1;
2045                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2046                     (data & MSR_IA32_BNDCFGS_RSVD))
2047                         return 1;
2048                 vmcs_write64(GUEST_BNDCFGS, data);
2049                 break;
2050         case MSR_IA32_UMWAIT_CONTROL:
2051                 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2052                         return 1;
2053
2054                 /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2055                 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2056                         return 1;
2057
2058                 vmx->msr_ia32_umwait_control = data;
2059                 break;
2060         case MSR_IA32_SPEC_CTRL:
2061                 if (!msr_info->host_initiated &&
2062                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2063                         return 1;
2064
2065                 if (kvm_spec_ctrl_test_value(data))
2066                         return 1;
2067
2068                 vmx->spec_ctrl = data;
2069                 if (!data)
2070                         break;
2071
2072                 /*
2073                  * For non-nested:
2074                  * When it's written (to non-zero) for the first time, pass
2075                  * it through.
2076                  *
2077                  * For nested:
2078                  * The handling of the MSR bitmap for L2 guests is done in
2079                  * nested_vmx_prepare_msr_bitmap. We should not touch the
2080                  * vmcs02.msr_bitmap here since it gets completely overwritten
2081                  * in the merging. We update the vmcs01 here for L1 as well
2082                  * since it will end up touching the MSR anyway now.
2083                  */
2084                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
2085                                               MSR_IA32_SPEC_CTRL,
2086                                               MSR_TYPE_RW);
2087                 break;
2088         case MSR_IA32_TSX_CTRL:
2089                 if (!msr_info->host_initiated &&
2090                     !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2091                         return 1;
2092                 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2093                         return 1;
2094                 goto find_shared_msr;
2095         case MSR_IA32_PRED_CMD:
2096                 if (!msr_info->host_initiated &&
2097                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
2098                         return 1;
2099
2100                 if (data & ~PRED_CMD_IBPB)
2101                         return 1;
2102                 if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL))
2103                         return 1;
2104                 if (!data)
2105                         break;
2106
2107                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2108
2109                 /*
2110                  * For non-nested:
2111                  * When it's written (to non-zero) for the first time, pass
2112                  * it through.
2113                  *
2114                  * For nested:
2115                  * The handling of the MSR bitmap for L2 guests is done in
2116                  * nested_vmx_prepare_msr_bitmap. We should not touch the
2117                  * vmcs02.msr_bitmap here since it gets completely overwritten
2118                  * in the merging.
2119                  */
2120                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
2121                                               MSR_TYPE_W);
2122                 break;
2123         case MSR_IA32_CR_PAT:
2124                 if (!kvm_pat_valid(data))
2125                         return 1;
2126
2127                 if (is_guest_mode(vcpu) &&
2128                     get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2129                         get_vmcs12(vcpu)->guest_ia32_pat = data;
2130
2131                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2132                         vmcs_write64(GUEST_IA32_PAT, data);
2133                         vcpu->arch.pat = data;
2134                         break;
2135                 }
2136                 ret = kvm_set_msr_common(vcpu, msr_info);
2137                 break;
2138         case MSR_IA32_TSC_ADJUST:
2139                 ret = kvm_set_msr_common(vcpu, msr_info);
2140                 break;
2141         case MSR_IA32_MCG_EXT_CTL:
2142                 if ((!msr_info->host_initiated &&
2143                      !(to_vmx(vcpu)->msr_ia32_feature_control &
2144                        FEAT_CTL_LMCE_ENABLED)) ||
2145                     (data & ~MCG_EXT_CTL_LMCE_EN))
2146                         return 1;
2147                 vcpu->arch.mcg_ext_ctl = data;
2148                 break;
2149         case MSR_IA32_FEAT_CTL:
2150                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
2151                     (to_vmx(vcpu)->msr_ia32_feature_control &
2152                      FEAT_CTL_LOCKED && !msr_info->host_initiated))
2153                         return 1;
2154                 vmx->msr_ia32_feature_control = data;
2155                 if (msr_info->host_initiated && data == 0)
2156                         vmx_leave_nested(vcpu);
2157                 break;
2158         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2159                 if (!msr_info->host_initiated)
2160                         return 1; /* they are read-only */
2161                 if (!nested_vmx_allowed(vcpu))
2162                         return 1;
2163                 return vmx_set_vmx_msr(vcpu, msr_index, data);
2164         case MSR_IA32_RTIT_CTL:
2165                 if (!vmx_pt_mode_is_host_guest() ||
2166                         vmx_rtit_ctl_check(vcpu, data) ||
2167                         vmx->nested.vmxon)
2168                         return 1;
2169                 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2170                 vmx->pt_desc.guest.ctl = data;
2171                 pt_update_intercept_for_msr(vmx);
2172                 break;
2173         case MSR_IA32_RTIT_STATUS:
2174                 if (!pt_can_write_msr(vmx))
2175                         return 1;
2176                 if (data & MSR_IA32_RTIT_STATUS_MASK)
2177                         return 1;
2178                 vmx->pt_desc.guest.status = data;
2179                 break;
2180         case MSR_IA32_RTIT_CR3_MATCH:
2181                 if (!pt_can_write_msr(vmx))
2182                         return 1;
2183                 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2184                                            PT_CAP_cr3_filtering))
2185                         return 1;
2186                 vmx->pt_desc.guest.cr3_match = data;
2187                 break;
2188         case MSR_IA32_RTIT_OUTPUT_BASE:
2189                 if (!pt_can_write_msr(vmx))
2190                         return 1;
2191                 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2192                                            PT_CAP_topa_output) &&
2193                     !intel_pt_validate_cap(vmx->pt_desc.caps,
2194                                            PT_CAP_single_range_output))
2195                         return 1;
2196                 if (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK)
2197                         return 1;
2198                 vmx->pt_desc.guest.output_base = data;
2199                 break;
2200         case MSR_IA32_RTIT_OUTPUT_MASK:
2201                 if (!pt_can_write_msr(vmx))
2202                         return 1;
2203                 if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2204                                            PT_CAP_topa_output) &&
2205                     !intel_pt_validate_cap(vmx->pt_desc.caps,
2206                                            PT_CAP_single_range_output))
2207                         return 1;
2208                 vmx->pt_desc.guest.output_mask = data;
2209                 break;
2210         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2211                 if (!pt_can_write_msr(vmx))
2212                         return 1;
2213                 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2214                 if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2215                                                        PT_CAP_num_address_ranges))
2216                         return 1;
2217                 if (is_noncanonical_address(data, vcpu))
2218                         return 1;
2219                 if (index % 2)
2220                         vmx->pt_desc.guest.addr_b[index / 2] = data;
2221                 else
2222                         vmx->pt_desc.guest.addr_a[index / 2] = data;
2223                 break;
2224         case MSR_TSC_AUX:
2225                 if (!msr_info->host_initiated &&
2226                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2227                         return 1;
2228                 /* Check reserved bit, higher 32 bits should be zero */
2229                 if ((data >> 32) != 0)
2230                         return 1;
2231                 goto find_shared_msr;
2232
2233         default:
2234         find_shared_msr:
2235                 msr = find_msr_entry(vmx, msr_index);
2236                 if (msr)
2237                         ret = vmx_set_guest_msr(vmx, msr, data);
2238                 else
2239                         ret = kvm_set_msr_common(vcpu, msr_info);
2240         }
2241
2242         return ret;
2243 }
2244
2245 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2246 {
2247         unsigned long guest_owned_bits;
2248
2249         kvm_register_mark_available(vcpu, reg);
2250
2251         switch (reg) {
2252         case VCPU_REGS_RSP:
2253                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2254                 break;
2255         case VCPU_REGS_RIP:
2256                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2257                 break;
2258         case VCPU_EXREG_PDPTR:
2259                 if (enable_ept)
2260                         ept_save_pdptrs(vcpu);
2261                 break;
2262         case VCPU_EXREG_CR0:
2263                 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2264
2265                 vcpu->arch.cr0 &= ~guest_owned_bits;
2266                 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2267                 break;
2268         case VCPU_EXREG_CR3:
2269                 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2270                         vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2271                 break;
2272         case VCPU_EXREG_CR4:
2273                 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2274
2275                 vcpu->arch.cr4 &= ~guest_owned_bits;
2276                 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2277                 break;
2278         default:
2279                 WARN_ON_ONCE(1);
2280                 break;
2281         }
2282 }
2283
2284 static __init int cpu_has_kvm_support(void)
2285 {
2286         return cpu_has_vmx();
2287 }
2288
2289 static __init int vmx_disabled_by_bios(void)
2290 {
2291         return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2292                !boot_cpu_has(X86_FEATURE_VMX);
2293 }
2294
2295 static int kvm_cpu_vmxon(u64 vmxon_pointer)
2296 {
2297         u64 msr;
2298
2299         cr4_set_bits(X86_CR4_VMXE);
2300         intel_pt_handle_vmx(1);
2301
2302         asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2303                           _ASM_EXTABLE(1b, %l[fault])
2304                           : : [vmxon_pointer] "m"(vmxon_pointer)
2305                           : : fault);
2306         return 0;
2307
2308 fault:
2309         WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2310                   rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2311         intel_pt_handle_vmx(0);
2312         cr4_clear_bits(X86_CR4_VMXE);
2313
2314         return -EFAULT;
2315 }
2316
2317 static int hardware_enable(void)
2318 {
2319         int cpu = raw_smp_processor_id();
2320         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2321         int r;
2322
2323         if (cr4_read_shadow() & X86_CR4_VMXE)
2324                 return -EBUSY;
2325
2326         /*
2327          * This can happen if we hot-added a CPU but failed to allocate
2328          * VP assist page for it.
2329          */
2330         if (static_branch_unlikely(&enable_evmcs) &&
2331             !hv_get_vp_assist_page(cpu))
2332                 return -EFAULT;
2333
2334         r = kvm_cpu_vmxon(phys_addr);
2335         if (r)
2336                 return r;
2337
2338         if (enable_ept)
2339                 ept_sync_global();
2340
2341         return 0;
2342 }
2343
2344 static void vmclear_local_loaded_vmcss(void)
2345 {
2346         int cpu = raw_smp_processor_id();
2347         struct loaded_vmcs *v, *n;
2348
2349         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2350                                  loaded_vmcss_on_cpu_link)
2351                 __loaded_vmcs_clear(v);
2352 }
2353
2354
2355 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2356  * tricks.
2357  */
2358 static void kvm_cpu_vmxoff(void)
2359 {
2360         asm volatile (__ex("vmxoff"));
2361
2362         intel_pt_handle_vmx(0);
2363         cr4_clear_bits(X86_CR4_VMXE);
2364 }
2365
2366 static void hardware_disable(void)
2367 {
2368         vmclear_local_loaded_vmcss();
2369         kvm_cpu_vmxoff();
2370 }
2371
2372 /*
2373  * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2374  * directly instead of going through cpu_has(), to ensure KVM is trapping
2375  * ENCLS whenever it's supported in hardware.  It does not matter whether
2376  * the host OS supports or has enabled SGX.
2377  */
2378 static bool cpu_has_sgx(void)
2379 {
2380         return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2381 }
2382
2383 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2384                                       u32 msr, u32 *result)
2385 {
2386         u32 vmx_msr_low, vmx_msr_high;
2387         u32 ctl = ctl_min | ctl_opt;
2388
2389         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2390
2391         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2392         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2393
2394         /* Ensure minimum (required) set of control bits are supported. */
2395         if (ctl_min & ~ctl)
2396                 return -EIO;
2397
2398         *result = ctl;
2399         return 0;
2400 }
2401
2402 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2403                                     struct vmx_capability *vmx_cap)
2404 {
2405         u32 vmx_msr_low, vmx_msr_high;
2406         u32 min, opt, min2, opt2;
2407         u32 _pin_based_exec_control = 0;
2408         u32 _cpu_based_exec_control = 0;
2409         u32 _cpu_based_2nd_exec_control = 0;
2410         u32 _vmexit_control = 0;
2411         u32 _vmentry_control = 0;
2412
2413         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2414         min = CPU_BASED_HLT_EXITING |
2415 #ifdef CONFIG_X86_64
2416               CPU_BASED_CR8_LOAD_EXITING |
2417               CPU_BASED_CR8_STORE_EXITING |
2418 #endif
2419               CPU_BASED_CR3_LOAD_EXITING |
2420               CPU_BASED_CR3_STORE_EXITING |
2421               CPU_BASED_UNCOND_IO_EXITING |
2422               CPU_BASED_MOV_DR_EXITING |
2423               CPU_BASED_USE_TSC_OFFSETTING |
2424               CPU_BASED_MWAIT_EXITING |
2425               CPU_BASED_MONITOR_EXITING |
2426               CPU_BASED_INVLPG_EXITING |
2427               CPU_BASED_RDPMC_EXITING;
2428
2429         opt = CPU_BASED_TPR_SHADOW |
2430               CPU_BASED_USE_MSR_BITMAPS |
2431               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2432         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2433                                 &_cpu_based_exec_control) < 0)
2434                 return -EIO;
2435 #ifdef CONFIG_X86_64
2436         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2437                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2438                                            ~CPU_BASED_CR8_STORE_EXITING;
2439 #endif
2440         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2441                 min2 = 0;
2442                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2443                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2444                         SECONDARY_EXEC_WBINVD_EXITING |
2445                         SECONDARY_EXEC_ENABLE_VPID |
2446                         SECONDARY_EXEC_ENABLE_EPT |
2447                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
2448                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2449                         SECONDARY_EXEC_DESC |
2450                         SECONDARY_EXEC_RDTSCP |
2451                         SECONDARY_EXEC_ENABLE_INVPCID |
2452                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
2453                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2454                         SECONDARY_EXEC_SHADOW_VMCS |
2455                         SECONDARY_EXEC_XSAVES |
2456                         SECONDARY_EXEC_RDSEED_EXITING |
2457                         SECONDARY_EXEC_RDRAND_EXITING |
2458                         SECONDARY_EXEC_ENABLE_PML |
2459                         SECONDARY_EXEC_TSC_SCALING |
2460                         SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2461                         SECONDARY_EXEC_PT_USE_GPA |
2462                         SECONDARY_EXEC_PT_CONCEAL_VMX |
2463                         SECONDARY_EXEC_ENABLE_VMFUNC;
2464                 if (cpu_has_sgx())
2465                         opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2466                 if (adjust_vmx_controls(min2, opt2,
2467                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2468                                         &_cpu_based_2nd_exec_control) < 0)
2469                         return -EIO;
2470         }
2471 #ifndef CONFIG_X86_64
2472         if (!(_cpu_based_2nd_exec_control &
2473                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2474                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2475 #endif
2476
2477         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2478                 _cpu_based_2nd_exec_control &= ~(
2479                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2480                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2481                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2482
2483         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2484                 &vmx_cap->ept, &vmx_cap->vpid);
2485
2486         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2487                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2488                    enabled */
2489                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2490                                              CPU_BASED_CR3_STORE_EXITING |
2491                                              CPU_BASED_INVLPG_EXITING);
2492         } else if (vmx_cap->ept) {
2493                 vmx_cap->ept = 0;
2494                 pr_warn_once("EPT CAP should not exist if not support "
2495                                 "1-setting enable EPT VM-execution control\n");
2496         }
2497         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2498                 vmx_cap->vpid) {
2499                 vmx_cap->vpid = 0;
2500                 pr_warn_once("VPID CAP should not exist if not support "
2501                                 "1-setting enable VPID VM-execution control\n");
2502         }
2503
2504         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2505 #ifdef CONFIG_X86_64
2506         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2507 #endif
2508         opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2509               VM_EXIT_LOAD_IA32_PAT |
2510               VM_EXIT_LOAD_IA32_EFER |
2511               VM_EXIT_CLEAR_BNDCFGS |
2512               VM_EXIT_PT_CONCEAL_PIP |
2513               VM_EXIT_CLEAR_IA32_RTIT_CTL;
2514         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2515                                 &_vmexit_control) < 0)
2516                 return -EIO;
2517
2518         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2519         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2520                  PIN_BASED_VMX_PREEMPTION_TIMER;
2521         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2522                                 &_pin_based_exec_control) < 0)
2523                 return -EIO;
2524
2525         if (cpu_has_broken_vmx_preemption_timer())
2526                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2527         if (!(_cpu_based_2nd_exec_control &
2528                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2529                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2530
2531         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2532         opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2533               VM_ENTRY_LOAD_IA32_PAT |
2534               VM_ENTRY_LOAD_IA32_EFER |
2535               VM_ENTRY_LOAD_BNDCFGS |
2536               VM_ENTRY_PT_CONCEAL_PIP |
2537               VM_ENTRY_LOAD_IA32_RTIT_CTL;
2538         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2539                                 &_vmentry_control) < 0)
2540                 return -EIO;
2541
2542         /*
2543          * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2544          * can't be used due to an errata where VM Exit may incorrectly clear
2545          * IA32_PERF_GLOBAL_CTRL[34:32].  Workaround the errata by using the
2546          * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2547          */
2548         if (boot_cpu_data.x86 == 0x6) {
2549                 switch (boot_cpu_data.x86_model) {
2550                 case 26: /* AAK155 */
2551                 case 30: /* AAP115 */
2552                 case 37: /* AAT100 */
2553                 case 44: /* BC86,AAY89,BD102 */
2554                 case 46: /* BA97 */
2555                         _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2556                         _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2557                         pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2558                                         "does not work properly. Using workaround\n");
2559                         break;
2560                 default:
2561                         break;
2562                 }
2563         }
2564
2565
2566         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2567
2568         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2569         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2570                 return -EIO;
2571
2572 #ifdef CONFIG_X86_64
2573         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2574         if (vmx_msr_high & (1u<<16))
2575                 return -EIO;
2576 #endif
2577
2578         /* Require Write-Back (WB) memory type for VMCS accesses. */
2579         if (((vmx_msr_high >> 18) & 15) != 6)
2580                 return -EIO;
2581
2582         vmcs_conf->size = vmx_msr_high & 0x1fff;
2583         vmcs_conf->order = get_order(vmcs_conf->size);
2584         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2585
2586         vmcs_conf->revision_id = vmx_msr_low;
2587
2588         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2589         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2590         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2591         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2592         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2593
2594         if (static_branch_unlikely(&enable_evmcs))
2595                 evmcs_sanitize_exec_ctrls(vmcs_conf);
2596
2597         return 0;
2598 }
2599
2600 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2601 {
2602         int node = cpu_to_node(cpu);
2603         struct page *pages;
2604         struct vmcs *vmcs;
2605
2606         pages = __alloc_pages_node(node, flags, vmcs_config.order);
2607         if (!pages)
2608                 return NULL;
2609         vmcs = page_address(pages);
2610         memset(vmcs, 0, vmcs_config.size);
2611
2612         /* KVM supports Enlightened VMCS v1 only */
2613         if (static_branch_unlikely(&enable_evmcs))
2614                 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2615         else
2616                 vmcs->hdr.revision_id = vmcs_config.revision_id;
2617
2618         if (shadow)
2619                 vmcs->hdr.shadow_vmcs = 1;
2620         return vmcs;
2621 }
2622
2623 void free_vmcs(struct vmcs *vmcs)
2624 {
2625         free_pages((unsigned long)vmcs, vmcs_config.order);
2626 }
2627
2628 /*
2629  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2630  */
2631 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2632 {
2633         if (!loaded_vmcs->vmcs)
2634                 return;
2635         loaded_vmcs_clear(loaded_vmcs);
2636         free_vmcs(loaded_vmcs->vmcs);
2637         loaded_vmcs->vmcs = NULL;
2638         if (loaded_vmcs->msr_bitmap)
2639                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2640         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2641 }
2642
2643 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2644 {
2645         loaded_vmcs->vmcs = alloc_vmcs(false);
2646         if (!loaded_vmcs->vmcs)
2647                 return -ENOMEM;
2648
2649         vmcs_clear(loaded_vmcs->vmcs);
2650
2651         loaded_vmcs->shadow_vmcs = NULL;
2652         loaded_vmcs->hv_timer_soft_disabled = false;
2653         loaded_vmcs->cpu = -1;
2654         loaded_vmcs->launched = 0;
2655
2656         if (cpu_has_vmx_msr_bitmap()) {
2657                 loaded_vmcs->msr_bitmap = (unsigned long *)
2658                                 __get_free_page(GFP_KERNEL_ACCOUNT);
2659                 if (!loaded_vmcs->msr_bitmap)
2660                         goto out_vmcs;
2661                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2662
2663                 if (IS_ENABLED(CONFIG_HYPERV) &&
2664                     static_branch_unlikely(&enable_evmcs) &&
2665                     (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2666                         struct hv_enlightened_vmcs *evmcs =
2667                                 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2668
2669                         evmcs->hv_enlightenments_control.msr_bitmap = 1;
2670                 }
2671         }
2672
2673         memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2674         memset(&loaded_vmcs->controls_shadow, 0,
2675                 sizeof(struct vmcs_controls_shadow));
2676
2677         return 0;
2678
2679 out_vmcs:
2680         free_loaded_vmcs(loaded_vmcs);
2681         return -ENOMEM;
2682 }
2683
2684 static void free_kvm_area(void)
2685 {
2686         int cpu;
2687
2688         for_each_possible_cpu(cpu) {
2689                 free_vmcs(per_cpu(vmxarea, cpu));
2690                 per_cpu(vmxarea, cpu) = NULL;
2691         }
2692 }
2693
2694 static __init int alloc_kvm_area(void)
2695 {
2696         int cpu;
2697
2698         for_each_possible_cpu(cpu) {
2699                 struct vmcs *vmcs;
2700
2701                 vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2702                 if (!vmcs) {
2703                         free_kvm_area();
2704                         return -ENOMEM;
2705                 }
2706
2707                 /*
2708                  * When eVMCS is enabled, alloc_vmcs_cpu() sets
2709                  * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2710                  * revision_id reported by MSR_IA32_VMX_BASIC.
2711                  *
2712                  * However, even though not explicitly documented by
2713                  * TLFS, VMXArea passed as VMXON argument should
2714                  * still be marked with revision_id reported by
2715                  * physical CPU.
2716                  */
2717                 if (static_branch_unlikely(&enable_evmcs))
2718                         vmcs->hdr.revision_id = vmcs_config.revision_id;
2719
2720                 per_cpu(vmxarea, cpu) = vmcs;
2721         }
2722         return 0;
2723 }
2724
2725 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2726                 struct kvm_segment *save)
2727 {
2728         if (!emulate_invalid_guest_state) {
2729                 /*
2730                  * CS and SS RPL should be equal during guest entry according
2731                  * to VMX spec, but in reality it is not always so. Since vcpu
2732                  * is in the middle of the transition from real mode to
2733                  * protected mode it is safe to assume that RPL 0 is a good
2734                  * default value.
2735                  */
2736                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2737                         save->selector &= ~SEGMENT_RPL_MASK;
2738                 save->dpl = save->selector & SEGMENT_RPL_MASK;
2739                 save->s = 1;
2740         }
2741         vmx_set_segment(vcpu, save, seg);
2742 }
2743
2744 static void enter_pmode(struct kvm_vcpu *vcpu)
2745 {
2746         unsigned long flags;
2747         struct vcpu_vmx *vmx = to_vmx(vcpu);
2748
2749         /*
2750          * Update real mode segment cache. It may be not up-to-date if sement
2751          * register was written while vcpu was in a guest mode.
2752          */
2753         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2754         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2755         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2756         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2757         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2758         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2759
2760         vmx->rmode.vm86_active = 0;
2761
2762         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2763
2764         flags = vmcs_readl(GUEST_RFLAGS);
2765         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2766         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2767         vmcs_writel(GUEST_RFLAGS, flags);
2768
2769         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2770                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2771
2772         update_exception_bitmap(vcpu);
2773
2774         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2775         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2776         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2777         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2778         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2779         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2780 }
2781
2782 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2783 {
2784         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2785         struct kvm_segment var = *save;
2786
2787         var.dpl = 0x3;
2788         if (seg == VCPU_SREG_CS)
2789                 var.type = 0x3;
2790
2791         if (!emulate_invalid_guest_state) {
2792                 var.selector = var.base >> 4;
2793                 var.base = var.base & 0xffff0;
2794                 var.limit = 0xffff;
2795                 var.g = 0;
2796                 var.db = 0;
2797                 var.present = 1;
2798                 var.s = 1;
2799                 var.l = 0;
2800                 var.unusable = 0;
2801                 var.type = 0x3;
2802                 var.avl = 0;
2803                 if (save->base & 0xf)
2804                         printk_once(KERN_WARNING "kvm: segment base is not "
2805                                         "paragraph aligned when entering "
2806                                         "protected mode (seg=%d)", seg);
2807         }
2808
2809         vmcs_write16(sf->selector, var.selector);
2810         vmcs_writel(sf->base, var.base);
2811         vmcs_write32(sf->limit, var.limit);
2812         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2813 }
2814
2815 static void enter_rmode(struct kvm_vcpu *vcpu)
2816 {
2817         unsigned long flags;
2818         struct vcpu_vmx *vmx = to_vmx(vcpu);
2819         struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2820
2821         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2822         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2823         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2824         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2825         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2826         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2827         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2828
2829         vmx->rmode.vm86_active = 1;
2830
2831         /*
2832          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2833          * vcpu. Warn the user that an update is overdue.
2834          */
2835         if (!kvm_vmx->tss_addr)
2836                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2837                              "called before entering vcpu\n");
2838
2839         vmx_segment_cache_clear(vmx);
2840
2841         vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2842         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2843         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2844
2845         flags = vmcs_readl(GUEST_RFLAGS);
2846         vmx->rmode.save_rflags = flags;
2847
2848         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2849
2850         vmcs_writel(GUEST_RFLAGS, flags);
2851         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2852         update_exception_bitmap(vcpu);
2853
2854         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2855         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2856         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2857         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2858         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2859         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2860
2861         kvm_mmu_reset_context(vcpu);
2862 }
2863
2864 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2865 {
2866         struct vcpu_vmx *vmx = to_vmx(vcpu);
2867         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2868
2869         if (!msr)
2870                 return;
2871
2872         vcpu->arch.efer = efer;
2873         if (efer & EFER_LMA) {
2874                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2875                 msr->data = efer;
2876         } else {
2877                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2878
2879                 msr->data = efer & ~EFER_LME;
2880         }
2881         setup_msrs(vmx);
2882 }
2883
2884 #ifdef CONFIG_X86_64
2885
2886 static void enter_lmode(struct kvm_vcpu *vcpu)
2887 {
2888         u32 guest_tr_ar;
2889
2890         vmx_segment_cache_clear(to_vmx(vcpu));
2891
2892         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2893         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2894                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2895                                      __func__);
2896                 vmcs_write32(GUEST_TR_AR_BYTES,
2897                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2898                              | VMX_AR_TYPE_BUSY_64_TSS);
2899         }
2900         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2901 }
2902
2903 static void exit_lmode(struct kvm_vcpu *vcpu)
2904 {
2905         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2906         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2907 }
2908
2909 #endif
2910
2911 static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2912 {
2913         struct vcpu_vmx *vmx = to_vmx(vcpu);
2914
2915         /*
2916          * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2917          * the CPU is not required to invalidate guest-physical mappings on
2918          * VM-Entry, even if VPID is disabled.  Guest-physical mappings are
2919          * associated with the root EPT structure and not any particular VPID
2920          * (INVVPID also isn't required to invalidate guest-physical mappings).
2921          */
2922         if (enable_ept) {
2923                 ept_sync_global();
2924         } else if (enable_vpid) {
2925                 if (cpu_has_vmx_invvpid_global()) {
2926                         vpid_sync_vcpu_global();
2927                 } else {
2928                         vpid_sync_vcpu_single(vmx->vpid);
2929                         vpid_sync_vcpu_single(vmx->nested.vpid02);
2930                 }
2931         }
2932 }
2933
2934 static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2935 {
2936         u64 root_hpa = vcpu->arch.mmu->root_hpa;
2937
2938         /* No flush required if the current context is invalid. */
2939         if (!VALID_PAGE(root_hpa))
2940                 return;
2941
2942         if (enable_ept)
2943                 ept_sync_context(construct_eptp(vcpu, root_hpa));
2944         else if (!is_guest_mode(vcpu))
2945                 vpid_sync_context(to_vmx(vcpu)->vpid);
2946         else
2947                 vpid_sync_context(nested_get_vpid02(vcpu));
2948 }
2949
2950 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2951 {
2952         /*
2953          * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2954          * vmx_flush_tlb_guest() for an explanation of why this is ok.
2955          */
2956         vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
2957 }
2958
2959 static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2960 {
2961         /*
2962          * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2963          * or a vpid couldn't be allocated for this vCPU.  VM-Enter and VM-Exit
2964          * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2965          * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2966          * i.e. no explicit INVVPID is necessary.
2967          */
2968         vpid_sync_context(to_vmx(vcpu)->vpid);
2969 }
2970
2971 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2972 {
2973         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2974
2975         if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
2976                 return;
2977
2978         if (is_pae_paging(vcpu)) {
2979                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2980                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2981                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2982                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2983         }
2984 }
2985
2986 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2987 {
2988         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2989
2990         if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
2991                 return;
2992
2993         mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2994         mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2995         mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2996         mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2997
2998         kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
2999 }
3000
3001 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3002                                         unsigned long cr0,
3003                                         struct kvm_vcpu *vcpu)
3004 {
3005         struct vcpu_vmx *vmx = to_vmx(vcpu);
3006
3007         if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3008                 vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3009         if (!(cr0 & X86_CR0_PG)) {
3010                 /* From paging/starting to nonpaging */
3011                 exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3012                                           CPU_BASED_CR3_STORE_EXITING);
3013                 vcpu->arch.cr0 = cr0;
3014                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3015         } else if (!is_paging(vcpu)) {
3016                 /* From nonpaging to paging */
3017                 exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3018                                             CPU_BASED_CR3_STORE_EXITING);
3019                 vcpu->arch.cr0 = cr0;
3020                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3021         }
3022
3023         if (!(cr0 & X86_CR0_WP))
3024                 *hw_cr0 &= ~X86_CR0_WP;
3025 }
3026
3027 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3028 {
3029         struct vcpu_vmx *vmx = to_vmx(vcpu);
3030         unsigned long hw_cr0;
3031
3032         hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3033         if (enable_unrestricted_guest)
3034                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3035         else {
3036                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3037
3038                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3039                         enter_pmode(vcpu);
3040
3041                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3042                         enter_rmode(vcpu);
3043         }
3044
3045 #ifdef CONFIG_X86_64
3046         if (vcpu->arch.efer & EFER_LME) {
3047                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3048                         enter_lmode(vcpu);
3049                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3050                         exit_lmode(vcpu);
3051         }
3052 #endif
3053
3054         if (enable_ept && !enable_unrestricted_guest)
3055                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3056
3057         vmcs_writel(CR0_READ_SHADOW, cr0);
3058         vmcs_writel(GUEST_CR0, hw_cr0);
3059         vcpu->arch.cr0 = cr0;
3060         kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3061
3062         /* depends on vcpu->arch.cr0 to be set to a new value */
3063         vmx->emulation_required = emulation_required(vcpu);
3064 }
3065
3066 static int vmx_get_tdp_level(struct kvm_vcpu *vcpu)
3067 {
3068         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
3069                 return 5;
3070         return 4;
3071 }
3072
3073 static int get_ept_level(struct kvm_vcpu *vcpu)
3074 {
3075         if (is_guest_mode(vcpu) && nested_cpu_has_ept(get_vmcs12(vcpu)))
3076                 return vmx_eptp_page_walk_level(nested_ept_get_eptp(vcpu));
3077
3078         return vmx_get_tdp_level(vcpu);
3079 }
3080
3081 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
3082 {
3083         u64 eptp = VMX_EPTP_MT_WB;
3084
3085         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3086
3087         if (enable_ept_ad_bits &&
3088             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3089                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
3090         eptp |= (root_hpa & PAGE_MASK);
3091
3092         return eptp;
3093 }
3094
3095 static 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          * If EPT is enabled, #PF is only trapped if MAXPHYADDR is mismatched
4361          * between guest and host.  In that case we only care about present
4362          * faults.
4363          */
4364         if (enable_ept) {
4365                 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, PFERR_PRESENT_MASK);
4366                 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, PFERR_PRESENT_MASK);
4367         }
4368 }
4369
4370 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4371 {
4372         struct vcpu_vmx *vmx = to_vmx(vcpu);
4373         struct msr_data apic_base_msr;
4374         u64 cr0;
4375
4376         vmx->rmode.vm86_active = 0;
4377         vmx->spec_ctrl = 0;
4378
4379         vmx->msr_ia32_umwait_control = 0;
4380
4381         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4382         vmx->hv_deadline_tsc = -1;
4383         kvm_set_cr8(vcpu, 0);
4384
4385         if (!init_event) {
4386                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4387                                      MSR_IA32_APICBASE_ENABLE;
4388                 if (kvm_vcpu_is_reset_bsp(vcpu))
4389                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4390                 apic_base_msr.host_initiated = true;
4391                 kvm_set_apic_base(vcpu, &apic_base_msr);
4392         }
4393
4394         vmx_segment_cache_clear(vmx);
4395
4396         seg_setup(VCPU_SREG_CS);
4397         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4398         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4399
4400         seg_setup(VCPU_SREG_DS);
4401         seg_setup(VCPU_SREG_ES);
4402         seg_setup(VCPU_SREG_FS);
4403         seg_setup(VCPU_SREG_GS);
4404         seg_setup(VCPU_SREG_SS);
4405
4406         vmcs_write16(GUEST_TR_SELECTOR, 0);
4407         vmcs_writel(GUEST_TR_BASE, 0);
4408         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4409         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4410
4411         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4412         vmcs_writel(GUEST_LDTR_BASE, 0);
4413         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4414         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4415
4416         if (!init_event) {
4417                 vmcs_write32(GUEST_SYSENTER_CS, 0);
4418                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4419                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4420                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4421         }
4422
4423         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4424         kvm_rip_write(vcpu, 0xfff0);
4425
4426         vmcs_writel(GUEST_GDTR_BASE, 0);
4427         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4428
4429         vmcs_writel(GUEST_IDTR_BASE, 0);
4430         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4431
4432         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4433         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4434         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4435         if (kvm_mpx_supported())
4436                 vmcs_write64(GUEST_BNDCFGS, 0);
4437
4438         setup_msrs(vmx);
4439
4440         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4441
4442         if (cpu_has_vmx_tpr_shadow() && !init_event) {
4443                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4444                 if (cpu_need_tpr_shadow(vcpu))
4445                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4446                                      __pa(vcpu->arch.apic->regs));
4447                 vmcs_write32(TPR_THRESHOLD, 0);
4448         }
4449
4450         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4451
4452         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4453         vmx->vcpu.arch.cr0 = cr0;
4454         vmx_set_cr0(vcpu, cr0); /* enter rmode */
4455         vmx_set_cr4(vcpu, 0);
4456         vmx_set_efer(vcpu, 0);
4457
4458         update_exception_bitmap(vcpu);
4459
4460         vpid_sync_context(vmx->vpid);
4461         if (init_event)
4462                 vmx_clear_hlt(vcpu);
4463 }
4464
4465 static void enable_irq_window(struct kvm_vcpu *vcpu)
4466 {
4467         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
4468 }
4469
4470 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4471 {
4472         if (!enable_vnmi ||
4473             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4474                 enable_irq_window(vcpu);
4475                 return;
4476         }
4477
4478         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
4479 }
4480
4481 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4482 {
4483         struct vcpu_vmx *vmx = to_vmx(vcpu);
4484         uint32_t intr;
4485         int irq = vcpu->arch.interrupt.nr;
4486
4487         trace_kvm_inj_virq(irq);
4488
4489         ++vcpu->stat.irq_injections;
4490         if (vmx->rmode.vm86_active) {
4491                 int inc_eip = 0;
4492                 if (vcpu->arch.interrupt.soft)
4493                         inc_eip = vcpu->arch.event_exit_inst_len;
4494                 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip);
4495                 return;
4496         }
4497         intr = irq | INTR_INFO_VALID_MASK;
4498         if (vcpu->arch.interrupt.soft) {
4499                 intr |= INTR_TYPE_SOFT_INTR;
4500                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4501                              vmx->vcpu.arch.event_exit_inst_len);
4502         } else
4503                 intr |= INTR_TYPE_EXT_INTR;
4504         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4505
4506         vmx_clear_hlt(vcpu);
4507 }
4508
4509 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4510 {
4511         struct vcpu_vmx *vmx = to_vmx(vcpu);
4512
4513         if (!enable_vnmi) {
4514                 /*
4515                  * Tracking the NMI-blocked state in software is built upon
4516                  * finding the next open IRQ window. This, in turn, depends on
4517                  * well-behaving guests: They have to keep IRQs disabled at
4518                  * least as long as the NMI handler runs. Otherwise we may
4519                  * cause NMI nesting, maybe breaking the guest. But as this is
4520                  * highly unlikely, we can live with the residual risk.
4521                  */
4522                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4523                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4524         }
4525
4526         ++vcpu->stat.nmi_injections;
4527         vmx->loaded_vmcs->nmi_known_unmasked = false;
4528
4529         if (vmx->rmode.vm86_active) {
4530                 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0);
4531                 return;
4532         }
4533
4534         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4535                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4536
4537         vmx_clear_hlt(vcpu);
4538 }
4539
4540 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4541 {
4542         struct vcpu_vmx *vmx = to_vmx(vcpu);
4543         bool masked;
4544
4545         if (!enable_vnmi)
4546                 return vmx->loaded_vmcs->soft_vnmi_blocked;
4547         if (vmx->loaded_vmcs->nmi_known_unmasked)
4548                 return false;
4549         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4550         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4551         return masked;
4552 }
4553
4554 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4555 {
4556         struct vcpu_vmx *vmx = to_vmx(vcpu);
4557
4558         if (!enable_vnmi) {
4559                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4560                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4561                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
4562                 }
4563         } else {
4564                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4565                 if (masked)
4566                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4567                                       GUEST_INTR_STATE_NMI);
4568                 else
4569                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4570                                         GUEST_INTR_STATE_NMI);
4571         }
4572 }
4573
4574 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu)
4575 {
4576         if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4577                 return false;
4578
4579         if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4580                 return true;
4581
4582         return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4583                 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI |
4584                  GUEST_INTR_STATE_NMI));
4585 }
4586
4587 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4588 {
4589         if (to_vmx(vcpu)->nested.nested_run_pending)
4590                 return -EBUSY;
4591
4592         /* An NMI must not be injected into L2 if it's supposed to VM-Exit.  */
4593         if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu))
4594                 return -EBUSY;
4595
4596         return !vmx_nmi_blocked(vcpu);
4597 }
4598
4599 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu)
4600 {
4601         if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4602                 return false;
4603
4604         return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) ||
4605                (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4606                 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4607 }
4608
4609 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4610 {
4611         if (to_vmx(vcpu)->nested.nested_run_pending)
4612                 return -EBUSY;
4613
4614        /*
4615         * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
4616         * e.g. if the IRQ arrived asynchronously after checking nested events.
4617         */
4618         if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
4619                 return -EBUSY;
4620
4621         return !vmx_interrupt_blocked(vcpu);
4622 }
4623
4624 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4625 {
4626         int ret;
4627
4628         if (enable_unrestricted_guest)
4629                 return 0;
4630
4631         mutex_lock(&kvm->slots_lock);
4632         ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4633                                       PAGE_SIZE * 3);
4634         mutex_unlock(&kvm->slots_lock);
4635
4636         if (ret)
4637                 return ret;
4638         to_kvm_vmx(kvm)->tss_addr = addr;
4639         return init_rmode_tss(kvm);
4640 }
4641
4642 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4643 {
4644         to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4645         return 0;
4646 }
4647
4648 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4649 {
4650         switch (vec) {
4651         case BP_VECTOR:
4652                 /*
4653                  * Update instruction length as we may reinject the exception
4654                  * from user space while in guest debugging mode.
4655                  */
4656                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4657                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4658                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4659                         return false;
4660                 /* fall through */
4661         case DB_VECTOR:
4662                 return !(vcpu->guest_debug &
4663                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP));
4664         case DE_VECTOR:
4665         case OF_VECTOR:
4666         case BR_VECTOR:
4667         case UD_VECTOR:
4668         case DF_VECTOR:
4669         case SS_VECTOR:
4670         case GP_VECTOR:
4671         case MF_VECTOR:
4672                 return true;
4673         }
4674         return false;
4675 }
4676
4677 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4678                                   int vec, u32 err_code)
4679 {
4680         /*
4681          * Instruction with address size override prefix opcode 0x67
4682          * Cause the #SS fault with 0 error code in VM86 mode.
4683          */
4684         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4685                 if (kvm_emulate_instruction(vcpu, 0)) {
4686                         if (vcpu->arch.halt_request) {
4687                                 vcpu->arch.halt_request = 0;
4688                                 return kvm_vcpu_halt(vcpu);
4689                         }
4690                         return 1;
4691                 }
4692                 return 0;
4693         }
4694
4695         /*
4696          * Forward all other exceptions that are valid in real mode.
4697          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4698          *        the required debugging infrastructure rework.
4699          */
4700         kvm_queue_exception(vcpu, vec);
4701         return 1;
4702 }
4703
4704 /*
4705  * Trigger machine check on the host. We assume all the MSRs are already set up
4706  * by the CPU and that we still run on the same CPU as the MCE occurred on.
4707  * We pass a fake environment to the machine check handler because we want
4708  * the guest to be always treated like user space, no matter what context
4709  * it used internally.
4710  */
4711 static void kvm_machine_check(void)
4712 {
4713 #if defined(CONFIG_X86_MCE)
4714         struct pt_regs regs = {
4715                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4716                 .flags = X86_EFLAGS_IF,
4717         };
4718
4719         do_machine_check(&regs);
4720 #endif
4721 }
4722
4723 static int handle_machine_check(struct kvm_vcpu *vcpu)
4724 {
4725         /* handled by vmx_vcpu_run() */
4726         return 1;
4727 }
4728
4729 /*
4730  * If the host has split lock detection disabled, then #AC is
4731  * unconditionally injected into the guest, which is the pre split lock
4732  * detection behaviour.
4733  *
4734  * If the host has split lock detection enabled then #AC is
4735  * only injected into the guest when:
4736  *  - Guest CPL == 3 (user mode)
4737  *  - Guest has #AC detection enabled in CR0
4738  *  - Guest EFLAGS has AC bit set
4739  */
4740 static inline bool guest_inject_ac(struct kvm_vcpu *vcpu)
4741 {
4742         if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT))
4743                 return true;
4744
4745         return vmx_get_cpl(vcpu) == 3 && kvm_read_cr0_bits(vcpu, X86_CR0_AM) &&
4746                (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
4747 }
4748
4749 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
4750 {
4751         struct vcpu_vmx *vmx = to_vmx(vcpu);
4752         struct kvm_run *kvm_run = vcpu->run;
4753         u32 intr_info, ex_no, error_code;
4754         unsigned long cr2, rip, dr6;
4755         u32 vect_info;
4756
4757         vect_info = vmx->idt_vectoring_info;
4758         intr_info = vmx_get_intr_info(vcpu);
4759
4760         if (is_machine_check(intr_info) || is_nmi(intr_info))
4761                 return 1; /* handled by handle_exception_nmi_irqoff() */
4762
4763         if (is_invalid_opcode(intr_info))
4764                 return handle_ud(vcpu);
4765
4766         error_code = 0;
4767         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4768                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4769
4770         if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4771                 WARN_ON_ONCE(!enable_vmware_backdoor);
4772
4773                 /*
4774                  * VMware backdoor emulation on #GP interception only handles
4775                  * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero
4776                  * error code on #GP.
4777                  */
4778                 if (error_code) {
4779                         kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4780                         return 1;
4781                 }
4782                 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
4783         }
4784
4785         /*
4786          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4787          * MMIO, it is better to report an internal error.
4788          * See the comments in vmx_handle_exit.
4789          */
4790         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4791             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4792                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4793                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4794                 vcpu->run->internal.ndata = 4;
4795                 vcpu->run->internal.data[0] = vect_info;
4796                 vcpu->run->internal.data[1] = intr_info;
4797                 vcpu->run->internal.data[2] = error_code;
4798                 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu;
4799                 return 0;
4800         }
4801
4802         if (is_page_fault(intr_info)) {
4803                 cr2 = vmx_get_exit_qual(vcpu);
4804                 if (enable_ept && !vcpu->arch.apf.host_apf_flags) {
4805                         /*
4806                          * EPT will cause page fault only if we need to
4807                          * detect illegal GPAs.
4808                          */
4809                         kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code);
4810                         return 1;
4811                 } else
4812                         return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4813         }
4814
4815         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4816
4817         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4818                 return handle_rmode_exception(vcpu, ex_no, error_code);
4819
4820         switch (ex_no) {
4821         case DB_VECTOR:
4822                 dr6 = vmx_get_exit_qual(vcpu);
4823                 if (!(vcpu->guest_debug &
4824                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4825                         if (is_icebp(intr_info))
4826                                 WARN_ON(!skip_emulated_instruction(vcpu));
4827
4828                         kvm_queue_exception_p(vcpu, DB_VECTOR, dr6);
4829                         return 1;
4830                 }
4831                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1 | DR6_RTM;
4832                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4833                 /* fall through */
4834         case BP_VECTOR:
4835                 /*
4836                  * Update instruction length as we may reinject #BP from
4837                  * user space while in guest debugging mode. Reading it for
4838                  * #DB as well causes no harm, it is not used in that case.
4839                  */
4840                 vmx->vcpu.arch.event_exit_inst_len =
4841                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4842                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4843                 rip = kvm_rip_read(vcpu);
4844                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4845                 kvm_run->debug.arch.exception = ex_no;
4846                 break;
4847         case AC_VECTOR:
4848                 if (guest_inject_ac(vcpu)) {
4849                         kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4850                         return 1;
4851                 }
4852
4853                 /*
4854                  * Handle split lock. Depending on detection mode this will
4855                  * either warn and disable split lock detection for this
4856                  * task or force SIGBUS on it.
4857                  */
4858                 if (handle_guest_split_lock(kvm_rip_read(vcpu)))
4859                         return 1;
4860                 fallthrough;
4861         default:
4862                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4863                 kvm_run->ex.exception = ex_no;
4864                 kvm_run->ex.error_code = error_code;
4865                 break;
4866         }
4867         return 0;
4868 }
4869
4870 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu)
4871 {
4872         ++vcpu->stat.irq_exits;
4873         return 1;
4874 }
4875
4876 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4877 {
4878         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4879         vcpu->mmio_needed = 0;
4880         return 0;
4881 }
4882
4883 static int handle_io(struct kvm_vcpu *vcpu)
4884 {
4885         unsigned long exit_qualification;
4886         int size, in, string;
4887         unsigned port;
4888
4889         exit_qualification = vmx_get_exit_qual(vcpu);
4890         string = (exit_qualification & 16) != 0;
4891
4892         ++vcpu->stat.io_exits;
4893
4894         if (string)
4895                 return kvm_emulate_instruction(vcpu, 0);
4896
4897         port = exit_qualification >> 16;
4898         size = (exit_qualification & 7) + 1;
4899         in = (exit_qualification & 8) != 0;
4900
4901         return kvm_fast_pio(vcpu, size, port, in);
4902 }
4903
4904 static void
4905 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4906 {
4907         /*
4908          * Patch in the VMCALL instruction:
4909          */
4910         hypercall[0] = 0x0f;
4911         hypercall[1] = 0x01;
4912         hypercall[2] = 0xc1;
4913 }
4914
4915 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4916 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4917 {
4918         if (is_guest_mode(vcpu)) {
4919                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4920                 unsigned long orig_val = val;
4921
4922                 /*
4923                  * We get here when L2 changed cr0 in a way that did not change
4924                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4925                  * but did change L0 shadowed bits. So we first calculate the
4926                  * effective cr0 value that L1 would like to write into the
4927                  * hardware. It consists of the L2-owned bits from the new
4928                  * value combined with the L1-owned bits from L1's guest_cr0.
4929                  */
4930                 val = (val & ~vmcs12->cr0_guest_host_mask) |
4931                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4932
4933                 if (!nested_guest_cr0_valid(vcpu, val))
4934                         return 1;
4935
4936                 if (kvm_set_cr0(vcpu, val))
4937                         return 1;
4938                 vmcs_writel(CR0_READ_SHADOW, orig_val);
4939                 return 0;
4940         } else {
4941                 if (to_vmx(vcpu)->nested.vmxon &&
4942                     !nested_host_cr0_valid(vcpu, val))
4943                         return 1;
4944
4945                 return kvm_set_cr0(vcpu, val);
4946         }
4947 }
4948
4949 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4950 {
4951         if (is_guest_mode(vcpu)) {
4952                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4953                 unsigned long orig_val = val;
4954
4955                 /* analogously to handle_set_cr0 */
4956                 val = (val & ~vmcs12->cr4_guest_host_mask) |
4957                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4958                 if (kvm_set_cr4(vcpu, val))
4959                         return 1;
4960                 vmcs_writel(CR4_READ_SHADOW, orig_val);
4961                 return 0;
4962         } else
4963                 return kvm_set_cr4(vcpu, val);
4964 }
4965
4966 static int handle_desc(struct kvm_vcpu *vcpu)
4967 {
4968         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4969         return kvm_emulate_instruction(vcpu, 0);
4970 }
4971
4972 static int handle_cr(struct kvm_vcpu *vcpu)
4973 {
4974         unsigned long exit_qualification, val;
4975         int cr;
4976         int reg;
4977         int err;
4978         int ret;
4979
4980         exit_qualification = vmx_get_exit_qual(vcpu);
4981         cr = exit_qualification & 15;
4982         reg = (exit_qualification >> 8) & 15;
4983         switch ((exit_qualification >> 4) & 3) {
4984         case 0: /* mov to cr */
4985                 val = kvm_register_readl(vcpu, reg);
4986                 trace_kvm_cr_write(cr, val);
4987                 switch (cr) {
4988                 case 0:
4989                         err = handle_set_cr0(vcpu, val);
4990                         return kvm_complete_insn_gp(vcpu, err);
4991                 case 3:
4992                         WARN_ON_ONCE(enable_unrestricted_guest);
4993                         err = kvm_set_cr3(vcpu, val);
4994                         return kvm_complete_insn_gp(vcpu, err);
4995                 case 4:
4996                         err = handle_set_cr4(vcpu, val);
4997                         return kvm_complete_insn_gp(vcpu, err);
4998                 case 8: {
4999                                 u8 cr8_prev = kvm_get_cr8(vcpu);
5000                                 u8 cr8 = (u8)val;
5001                                 err = kvm_set_cr8(vcpu, cr8);
5002                                 ret = kvm_complete_insn_gp(vcpu, err);
5003                                 if (lapic_in_kernel(vcpu))
5004                                         return ret;
5005                                 if (cr8_prev <= cr8)
5006                                         return ret;
5007                                 /*
5008                                  * TODO: we might be squashing a
5009                                  * KVM_GUESTDBG_SINGLESTEP-triggered
5010                                  * KVM_EXIT_DEBUG here.
5011                                  */
5012                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
5013                                 return 0;
5014                         }
5015                 }
5016                 break;
5017         case 2: /* clts */
5018                 WARN_ONCE(1, "Guest should always own CR0.TS");
5019                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
5020                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
5021                 return kvm_skip_emulated_instruction(vcpu);
5022         case 1: /*mov from cr*/
5023                 switch (cr) {
5024                 case 3:
5025                         WARN_ON_ONCE(enable_unrestricted_guest);
5026                         val = kvm_read_cr3(vcpu);
5027                         kvm_register_write(vcpu, reg, val);
5028                         trace_kvm_cr_read(cr, val);
5029                         return kvm_skip_emulated_instruction(vcpu);
5030                 case 8:
5031                         val = kvm_get_cr8(vcpu);
5032                         kvm_register_write(vcpu, reg, val);
5033                         trace_kvm_cr_read(cr, val);
5034                         return kvm_skip_emulated_instruction(vcpu);
5035                 }
5036                 break;
5037         case 3: /* lmsw */
5038                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
5039                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
5040                 kvm_lmsw(vcpu, val);
5041
5042                 return kvm_skip_emulated_instruction(vcpu);
5043         default:
5044                 break;
5045         }
5046         vcpu->run->exit_reason = 0;
5047         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
5048                (int)(exit_qualification >> 4) & 3, cr);
5049         return 0;
5050 }
5051
5052 static int handle_dr(struct kvm_vcpu *vcpu)
5053 {
5054         unsigned long exit_qualification;
5055         int dr, dr7, reg;
5056
5057         exit_qualification = vmx_get_exit_qual(vcpu);
5058         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
5059
5060         /* First, if DR does not exist, trigger UD */
5061         if (!kvm_require_dr(vcpu, dr))
5062                 return 1;
5063
5064         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
5065         if (!kvm_require_cpl(vcpu, 0))
5066                 return 1;
5067         dr7 = vmcs_readl(GUEST_DR7);
5068         if (dr7 & DR7_GD) {
5069                 /*
5070                  * As the vm-exit takes precedence over the debug trap, we
5071                  * need to emulate the latter, either for the host or the
5072                  * guest debugging itself.
5073                  */
5074                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
5075                         vcpu->run->debug.arch.dr6 = DR6_BD | DR6_RTM | DR6_FIXED_1;
5076                         vcpu->run->debug.arch.dr7 = dr7;
5077                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
5078                         vcpu->run->debug.arch.exception = DB_VECTOR;
5079                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
5080                         return 0;
5081                 } else {
5082                         kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD);
5083                         return 1;
5084                 }
5085         }
5086
5087         if (vcpu->guest_debug == 0) {
5088                 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5089
5090                 /*
5091                  * No more DR vmexits; force a reload of the debug registers
5092                  * and reenter on this instruction.  The next vmexit will
5093                  * retrieve the full state of the debug registers.
5094                  */
5095                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
5096                 return 1;
5097         }
5098
5099         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
5100         if (exit_qualification & TYPE_MOV_FROM_DR) {
5101                 unsigned long val;
5102
5103                 if (kvm_get_dr(vcpu, dr, &val))
5104                         return 1;
5105                 kvm_register_write(vcpu, reg, val);
5106         } else
5107                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
5108                         return 1;
5109
5110         return kvm_skip_emulated_instruction(vcpu);
5111 }
5112
5113 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
5114 {
5115         get_debugreg(vcpu->arch.db[0], 0);
5116         get_debugreg(vcpu->arch.db[1], 1);
5117         get_debugreg(vcpu->arch.db[2], 2);
5118         get_debugreg(vcpu->arch.db[3], 3);
5119         get_debugreg(vcpu->arch.dr6, 6);
5120         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
5121
5122         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
5123         exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING);
5124 }
5125
5126 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
5127 {
5128         vmcs_writel(GUEST_DR7, val);
5129 }
5130
5131 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
5132 {
5133         kvm_apic_update_ppr(vcpu);
5134         return 1;
5135 }
5136
5137 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
5138 {
5139         exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
5140
5141         kvm_make_request(KVM_REQ_EVENT, vcpu);
5142
5143         ++vcpu->stat.irq_window_exits;
5144         return 1;
5145 }
5146
5147 static int handle_vmcall(struct kvm_vcpu *vcpu)
5148 {
5149         return kvm_emulate_hypercall(vcpu);
5150 }
5151
5152 static int handle_invd(struct kvm_vcpu *vcpu)
5153 {
5154         return kvm_emulate_instruction(vcpu, 0);
5155 }
5156
5157 static int handle_invlpg(struct kvm_vcpu *vcpu)
5158 {
5159         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5160
5161         kvm_mmu_invlpg(vcpu, exit_qualification);
5162         return kvm_skip_emulated_instruction(vcpu);
5163 }
5164
5165 static int handle_rdpmc(struct kvm_vcpu *vcpu)
5166 {
5167         int err;
5168
5169         err = kvm_rdpmc(vcpu);
5170         return kvm_complete_insn_gp(vcpu, err);
5171 }
5172
5173 static int handle_wbinvd(struct kvm_vcpu *vcpu)
5174 {
5175         return kvm_emulate_wbinvd(vcpu);
5176 }
5177
5178 static int handle_xsetbv(struct kvm_vcpu *vcpu)
5179 {
5180         u64 new_bv = kvm_read_edx_eax(vcpu);
5181         u32 index = kvm_rcx_read(vcpu);
5182
5183         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
5184                 return kvm_skip_emulated_instruction(vcpu);
5185         return 1;
5186 }
5187
5188 static int handle_apic_access(struct kvm_vcpu *vcpu)
5189 {
5190         if (likely(fasteoi)) {
5191                 unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5192                 int access_type, offset;
5193
5194                 access_type = exit_qualification & APIC_ACCESS_TYPE;
5195                 offset = exit_qualification & APIC_ACCESS_OFFSET;
5196                 /*
5197                  * Sane guest uses MOV to write EOI, with written value
5198                  * not cared. So make a short-circuit here by avoiding
5199                  * heavy instruction emulation.
5200                  */
5201                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
5202                     (offset == APIC_EOI)) {
5203                         kvm_lapic_set_eoi(vcpu);
5204                         return kvm_skip_emulated_instruction(vcpu);
5205                 }
5206         }
5207         return kvm_emulate_instruction(vcpu, 0);
5208 }
5209
5210 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
5211 {
5212         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5213         int vector = exit_qualification & 0xff;
5214
5215         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
5216         kvm_apic_set_eoi_accelerated(vcpu, vector);
5217         return 1;
5218 }
5219
5220 static int handle_apic_write(struct kvm_vcpu *vcpu)
5221 {
5222         unsigned long exit_qualification = vmx_get_exit_qual(vcpu);
5223         u32 offset = exit_qualification & 0xfff;
5224
5225         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
5226         kvm_apic_write_nodecode(vcpu, offset);
5227         return 1;
5228 }
5229
5230 static int handle_task_switch(struct kvm_vcpu *vcpu)
5231 {
5232         struct vcpu_vmx *vmx = to_vmx(vcpu);
5233         unsigned long exit_qualification;
5234         bool has_error_code = false;
5235         u32 error_code = 0;
5236         u16 tss_selector;
5237         int reason, type, idt_v, idt_index;
5238
5239         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
5240         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
5241         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
5242
5243         exit_qualification = vmx_get_exit_qual(vcpu);
5244
5245         reason = (u32)exit_qualification >> 30;
5246         if (reason == TASK_SWITCH_GATE && idt_v) {
5247                 switch (type) {
5248                 case INTR_TYPE_NMI_INTR:
5249                         vcpu->arch.nmi_injected = false;
5250                         vmx_set_nmi_mask(vcpu, true);
5251                         break;
5252                 case INTR_TYPE_EXT_INTR:
5253                 case INTR_TYPE_SOFT_INTR:
5254                         kvm_clear_interrupt_queue(vcpu);
5255                         break;
5256                 case INTR_TYPE_HARD_EXCEPTION:
5257                         if (vmx->idt_vectoring_info &
5258                             VECTORING_INFO_DELIVER_CODE_MASK) {
5259                                 has_error_code = true;
5260                                 error_code =
5261                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
5262                         }
5263                         /* fall through */
5264                 case INTR_TYPE_SOFT_EXCEPTION:
5265                         kvm_clear_exception_queue(vcpu);
5266                         break;
5267                 default:
5268                         break;
5269                 }
5270         }
5271         tss_selector = exit_qualification;
5272
5273         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5274                        type != INTR_TYPE_EXT_INTR &&
5275                        type != INTR_TYPE_NMI_INTR))
5276                 WARN_ON(!skip_emulated_instruction(vcpu));
5277
5278         /*
5279          * TODO: What about debug traps on tss switch?
5280          *       Are we supposed to inject them and update dr6?
5281          */
5282         return kvm_task_switch(vcpu, tss_selector,
5283                                type == INTR_TYPE_SOFT_INTR ? idt_index : -1,
5284                                reason, has_error_code, error_code);
5285 }
5286
5287 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5288 {
5289         unsigned long exit_qualification;
5290         gpa_t gpa;
5291         u64 error_code;
5292
5293         exit_qualification = vmx_get_exit_qual(vcpu);
5294
5295         /*
5296          * EPT violation happened while executing iret from NMI,
5297          * "blocked by NMI" bit has to be set before next VM entry.
5298          * There are errata that may cause this bit to not be set:
5299          * AAK134, BY25.
5300          */
5301         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5302                         enable_vnmi &&
5303                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5304                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5305
5306         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5307         trace_kvm_page_fault(gpa, exit_qualification);
5308
5309         /* Is it a read fault? */
5310         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5311                      ? PFERR_USER_MASK : 0;
5312         /* Is it a write fault? */
5313         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5314                       ? PFERR_WRITE_MASK : 0;
5315         /* Is it a fetch fault? */
5316         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5317                       ? PFERR_FETCH_MASK : 0;
5318         /* ept page table entry is present? */
5319         error_code |= (exit_qualification &
5320                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5321                         EPT_VIOLATION_EXECUTABLE))
5322                       ? PFERR_PRESENT_MASK : 0;
5323
5324         error_code |= (exit_qualification & 0x100) != 0 ?
5325                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5326
5327         vcpu->arch.exit_qualification = exit_qualification;
5328
5329         /*
5330          * Check that the GPA doesn't exceed physical memory limits, as that is
5331          * a guest page fault.  We have to emulate the instruction here, because
5332          * if the illegal address is that of a paging structure, then
5333          * EPT_VIOLATION_ACC_WRITE bit is set.  Alternatively, if supported we
5334          * would also use advanced VM-exit information for EPT violations to
5335          * reconstruct the page fault error code.
5336          */
5337         if (unlikely(kvm_mmu_is_illegal_gpa(vcpu, gpa)))
5338                 return kvm_emulate_instruction(vcpu, 0);
5339
5340         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5341 }
5342
5343 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5344 {
5345         gpa_t gpa;
5346
5347         /*
5348          * A nested guest cannot optimize MMIO vmexits, because we have an
5349          * nGPA here instead of the required GPA.
5350          */
5351         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5352         if (!is_guest_mode(vcpu) &&
5353             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5354                 trace_kvm_fast_mmio(gpa);
5355                 return kvm_skip_emulated_instruction(vcpu);
5356         }
5357
5358         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5359 }
5360
5361 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5362 {
5363         WARN_ON_ONCE(!enable_vnmi);
5364         exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
5365         ++vcpu->stat.nmi_window_exits;
5366         kvm_make_request(KVM_REQ_EVENT, vcpu);
5367
5368         return 1;
5369 }
5370
5371 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5372 {
5373         struct vcpu_vmx *vmx = to_vmx(vcpu);
5374         bool intr_window_requested;
5375         unsigned count = 130;
5376
5377         intr_window_requested = exec_controls_get(vmx) &
5378                                 CPU_BASED_INTR_WINDOW_EXITING;
5379
5380         while (vmx->emulation_required && count-- != 0) {
5381                 if (intr_window_requested && !vmx_interrupt_blocked(vcpu))
5382                         return handle_interrupt_window(&vmx->vcpu);
5383
5384                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5385                         return 1;
5386
5387                 if (!kvm_emulate_instruction(vcpu, 0))
5388                         return 0;
5389
5390                 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5391                     vcpu->arch.exception.pending) {
5392                         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5393                         vcpu->run->internal.suberror =
5394                                                 KVM_INTERNAL_ERROR_EMULATION;
5395                         vcpu->run->internal.ndata = 0;
5396                         return 0;
5397                 }
5398
5399                 if (vcpu->arch.halt_request) {
5400                         vcpu->arch.halt_request = 0;
5401                         return kvm_vcpu_halt(vcpu);
5402                 }
5403
5404                 /*
5405                  * Note, return 1 and not 0, vcpu_run() is responsible for
5406                  * morphing the pending signal into the proper return code.
5407                  */
5408                 if (signal_pending(current))
5409                         return 1;
5410
5411                 if (need_resched())
5412                         schedule();
5413         }
5414
5415         return 1;
5416 }
5417
5418 static void grow_ple_window(struct kvm_vcpu *vcpu)
5419 {
5420         struct vcpu_vmx *vmx = to_vmx(vcpu);
5421         unsigned int old = vmx->ple_window;
5422
5423         vmx->ple_window = __grow_ple_window(old, ple_window,
5424                                             ple_window_grow,
5425                                             ple_window_max);
5426
5427         if (vmx->ple_window != old) {
5428                 vmx->ple_window_dirty = true;
5429                 trace_kvm_ple_window_update(vcpu->vcpu_id,
5430                                             vmx->ple_window, old);
5431         }
5432 }
5433
5434 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5435 {
5436         struct vcpu_vmx *vmx = to_vmx(vcpu);
5437         unsigned int old = vmx->ple_window;
5438
5439         vmx->ple_window = __shrink_ple_window(old, ple_window,
5440                                               ple_window_shrink,
5441                                               ple_window);
5442
5443         if (vmx->ple_window != old) {
5444                 vmx->ple_window_dirty = true;
5445                 trace_kvm_ple_window_update(vcpu->vcpu_id,
5446                                             vmx->ple_window, old);
5447         }
5448 }
5449
5450 /*
5451  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5452  */
5453 static void wakeup_handler(void)
5454 {
5455         struct kvm_vcpu *vcpu;
5456         int cpu = smp_processor_id();
5457
5458         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5459         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5460                         blocked_vcpu_list) {
5461                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5462
5463                 if (pi_test_on(pi_desc) == 1)
5464                         kvm_vcpu_kick(vcpu);
5465         }
5466         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5467 }
5468
5469 static void vmx_enable_tdp(void)
5470 {
5471         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5472                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5473                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5474                 0ull, VMX_EPT_EXECUTABLE_MASK,
5475                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5476                 VMX_EPT_RWX_MASK, 0ull);
5477
5478         ept_set_mmio_spte_mask();
5479 }
5480
5481 /*
5482  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5483  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5484  */
5485 static int handle_pause(struct kvm_vcpu *vcpu)
5486 {
5487         if (!kvm_pause_in_guest(vcpu->kvm))
5488                 grow_ple_window(vcpu);
5489
5490         /*
5491          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5492          * VM-execution control is ignored if CPL > 0. OTOH, KVM
5493          * never set PAUSE_EXITING and just set PLE if supported,
5494          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5495          */
5496         kvm_vcpu_on_spin(vcpu, true);
5497         return kvm_skip_emulated_instruction(vcpu);
5498 }
5499
5500 static int handle_nop(struct kvm_vcpu *vcpu)
5501 {
5502         return kvm_skip_emulated_instruction(vcpu);
5503 }
5504
5505 static int handle_mwait(struct kvm_vcpu *vcpu)
5506 {
5507         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5508         return handle_nop(vcpu);
5509 }
5510
5511 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5512 {
5513         kvm_queue_exception(vcpu, UD_VECTOR);
5514         return 1;
5515 }
5516
5517 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5518 {
5519         return 1;
5520 }
5521
5522 static int handle_monitor(struct kvm_vcpu *vcpu)
5523 {
5524         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5525         return handle_nop(vcpu);
5526 }
5527
5528 static int handle_invpcid(struct kvm_vcpu *vcpu)
5529 {
5530         u32 vmx_instruction_info;
5531         unsigned long type;
5532         bool pcid_enabled;
5533         gva_t gva;
5534         struct x86_exception e;
5535         unsigned i;
5536         unsigned long roots_to_free = 0;
5537         struct {
5538                 u64 pcid;
5539                 u64 gla;
5540         } operand;
5541         int r;
5542
5543         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5544                 kvm_queue_exception(vcpu, UD_VECTOR);
5545                 return 1;
5546         }
5547
5548         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5549         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5550
5551         if (type > 3) {
5552                 kvm_inject_gp(vcpu, 0);
5553                 return 1;
5554         }
5555
5556         /* According to the Intel instruction reference, the memory operand
5557          * is read even if it isn't needed (e.g., for type==all)
5558          */
5559         if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu),
5560                                 vmx_instruction_info, false,
5561                                 sizeof(operand), &gva))
5562                 return 1;
5563
5564         r = kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e);
5565         if (r != X86EMUL_CONTINUE)
5566                 return vmx_handle_memory_failure(vcpu, r, &e);
5567
5568         if (operand.pcid >> 12 != 0) {
5569                 kvm_inject_gp(vcpu, 0);
5570                 return 1;
5571         }
5572
5573         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5574
5575         switch (type) {
5576         case INVPCID_TYPE_INDIV_ADDR:
5577                 if ((!pcid_enabled && (operand.pcid != 0)) ||
5578                     is_noncanonical_address(operand.gla, vcpu)) {
5579                         kvm_inject_gp(vcpu, 0);
5580                         return 1;
5581                 }
5582                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5583                 return kvm_skip_emulated_instruction(vcpu);
5584
5585         case INVPCID_TYPE_SINGLE_CTXT:
5586                 if (!pcid_enabled && (operand.pcid != 0)) {
5587                         kvm_inject_gp(vcpu, 0);
5588                         return 1;
5589                 }
5590
5591                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5592                         kvm_mmu_sync_roots(vcpu);
5593                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
5594                 }
5595
5596                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5597                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].pgd)
5598                             == operand.pcid)
5599                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5600
5601                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5602                 /*
5603                  * If neither the current cr3 nor any of the prev_roots use the
5604                  * given PCID, then nothing needs to be done here because a
5605                  * resync will happen anyway before switching to any other CR3.
5606                  */
5607
5608                 return kvm_skip_emulated_instruction(vcpu);
5609
5610         case INVPCID_TYPE_ALL_NON_GLOBAL:
5611                 /*
5612                  * Currently, KVM doesn't mark global entries in the shadow
5613                  * page tables, so a non-global flush just degenerates to a
5614                  * global flush. If needed, we could optimize this later by
5615                  * keeping track of global entries in shadow page tables.
5616                  */
5617
5618                 /* fall-through */
5619         case INVPCID_TYPE_ALL_INCL_GLOBAL:
5620                 kvm_mmu_unload(vcpu);
5621                 return kvm_skip_emulated_instruction(vcpu);
5622
5623         default:
5624                 BUG(); /* We have already checked above that type <= 3 */
5625         }
5626 }
5627
5628 static int handle_pml_full(struct kvm_vcpu *vcpu)
5629 {
5630         unsigned long exit_qualification;
5631
5632         trace_kvm_pml_full(vcpu->vcpu_id);
5633
5634         exit_qualification = vmx_get_exit_qual(vcpu);
5635
5636         /*
5637          * PML buffer FULL happened while executing iret from NMI,
5638          * "blocked by NMI" bit has to be set before next VM entry.
5639          */
5640         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5641                         enable_vnmi &&
5642                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5643                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5644                                 GUEST_INTR_STATE_NMI);
5645
5646         /*
5647          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5648          * here.., and there's no userspace involvement needed for PML.
5649          */
5650         return 1;
5651 }
5652
5653 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu)
5654 {
5655         struct vcpu_vmx *vmx = to_vmx(vcpu);
5656
5657         if (!vmx->req_immediate_exit &&
5658             !unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) {
5659                 kvm_lapic_expired_hv_timer(vcpu);
5660                 return EXIT_FASTPATH_REENTER_GUEST;
5661         }
5662
5663         return EXIT_FASTPATH_NONE;
5664 }
5665
5666 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5667 {
5668         handle_fastpath_preemption_timer(vcpu);
5669         return 1;
5670 }
5671
5672 /*
5673  * When nested=0, all VMX instruction VM Exits filter here.  The handlers
5674  * are overwritten by nested_vmx_setup() when nested=1.
5675  */
5676 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5677 {
5678         kvm_queue_exception(vcpu, UD_VECTOR);
5679         return 1;
5680 }
5681
5682 static int handle_encls(struct kvm_vcpu *vcpu)
5683 {
5684         /*
5685          * SGX virtualization is not yet supported.  There is no software
5686          * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5687          * to prevent the guest from executing ENCLS.
5688          */
5689         kvm_queue_exception(vcpu, UD_VECTOR);
5690         return 1;
5691 }
5692
5693 /*
5694  * The exit handlers return 1 if the exit was handled fully and guest execution
5695  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
5696  * to be done to userspace and return 0.
5697  */
5698 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5699         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception_nmi,
5700         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
5701         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
5702         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
5703         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
5704         [EXIT_REASON_CR_ACCESS]               = handle_cr,
5705         [EXIT_REASON_DR_ACCESS]               = handle_dr,
5706         [EXIT_REASON_CPUID]                   = kvm_emulate_cpuid,
5707         [EXIT_REASON_MSR_READ]                = kvm_emulate_rdmsr,
5708         [EXIT_REASON_MSR_WRITE]               = kvm_emulate_wrmsr,
5709         [EXIT_REASON_INTERRUPT_WINDOW]        = handle_interrupt_window,
5710         [EXIT_REASON_HLT]                     = kvm_emulate_halt,
5711         [EXIT_REASON_INVD]                    = handle_invd,
5712         [EXIT_REASON_INVLPG]                  = handle_invlpg,
5713         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
5714         [EXIT_REASON_VMCALL]                  = handle_vmcall,
5715         [EXIT_REASON_VMCLEAR]                 = handle_vmx_instruction,
5716         [EXIT_REASON_VMLAUNCH]                = handle_vmx_instruction,
5717         [EXIT_REASON_VMPTRLD]                 = handle_vmx_instruction,
5718         [EXIT_REASON_VMPTRST]                 = handle_vmx_instruction,
5719         [EXIT_REASON_VMREAD]                  = handle_vmx_instruction,
5720         [EXIT_REASON_VMRESUME]                = handle_vmx_instruction,
5721         [EXIT_REASON_VMWRITE]                 = handle_vmx_instruction,
5722         [EXIT_REASON_VMOFF]                   = handle_vmx_instruction,
5723         [EXIT_REASON_VMON]                    = handle_vmx_instruction,
5724         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
5725         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
5726         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
5727         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
5728         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
5729         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
5730         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
5731         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
5732         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
5733         [EXIT_REASON_LDTR_TR]                 = handle_desc,
5734         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
5735         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
5736         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
5737         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
5738         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
5739         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
5740         [EXIT_REASON_INVEPT]                  = handle_vmx_instruction,
5741         [EXIT_REASON_INVVPID]                 = handle_vmx_instruction,
5742         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
5743         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
5744         [EXIT_REASON_PML_FULL]                = handle_pml_full,
5745         [EXIT_REASON_INVPCID]                 = handle_invpcid,
5746         [EXIT_REASON_VMFUNC]                  = handle_vmx_instruction,
5747         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
5748         [EXIT_REASON_ENCLS]                   = handle_encls,
5749 };
5750
5751 static const int kvm_vmx_max_exit_handlers =
5752         ARRAY_SIZE(kvm_vmx_exit_handlers);
5753
5754 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5755 {
5756         *info1 = vmx_get_exit_qual(vcpu);
5757         *info2 = vmx_get_intr_info(vcpu);
5758 }
5759
5760 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5761 {
5762         if (vmx->pml_pg) {
5763                 __free_page(vmx->pml_pg);
5764                 vmx->pml_pg = NULL;
5765         }
5766 }
5767
5768 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5769 {
5770         struct vcpu_vmx *vmx = to_vmx(vcpu);
5771         u64 *pml_buf;
5772         u16 pml_idx;
5773
5774         pml_idx = vmcs_read16(GUEST_PML_INDEX);
5775
5776         /* Do nothing if PML buffer is empty */
5777         if (pml_idx == (PML_ENTITY_NUM - 1))
5778                 return;
5779
5780         /* PML index always points to next available PML buffer entity */
5781         if (pml_idx >= PML_ENTITY_NUM)
5782                 pml_idx = 0;
5783         else
5784                 pml_idx++;
5785
5786         pml_buf = page_address(vmx->pml_pg);
5787         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5788                 u64 gpa;
5789
5790                 gpa = pml_buf[pml_idx];
5791                 WARN_ON(gpa & (PAGE_SIZE - 1));
5792                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5793         }
5794
5795         /* reset PML index */
5796         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5797 }
5798
5799 /*
5800  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5801  * Called before reporting dirty_bitmap to userspace.
5802  */
5803 static void kvm_flush_pml_buffers(struct kvm *kvm)
5804 {
5805         int i;
5806         struct kvm_vcpu *vcpu;
5807         /*
5808          * We only need to kick vcpu out of guest mode here, as PML buffer
5809          * is flushed at beginning of all VMEXITs, and it's obvious that only
5810          * vcpus running in guest are possible to have unflushed GPAs in PML
5811          * buffer.
5812          */
5813         kvm_for_each_vcpu(i, vcpu, kvm)
5814                 kvm_vcpu_kick(vcpu);
5815 }
5816
5817 static void vmx_dump_sel(char *name, uint32_t sel)
5818 {
5819         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5820                name, vmcs_read16(sel),
5821                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5822                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5823                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5824 }
5825
5826 static void vmx_dump_dtsel(char *name, uint32_t limit)
5827 {
5828         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
5829                name, vmcs_read32(limit),
5830                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5831 }
5832
5833 void dump_vmcs(void)
5834 {
5835         u32 vmentry_ctl, vmexit_ctl;
5836         u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
5837         unsigned long cr4;
5838         u64 efer;
5839
5840         if (!dump_invalid_vmcs) {
5841                 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n");
5842                 return;
5843         }
5844
5845         vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5846         vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5847         cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5848         pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5849         cr4 = vmcs_readl(GUEST_CR4);
5850         efer = vmcs_read64(GUEST_IA32_EFER);
5851         secondary_exec_control = 0;
5852         if (cpu_has_secondary_exec_ctrls())
5853                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5854
5855         pr_err("*** Guest State ***\n");
5856         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5857                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5858                vmcs_readl(CR0_GUEST_HOST_MASK));
5859         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5860                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5861         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5862         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5863             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5864         {
5865                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
5866                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5867                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
5868                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5869         }
5870         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
5871                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5872         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
5873                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5874         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5875                vmcs_readl(GUEST_SYSENTER_ESP),
5876                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5877         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
5878         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
5879         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
5880         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
5881         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
5882         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
5883         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5884         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5885         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5886         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
5887         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5888             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5889                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
5890                        efer, vmcs_read64(GUEST_IA32_PAT));
5891         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
5892                vmcs_read64(GUEST_IA32_DEBUGCTL),
5893                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5894         if (cpu_has_load_perf_global_ctrl() &&
5895             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5896                 pr_err("PerfGlobCtl = 0x%016llx\n",
5897                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5898         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5899                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5900         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
5901                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5902                vmcs_read32(GUEST_ACTIVITY_STATE));
5903         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5904                 pr_err("InterruptStatus = %04x\n",
5905                        vmcs_read16(GUEST_INTR_STATUS));
5906
5907         pr_err("*** Host State ***\n");
5908         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
5909                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5910         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5911                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5912                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5913                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5914                vmcs_read16(HOST_TR_SELECTOR));
5915         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5916                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5917                vmcs_readl(HOST_TR_BASE));
5918         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5919                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5920         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5921                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5922                vmcs_readl(HOST_CR4));
5923         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5924                vmcs_readl(HOST_IA32_SYSENTER_ESP),
5925                vmcs_read32(HOST_IA32_SYSENTER_CS),
5926                vmcs_readl(HOST_IA32_SYSENTER_EIP));
5927         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5928                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
5929                        vmcs_read64(HOST_IA32_EFER),
5930                        vmcs_read64(HOST_IA32_PAT));
5931         if (cpu_has_load_perf_global_ctrl() &&
5932             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5933                 pr_err("PerfGlobCtl = 0x%016llx\n",
5934                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5935
5936         pr_err("*** Control State ***\n");
5937         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5938                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5939         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5940         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5941                vmcs_read32(EXCEPTION_BITMAP),
5942                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5943                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5944         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5945                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5946                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5947                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5948         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5949                vmcs_read32(VM_EXIT_INTR_INFO),
5950                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5951                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5952         pr_err("        reason=%08x qualification=%016lx\n",
5953                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5954         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5955                vmcs_read32(IDT_VECTORING_INFO_FIELD),
5956                vmcs_read32(IDT_VECTORING_ERROR_CODE));
5957         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5958         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5959                 pr_err("TSC Multiplier = 0x%016llx\n",
5960                        vmcs_read64(TSC_MULTIPLIER));
5961         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) {
5962                 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
5963                         u16 status = vmcs_read16(GUEST_INTR_STATUS);
5964                         pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff);
5965                 }
5966                 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5967                 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
5968                         pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR));
5969                 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR));
5970         }
5971         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5972                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5973         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5974                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5975         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5976                 pr_err("PLE Gap=%08x Window=%08x\n",
5977                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5978         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5979                 pr_err("Virtual processor ID = 0x%04x\n",
5980                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
5981 }
5982
5983 /*
5984  * The guest has exited.  See if we can fix it or if we need userspace
5985  * assistance.
5986  */
5987 static int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
5988 {
5989         struct vcpu_vmx *vmx = to_vmx(vcpu);
5990         u32 exit_reason = vmx->exit_reason;
5991         u32 vectoring_info = vmx->idt_vectoring_info;
5992
5993         /*
5994          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5995          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5996          * querying dirty_bitmap, we only need to kick all vcpus out of guest
5997          * mode as if vcpus is in root mode, the PML buffer must has been
5998          * flushed already.
5999          */
6000         if (enable_pml)
6001                 vmx_flush_pml_buffer(vcpu);
6002
6003         /*
6004          * We should never reach this point with a pending nested VM-Enter, and
6005          * more specifically emulation of L2 due to invalid guest state (see
6006          * below) should never happen as that means we incorrectly allowed a
6007          * nested VM-Enter with an invalid vmcs12.
6008          */
6009         WARN_ON_ONCE(vmx->nested.nested_run_pending);
6010
6011         /* If guest state is invalid, start emulating */
6012         if (vmx->emulation_required)
6013                 return handle_invalid_guest_state(vcpu);
6014
6015         if (is_guest_mode(vcpu)) {
6016                 /*
6017                  * The host physical addresses of some pages of guest memory
6018                  * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
6019                  * Page). The CPU may write to these pages via their host
6020                  * physical address while L2 is running, bypassing any
6021                  * address-translation-based dirty tracking (e.g. EPT write
6022                  * protection).
6023                  *
6024                  * Mark them dirty on every exit from L2 to prevent them from
6025                  * getting out of sync with dirty tracking.
6026                  */
6027                 nested_mark_vmcs12_pages_dirty(vcpu);
6028
6029                 if (nested_vmx_reflect_vmexit(vcpu))
6030                         return 1;
6031         }
6032
6033         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
6034                 dump_vmcs();
6035                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6036                 vcpu->run->fail_entry.hardware_entry_failure_reason
6037                         = exit_reason;
6038                 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6039                 return 0;
6040         }
6041
6042         if (unlikely(vmx->fail)) {
6043                 dump_vmcs();
6044                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
6045                 vcpu->run->fail_entry.hardware_entry_failure_reason
6046                         = vmcs_read32(VM_INSTRUCTION_ERROR);
6047                 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
6048                 return 0;
6049         }
6050
6051         /*
6052          * Note:
6053          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
6054          * delivery event since it indicates guest is accessing MMIO.
6055          * The vm-exit can be triggered again after return to guest that
6056          * will cause infinite loop.
6057          */
6058         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
6059                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
6060                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
6061                         exit_reason != EXIT_REASON_PML_FULL &&
6062                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
6063                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6064                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
6065                 vcpu->run->internal.ndata = 3;
6066                 vcpu->run->internal.data[0] = vectoring_info;
6067                 vcpu->run->internal.data[1] = exit_reason;
6068                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
6069                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
6070                         vcpu->run->internal.ndata++;
6071                         vcpu->run->internal.data[3] =
6072                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6073                 }
6074                 vcpu->run->internal.data[vcpu->run->internal.ndata++] =
6075                         vcpu->arch.last_vmentry_cpu;
6076                 return 0;
6077         }
6078
6079         if (unlikely(!enable_vnmi &&
6080                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
6081                 if (!vmx_interrupt_blocked(vcpu)) {
6082                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6083                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
6084                            vcpu->arch.nmi_pending) {
6085                         /*
6086                          * This CPU don't support us in finding the end of an
6087                          * NMI-blocked window if the guest runs with IRQs
6088                          * disabled. So we pull the trigger after 1 s of
6089                          * futile waiting, but inform the user about this.
6090                          */
6091                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
6092                                "state on VCPU %d after 1 s timeout\n",
6093                                __func__, vcpu->vcpu_id);
6094                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
6095                 }
6096         }
6097
6098         if (exit_fastpath != EXIT_FASTPATH_NONE)
6099                 return 1;
6100
6101         if (exit_reason >= kvm_vmx_max_exit_handlers)
6102                 goto unexpected_vmexit;
6103 #ifdef CONFIG_RETPOLINE
6104         if (exit_reason == EXIT_REASON_MSR_WRITE)
6105                 return kvm_emulate_wrmsr(vcpu);
6106         else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
6107                 return handle_preemption_timer(vcpu);
6108         else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
6109                 return handle_interrupt_window(vcpu);
6110         else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6111                 return handle_external_interrupt(vcpu);
6112         else if (exit_reason == EXIT_REASON_HLT)
6113                 return kvm_emulate_halt(vcpu);
6114         else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
6115                 return handle_ept_misconfig(vcpu);
6116 #endif
6117
6118         exit_reason = array_index_nospec(exit_reason,
6119                                          kvm_vmx_max_exit_handlers);
6120         if (!kvm_vmx_exit_handlers[exit_reason])
6121                 goto unexpected_vmexit;
6122
6123         return kvm_vmx_exit_handlers[exit_reason](vcpu);
6124
6125 unexpected_vmexit:
6126         vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n", exit_reason);
6127         dump_vmcs();
6128         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6129         vcpu->run->internal.suberror =
6130                         KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
6131         vcpu->run->internal.ndata = 2;
6132         vcpu->run->internal.data[0] = exit_reason;
6133         vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
6134         return 0;
6135 }
6136
6137 /*
6138  * Software based L1D cache flush which is used when microcode providing
6139  * the cache control MSR is not loaded.
6140  *
6141  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
6142  * flush it is required to read in 64 KiB because the replacement algorithm
6143  * is not exactly LRU. This could be sized at runtime via topology
6144  * information but as all relevant affected CPUs have 32KiB L1D cache size
6145  * there is no point in doing so.
6146  */
6147 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu)
6148 {
6149         int size = PAGE_SIZE << L1D_CACHE_ORDER;
6150
6151         /*
6152          * This code is only executed when the the flush mode is 'cond' or
6153          * 'always'
6154          */
6155         if (static_branch_likely(&vmx_l1d_flush_cond)) {
6156                 bool flush_l1d;
6157
6158                 /*
6159                  * Clear the per-vcpu flush bit, it gets set again
6160                  * either from vcpu_run() or from one of the unsafe
6161                  * VMEXIT handlers.
6162                  */
6163                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
6164                 vcpu->arch.l1tf_flush_l1d = false;
6165
6166                 /*
6167                  * Clear the per-cpu flush bit, it gets set again from
6168                  * the interrupt handlers.
6169                  */
6170                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
6171                 kvm_clear_cpu_l1tf_flush_l1d();
6172
6173                 if (!flush_l1d)
6174                         return;
6175         }
6176
6177         vcpu->stat.l1d_flush++;
6178
6179         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
6180                 native_wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
6181                 return;
6182         }
6183
6184         asm volatile(
6185                 /* First ensure the pages are in the TLB */
6186                 "xorl   %%eax, %%eax\n"
6187                 ".Lpopulate_tlb:\n\t"
6188                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6189                 "addl   $4096, %%eax\n\t"
6190                 "cmpl   %%eax, %[size]\n\t"
6191                 "jne    .Lpopulate_tlb\n\t"
6192                 "xorl   %%eax, %%eax\n\t"
6193                 "cpuid\n\t"
6194                 /* Now fill the cache */
6195                 "xorl   %%eax, %%eax\n"
6196                 ".Lfill_cache:\n"
6197                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
6198                 "addl   $64, %%eax\n\t"
6199                 "cmpl   %%eax, %[size]\n\t"
6200                 "jne    .Lfill_cache\n\t"
6201                 "lfence\n"
6202                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
6203                     [size] "r" (size)
6204                 : "eax", "ebx", "ecx", "edx");
6205 }
6206
6207 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
6208 {
6209         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6210         int tpr_threshold;
6211
6212         if (is_guest_mode(vcpu) &&
6213                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
6214                 return;
6215
6216         tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr;
6217         if (is_guest_mode(vcpu))
6218                 to_vmx(vcpu)->nested.l1_tpr_threshold = tpr_threshold;
6219         else
6220                 vmcs_write32(TPR_THRESHOLD, tpr_threshold);
6221 }
6222
6223 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
6224 {
6225         struct vcpu_vmx *vmx = to_vmx(vcpu);
6226         u32 sec_exec_control;
6227
6228         if (!lapic_in_kernel(vcpu))
6229                 return;
6230
6231         if (!flexpriority_enabled &&
6232             !cpu_has_vmx_virtualize_x2apic_mode())
6233                 return;
6234
6235         /* Postpone execution until vmcs01 is the current VMCS. */
6236         if (is_guest_mode(vcpu)) {
6237                 vmx->nested.change_vmcs01_virtual_apic_mode = true;
6238                 return;
6239         }
6240
6241         sec_exec_control = secondary_exec_controls_get(vmx);
6242         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
6243                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
6244
6245         switch (kvm_get_apic_mode(vcpu)) {
6246         case LAPIC_MODE_INVALID:
6247                 WARN_ONCE(true, "Invalid local APIC state");
6248         case LAPIC_MODE_DISABLED:
6249                 break;
6250         case LAPIC_MODE_XAPIC:
6251                 if (flexpriority_enabled) {
6252                         sec_exec_control |=
6253                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6254                         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6255
6256                         /*
6257                          * Flush the TLB, reloading the APIC access page will
6258                          * only do so if its physical address has changed, but
6259                          * the guest may have inserted a non-APIC mapping into
6260                          * the TLB while the APIC access page was disabled.
6261                          */
6262                         kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
6263                 }
6264                 break;
6265         case LAPIC_MODE_X2APIC:
6266                 if (cpu_has_vmx_virtualize_x2apic_mode())
6267                         sec_exec_control |=
6268                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6269                 break;
6270         }
6271         secondary_exec_controls_set(vmx, sec_exec_control);
6272
6273         vmx_update_msr_bitmap(vcpu);
6274 }
6275
6276 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu)
6277 {
6278         struct page *page;
6279
6280         /* Defer reload until vmcs01 is the current VMCS. */
6281         if (is_guest_mode(vcpu)) {
6282                 to_vmx(vcpu)->nested.reload_vmcs01_apic_access_page = true;
6283                 return;
6284         }
6285
6286         if (!(secondary_exec_controls_get(to_vmx(vcpu)) &
6287             SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
6288                 return;
6289
6290         page = gfn_to_page(vcpu->kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
6291         if (is_error_page(page))
6292                 return;
6293
6294         vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(page));
6295         vmx_flush_tlb_current(vcpu);
6296
6297         /*
6298          * Do not pin apic access page in memory, the MMU notifier
6299          * will call us again if it is migrated or swapped out.
6300          */
6301         put_page(page);
6302 }
6303
6304 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
6305 {
6306         u16 status;
6307         u8 old;
6308
6309         if (max_isr == -1)
6310                 max_isr = 0;
6311
6312         status = vmcs_read16(GUEST_INTR_STATUS);
6313         old = status >> 8;
6314         if (max_isr != old) {
6315                 status &= 0xff;
6316                 status |= max_isr << 8;
6317                 vmcs_write16(GUEST_INTR_STATUS, status);
6318         }
6319 }
6320
6321 static void vmx_set_rvi(int vector)
6322 {
6323         u16 status;
6324         u8 old;
6325
6326         if (vector == -1)
6327                 vector = 0;
6328
6329         status = vmcs_read16(GUEST_INTR_STATUS);
6330         old = (u8)status & 0xff;
6331         if ((u8)vector != old) {
6332                 status &= ~0xff;
6333                 status |= (u8)vector;
6334                 vmcs_write16(GUEST_INTR_STATUS, status);
6335         }
6336 }
6337
6338 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6339 {
6340         /*
6341          * When running L2, updating RVI is only relevant when
6342          * vmcs12 virtual-interrupt-delivery enabled.
6343          * However, it can be enabled only when L1 also
6344          * intercepts external-interrupts and in that case
6345          * we should not update vmcs02 RVI but instead intercept
6346          * interrupt. Therefore, do nothing when running L2.
6347          */
6348         if (!is_guest_mode(vcpu))
6349                 vmx_set_rvi(max_irr);
6350 }
6351
6352 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6353 {
6354         struct vcpu_vmx *vmx = to_vmx(vcpu);
6355         int max_irr;
6356         bool max_irr_updated;
6357
6358         WARN_ON(!vcpu->arch.apicv_active);
6359         if (pi_test_on(&vmx->pi_desc)) {
6360                 pi_clear_on(&vmx->pi_desc);
6361                 /*
6362                  * IOMMU can write to PID.ON, so the barrier matters even on UP.
6363                  * But on x86 this is just a compiler barrier anyway.
6364                  */
6365                 smp_mb__after_atomic();
6366                 max_irr_updated =
6367                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6368
6369                 /*
6370                  * If we are running L2 and L1 has a new pending interrupt
6371                  * which can be injected, we should re-evaluate
6372                  * what should be done with this new L1 interrupt.
6373                  * If L1 intercepts external-interrupts, we should
6374                  * exit from L2 to L1. Otherwise, interrupt should be
6375                  * delivered directly to L2.
6376                  */
6377                 if (is_guest_mode(vcpu) && max_irr_updated) {
6378                         if (nested_exit_on_intr(vcpu))
6379                                 kvm_vcpu_exiting_guest_mode(vcpu);
6380                         else
6381                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6382                 }
6383         } else {
6384                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6385         }
6386         vmx_hwapic_irr_update(vcpu, max_irr);
6387         return max_irr;
6388 }
6389
6390 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
6391 {
6392         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6393
6394         return pi_test_on(pi_desc) ||
6395                 (pi_test_sn(pi_desc) && !pi_is_pir_empty(pi_desc));
6396 }
6397
6398 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6399 {
6400         if (!kvm_vcpu_apicv_active(vcpu))
6401                 return;
6402
6403         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6404         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6405         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6406         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6407 }
6408
6409 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6410 {
6411         struct vcpu_vmx *vmx = to_vmx(vcpu);
6412
6413         pi_clear_on(&vmx->pi_desc);
6414         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6415 }
6416
6417 static void handle_exception_nmi_irqoff(struct vcpu_vmx *vmx)
6418 {
6419         u32 intr_info = vmx_get_intr_info(&vmx->vcpu);
6420
6421         /* if exit due to PF check for async PF */
6422         if (is_page_fault(intr_info)) {
6423                 vmx->vcpu.arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags();
6424         /* Handle machine checks before interrupts are enabled */
6425         } else if (is_machine_check(intr_info)) {
6426                 kvm_machine_check();
6427         /* We need to handle NMIs before interrupts are enabled */
6428         } else if (is_nmi(intr_info)) {
6429                 kvm_before_interrupt(&vmx->vcpu);
6430                 asm("int $2");
6431                 kvm_after_interrupt(&vmx->vcpu);
6432         }
6433 }
6434
6435 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu)
6436 {
6437         unsigned int vector;
6438         unsigned long entry;
6439 #ifdef CONFIG_X86_64
6440         unsigned long tmp;
6441 #endif
6442         gate_desc *desc;
6443         u32 intr_info = vmx_get_intr_info(vcpu);
6444
6445         if (WARN_ONCE(!is_external_intr(intr_info),
6446             "KVM: unexpected VM-Exit interrupt info: 0x%x", intr_info))
6447                 return;
6448
6449         vector = intr_info & INTR_INFO_VECTOR_MASK;
6450         desc = (gate_desc *)host_idt_base + vector;
6451         entry = gate_offset(desc);
6452
6453         kvm_before_interrupt(vcpu);
6454
6455         asm volatile(
6456 #ifdef CONFIG_X86_64
6457                 "mov %%rsp, %[sp]\n\t"
6458                 "and $-16, %%rsp\n\t"
6459                 "push %[ss]\n\t"
6460                 "push %[sp]\n\t"
6461 #endif
6462                 "pushf\n\t"
6463                 "push %[cs]\n\t"
6464                 CALL_NOSPEC
6465                 :
6466 #ifdef CONFIG_X86_64
6467                 [sp]"=&r"(tmp),
6468 #endif
6469                 ASM_CALL_CONSTRAINT
6470                 :
6471                 [thunk_target]"r"(entry),
6472 #ifdef CONFIG_X86_64
6473                 [ss]"i"(__KERNEL_DS),
6474 #endif
6475                 [cs]"i"(__KERNEL_CS)
6476         );
6477
6478         kvm_after_interrupt(vcpu);
6479 }
6480 STACK_FRAME_NON_STANDARD(handle_external_interrupt_irqoff);
6481
6482 static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6483 {
6484         struct vcpu_vmx *vmx = to_vmx(vcpu);
6485
6486         if (vmx->exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
6487                 handle_external_interrupt_irqoff(vcpu);
6488         else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
6489                 handle_exception_nmi_irqoff(vmx);
6490 }
6491
6492 static bool vmx_has_emulated_msr(u32 index)
6493 {
6494         switch (index) {
6495         case MSR_IA32_SMBASE:
6496                 /*
6497                  * We cannot do SMM unless we can run the guest in big
6498                  * real mode.
6499                  */
6500                 return enable_unrestricted_guest || emulate_invalid_guest_state;
6501         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6502                 return nested;
6503         case MSR_AMD64_VIRT_SPEC_CTRL:
6504                 /* This is AMD only.  */
6505                 return false;
6506         default:
6507                 return true;
6508         }
6509 }
6510
6511 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
6512 {
6513         u32 exit_intr_info;
6514         bool unblock_nmi;
6515         u8 vector;
6516         bool idtv_info_valid;
6517
6518         idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6519
6520         if (enable_vnmi) {
6521                 if (vmx->loaded_vmcs->nmi_known_unmasked)
6522                         return;
6523
6524                 exit_intr_info = vmx_get_intr_info(&vmx->vcpu);
6525                 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
6526                 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
6527                 /*
6528                  * SDM 3: 27.7.1.2 (September 2008)
6529                  * Re-set bit "block by NMI" before VM entry if vmexit caused by
6530                  * a guest IRET fault.
6531                  * SDM 3: 23.2.2 (September 2008)
6532                  * Bit 12 is undefined in any of the following cases:
6533                  *  If the VM exit sets the valid bit in the IDT-vectoring
6534                  *   information field.
6535                  *  If the VM exit is due to a double fault.
6536                  */
6537                 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
6538                     vector != DF_VECTOR && !idtv_info_valid)
6539                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6540                                       GUEST_INTR_STATE_NMI);
6541                 else
6542                         vmx->loaded_vmcs->nmi_known_unmasked =
6543                                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
6544                                   & GUEST_INTR_STATE_NMI);
6545         } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
6546                 vmx->loaded_vmcs->vnmi_blocked_time +=
6547                         ktime_to_ns(ktime_sub(ktime_get(),
6548                                               vmx->loaded_vmcs->entry_time));
6549 }
6550
6551 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
6552                                       u32 idt_vectoring_info,
6553                                       int instr_len_field,
6554                                       int error_code_field)
6555 {
6556         u8 vector;
6557         int type;
6558         bool idtv_info_valid;
6559
6560         idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
6561
6562         vcpu->arch.nmi_injected = false;
6563         kvm_clear_exception_queue(vcpu);
6564         kvm_clear_interrupt_queue(vcpu);
6565
6566         if (!idtv_info_valid)
6567                 return;
6568
6569         kvm_make_request(KVM_REQ_EVENT, vcpu);
6570
6571         vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
6572         type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
6573
6574         switch (type) {
6575         case INTR_TYPE_NMI_INTR:
6576                 vcpu->arch.nmi_injected = true;
6577                 /*
6578                  * SDM 3: 27.7.1.2 (September 2008)
6579                  * Clear bit "block by NMI" before VM entry if a NMI
6580                  * delivery faulted.
6581                  */
6582                 vmx_set_nmi_mask(vcpu, false);
6583                 break;
6584         case INTR_TYPE_SOFT_EXCEPTION:
6585                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6586                 /* fall through */
6587         case INTR_TYPE_HARD_EXCEPTION:
6588                 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
6589                         u32 err = vmcs_read32(error_code_field);
6590                         kvm_requeue_exception_e(vcpu, vector, err);
6591                 } else
6592                         kvm_requeue_exception(vcpu, vector);
6593                 break;
6594         case INTR_TYPE_SOFT_INTR:
6595                 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
6596                 /* fall through */
6597         case INTR_TYPE_EXT_INTR:
6598                 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
6599                 break;
6600         default:
6601                 break;
6602         }
6603 }
6604
6605 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
6606 {
6607         __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
6608                                   VM_EXIT_INSTRUCTION_LEN,
6609                                   IDT_VECTORING_ERROR_CODE);
6610 }
6611
6612 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
6613 {
6614         __vmx_complete_interrupts(vcpu,
6615                                   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
6616                                   VM_ENTRY_INSTRUCTION_LEN,
6617                                   VM_ENTRY_EXCEPTION_ERROR_CODE);
6618
6619         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
6620 }
6621
6622 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
6623 {
6624         int i, nr_msrs;
6625         struct perf_guest_switch_msr *msrs;
6626
6627         msrs = perf_guest_get_msrs(&nr_msrs);
6628
6629         if (!msrs)
6630                 return;
6631
6632         for (i = 0; i < nr_msrs; i++)
6633                 if (msrs[i].host == msrs[i].guest)
6634                         clear_atomic_switch_msr(vmx, msrs[i].msr);
6635                 else
6636                         add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
6637                                         msrs[i].host, false);
6638 }
6639
6640 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
6641 {
6642         struct vcpu_vmx *vmx = to_vmx(vcpu);
6643         u64 tscl;
6644         u32 delta_tsc;
6645
6646         if (vmx->req_immediate_exit) {
6647                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0);
6648                 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6649         } else if (vmx->hv_deadline_tsc != -1) {
6650                 tscl = rdtsc();
6651                 if (vmx->hv_deadline_tsc > tscl)
6652                         /* set_hv_timer ensures the delta fits in 32-bits */
6653                         delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
6654                                 cpu_preemption_timer_multi);
6655                 else
6656                         delta_tsc = 0;
6657
6658                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
6659                 vmx->loaded_vmcs->hv_timer_soft_disabled = false;
6660         } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) {
6661                 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1);
6662                 vmx->loaded_vmcs->hv_timer_soft_disabled = true;
6663         }
6664 }
6665
6666 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp)
6667 {
6668         if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) {
6669                 vmx->loaded_vmcs->host_state.rsp = host_rsp;
6670                 vmcs_writel(HOST_RSP, host_rsp);
6671         }
6672 }
6673
6674 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
6675 {
6676         switch (to_vmx(vcpu)->exit_reason) {
6677         case EXIT_REASON_MSR_WRITE:
6678                 return handle_fastpath_set_msr_irqoff(vcpu);
6679         case EXIT_REASON_PREEMPTION_TIMER:
6680                 return handle_fastpath_preemption_timer(vcpu);
6681         default:
6682                 return EXIT_FASTPATH_NONE;
6683         }
6684 }
6685
6686 bool __vmx_vcpu_run(struct vcpu_vmx *vmx, unsigned long *regs, bool launched);
6687
6688 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
6689                                         struct vcpu_vmx *vmx)
6690 {
6691         /*
6692          * VMENTER enables interrupts (host state), but the kernel state is
6693          * interrupts disabled when this is invoked. Also tell RCU about
6694          * it. This is the same logic as for exit_to_user_mode().
6695          *
6696          * This ensures that e.g. latency analysis on the host observes
6697          * guest mode as interrupt enabled.
6698          *
6699          * guest_enter_irqoff() informs context tracking about the
6700          * transition to guest mode and if enabled adjusts RCU state
6701          * accordingly.
6702          */
6703         instrumentation_begin();
6704         trace_hardirqs_on_prepare();
6705         lockdep_hardirqs_on_prepare(CALLER_ADDR0);
6706         instrumentation_end();
6707
6708         guest_enter_irqoff();
6709         lockdep_hardirqs_on(CALLER_ADDR0);
6710
6711         /* L1D Flush includes CPU buffer clear to mitigate MDS */
6712         if (static_branch_unlikely(&vmx_l1d_should_flush))
6713                 vmx_l1d_flush(vcpu);
6714         else if (static_branch_unlikely(&mds_user_clear))
6715                 mds_clear_cpu_buffers();
6716
6717         if (vcpu->arch.cr2 != native_read_cr2())
6718                 native_write_cr2(vcpu->arch.cr2);
6719
6720         vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs,
6721                                    vmx->loaded_vmcs->launched);
6722
6723         vcpu->arch.cr2 = native_read_cr2();
6724
6725         /*
6726          * VMEXIT disables interrupts (host state), but tracing and lockdep
6727          * have them in state 'on' as recorded before entering guest mode.
6728          * Same as enter_from_user_mode().
6729          *
6730          * guest_exit_irqoff() restores host context and reinstates RCU if
6731          * enabled and required.
6732          *
6733          * This needs to be done before the below as native_read_msr()
6734          * contains a tracepoint and x86_spec_ctrl_restore_host() calls
6735          * into world and some more.
6736          */
6737         lockdep_hardirqs_off(CALLER_ADDR0);
6738         guest_exit_irqoff();
6739
6740         instrumentation_begin();
6741         trace_hardirqs_off_finish();
6742         instrumentation_end();
6743 }
6744
6745 static fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu)
6746 {
6747         fastpath_t exit_fastpath;
6748         struct vcpu_vmx *vmx = to_vmx(vcpu);
6749         unsigned long cr3, cr4;
6750
6751 reenter_guest:
6752         /* Record the guest's net vcpu time for enforced NMI injections. */
6753         if (unlikely(!enable_vnmi &&
6754                      vmx->loaded_vmcs->soft_vnmi_blocked))
6755                 vmx->loaded_vmcs->entry_time = ktime_get();
6756
6757         /* Don't enter VMX if guest state is invalid, let the exit handler
6758            start emulation until we arrive back to a valid state */
6759         if (vmx->emulation_required)
6760                 return EXIT_FASTPATH_NONE;
6761
6762         if (vmx->ple_window_dirty) {
6763                 vmx->ple_window_dirty = false;
6764                 vmcs_write32(PLE_WINDOW, vmx->ple_window);
6765         }
6766
6767         /*
6768          * We did this in prepare_switch_to_guest, because it needs to
6769          * be within srcu_read_lock.
6770          */
6771         WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync);
6772
6773         if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP))
6774                 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
6775         if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP))
6776                 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
6777
6778         cr3 = __get_current_cr3_fast();
6779         if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
6780                 vmcs_writel(HOST_CR3, cr3);
6781                 vmx->loaded_vmcs->host_state.cr3 = cr3;
6782         }
6783
6784         cr4 = cr4_read_shadow();
6785         if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
6786                 vmcs_writel(HOST_CR4, cr4);
6787                 vmx->loaded_vmcs->host_state.cr4 = cr4;
6788         }
6789
6790         /* When single-stepping over STI and MOV SS, we must clear the
6791          * corresponding interruptibility bits in the guest state. Otherwise
6792          * vmentry fails as it then expects bit 14 (BS) in pending debug
6793          * exceptions being set, but that's not correct for the guest debugging
6794          * case. */
6795         if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
6796                 vmx_set_interrupt_shadow(vcpu, 0);
6797
6798         kvm_load_guest_xsave_state(vcpu);
6799
6800         pt_guest_enter(vmx);
6801
6802         atomic_switch_perf_msrs(vmx);
6803
6804         if (enable_preemption_timer)
6805                 vmx_update_hv_timer(vcpu);
6806
6807         if (lapic_in_kernel(vcpu) &&
6808                 vcpu->arch.apic->lapic_timer.timer_advance_ns)
6809                 kvm_wait_lapic_expire(vcpu);
6810
6811         /*
6812          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
6813          * it's non-zero. Since vmentry is serialising on affected CPUs, there
6814          * is no need to worry about the conditional branch over the wrmsr
6815          * being speculatively taken.
6816          */
6817         x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
6818
6819         /* The actual VMENTER/EXIT is in the .noinstr.text section. */
6820         vmx_vcpu_enter_exit(vcpu, vmx);
6821
6822         /*
6823          * We do not use IBRS in the kernel. If this vCPU has used the
6824          * SPEC_CTRL MSR it may have left it on; save the value and
6825          * turn it off. This is much more efficient than blindly adding
6826          * it to the atomic save/restore list. Especially as the former
6827          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
6828          *
6829          * For non-nested case:
6830          * If the L01 MSR bitmap does not intercept the MSR, then we need to
6831          * save it.
6832          *
6833          * For nested case:
6834          * If the L02 MSR bitmap does not intercept the MSR, then we need to
6835          * save it.
6836          */
6837         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
6838                 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
6839
6840         x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
6841
6842         /* All fields are clean at this point */
6843         if (static_branch_unlikely(&enable_evmcs))
6844                 current_evmcs->hv_clean_fields |=
6845                         HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
6846
6847         if (static_branch_unlikely(&enable_evmcs))
6848                 current_evmcs->hv_vp_id = vcpu->arch.hyperv.vp_index;
6849
6850         /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
6851         if (vmx->host_debugctlmsr)
6852                 update_debugctlmsr(vmx->host_debugctlmsr);
6853
6854 #ifndef CONFIG_X86_64
6855         /*
6856          * The sysexit path does not restore ds/es, so we must set them to
6857          * a reasonable value ourselves.
6858          *
6859          * We can't defer this to vmx_prepare_switch_to_host() since that
6860          * function may be executed in interrupt context, which saves and
6861          * restore segments around it, nullifying its effect.
6862          */
6863         loadsegment(ds, __USER_DS);
6864         loadsegment(es, __USER_DS);
6865 #endif
6866
6867         vmx_register_cache_reset(vcpu);
6868
6869         pt_guest_exit(vmx);
6870
6871         kvm_load_host_xsave_state(vcpu);
6872
6873         vmx->nested.nested_run_pending = 0;
6874         vmx->idt_vectoring_info = 0;
6875
6876         if (unlikely(vmx->fail)) {
6877                 vmx->exit_reason = 0xdead;
6878                 return EXIT_FASTPATH_NONE;
6879         }
6880
6881         vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
6882         if (unlikely((u16)vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY))
6883                 kvm_machine_check();
6884
6885         trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
6886
6887         if (unlikely(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6888                 return EXIT_FASTPATH_NONE;
6889
6890         vmx->loaded_vmcs->launched = 1;
6891         vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
6892
6893         vmx_recover_nmi_blocking(vmx);
6894         vmx_complete_interrupts(vmx);
6895
6896         if (is_guest_mode(vcpu))
6897                 return EXIT_FASTPATH_NONE;
6898
6899         exit_fastpath = vmx_exit_handlers_fastpath(vcpu);
6900         if (exit_fastpath == EXIT_FASTPATH_REENTER_GUEST) {
6901                 if (!kvm_vcpu_exit_request(vcpu)) {
6902                         /*
6903                          * FIXME: this goto should be a loop in vcpu_enter_guest,
6904                          * but it would incur the cost of a retpoline for now.
6905                          * Revisit once static calls are available.
6906                          */
6907                         if (vcpu->arch.apicv_active)
6908                                 vmx_sync_pir_to_irr(vcpu);
6909                         goto reenter_guest;
6910                 }
6911                 exit_fastpath = EXIT_FASTPATH_EXIT_HANDLED;
6912         }
6913
6914         return exit_fastpath;
6915 }
6916
6917 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
6918 {
6919         struct vcpu_vmx *vmx = to_vmx(vcpu);
6920
6921         if (enable_pml)
6922                 vmx_destroy_pml_buffer(vmx);
6923         free_vpid(vmx->vpid);
6924         nested_vmx_free_vcpu(vcpu);
6925         free_loaded_vmcs(vmx->loaded_vmcs);
6926 }
6927
6928 static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
6929 {
6930         struct vcpu_vmx *vmx;
6931         unsigned long *msr_bitmap;
6932         int i, cpu, err;
6933
6934         BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
6935         vmx = to_vmx(vcpu);
6936
6937         err = -ENOMEM;
6938
6939         vmx->vpid = allocate_vpid();
6940
6941         /*
6942          * If PML is turned on, failure on enabling PML just results in failure
6943          * of creating the vcpu, therefore we can simplify PML logic (by
6944          * avoiding dealing with cases, such as enabling PML partially on vcpus
6945          * for the guest), etc.
6946          */
6947         if (enable_pml) {
6948                 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
6949                 if (!vmx->pml_pg)
6950                         goto free_vpid;
6951         }
6952
6953         BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) != NR_SHARED_MSRS);
6954
6955         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6956                 u32 index = vmx_msr_index[i];
6957                 u32 data_low, data_high;
6958                 int j = vmx->nmsrs;
6959
6960                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6961                         continue;
6962                 if (wrmsr_safe(index, data_low, data_high) < 0)
6963                         continue;
6964
6965                 vmx->guest_msrs[j].index = i;
6966                 vmx->guest_msrs[j].data = 0;
6967                 switch (index) {
6968                 case MSR_IA32_TSX_CTRL:
6969                         /*
6970                          * No need to pass TSX_CTRL_CPUID_CLEAR through, so
6971                          * let's avoid changing CPUID bits under the host
6972                          * kernel's feet.
6973                          */
6974                         vmx->guest_msrs[j].mask = ~(u64)TSX_CTRL_CPUID_CLEAR;
6975                         break;
6976                 default:
6977                         vmx->guest_msrs[j].mask = -1ull;
6978                         break;
6979                 }
6980                 ++vmx->nmsrs;
6981         }
6982
6983         err = alloc_loaded_vmcs(&vmx->vmcs01);
6984         if (err < 0)
6985                 goto free_pml;
6986
6987         msr_bitmap = vmx->vmcs01.msr_bitmap;
6988         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_TSC, MSR_TYPE_R);
6989         vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
6990         vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
6991         vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
6992         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
6993         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
6994         vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
6995         if (kvm_cstate_in_guest(vcpu->kvm)) {
6996                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
6997                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
6998                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
6999                 vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R);
7000         }
7001         vmx->msr_bitmap_mode = 0;
7002
7003         vmx->loaded_vmcs = &vmx->vmcs01;
7004         cpu = get_cpu();
7005         vmx_vcpu_load(vcpu, cpu);
7006         vcpu->cpu = cpu;
7007         init_vmcs(vmx);
7008         vmx_vcpu_put(vcpu);
7009         put_cpu();
7010         if (cpu_need_virtualize_apic_accesses(vcpu)) {
7011                 err = alloc_apic_access_page(vcpu->kvm);
7012                 if (err)
7013                         goto free_vmcs;
7014         }
7015
7016         if (enable_ept && !enable_unrestricted_guest) {
7017                 err = init_rmode_identity_map(vcpu->kvm);
7018                 if (err)
7019                         goto free_vmcs;
7020         }
7021
7022         if (nested)
7023                 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
7024                                            vmx_capability.ept);
7025         else
7026                 memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
7027
7028         vmx->nested.posted_intr_nv = -1;
7029         vmx->nested.current_vmptr = -1ull;
7030
7031         vcpu->arch.microcode_version = 0x100000000ULL;
7032         vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
7033
7034         /*
7035          * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
7036          * or POSTED_INTR_WAKEUP_VECTOR.
7037          */
7038         vmx->pi_desc.nv = POSTED_INTR_VECTOR;
7039         vmx->pi_desc.sn = 1;
7040
7041         vmx->ept_pointer = INVALID_PAGE;
7042
7043         return 0;
7044
7045 free_vmcs:
7046         free_loaded_vmcs(vmx->loaded_vmcs);
7047 free_pml:
7048         vmx_destroy_pml_buffer(vmx);
7049 free_vpid:
7050         free_vpid(vmx->vpid);
7051         return err;
7052 }
7053
7054 #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"
7055 #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"
7056
7057 static int vmx_vm_init(struct kvm *kvm)
7058 {
7059         spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
7060
7061         if (!ple_gap)
7062                 kvm->arch.pause_in_guest = true;
7063
7064         if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
7065                 switch (l1tf_mitigation) {
7066                 case L1TF_MITIGATION_OFF:
7067                 case L1TF_MITIGATION_FLUSH_NOWARN:
7068                         /* 'I explicitly don't care' is set */
7069                         break;
7070                 case L1TF_MITIGATION_FLUSH:
7071                 case L1TF_MITIGATION_FLUSH_NOSMT:
7072                 case L1TF_MITIGATION_FULL:
7073                         /*
7074                          * Warn upon starting the first VM in a potentially
7075                          * insecure environment.
7076                          */
7077                         if (sched_smt_active())
7078                                 pr_warn_once(L1TF_MSG_SMT);
7079                         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
7080                                 pr_warn_once(L1TF_MSG_L1D);
7081                         break;
7082                 case L1TF_MITIGATION_FULL_FORCE:
7083                         /* Flush is enforced */
7084                         break;
7085                 }
7086         }
7087         kvm_apicv_init(kvm, enable_apicv);
7088         return 0;
7089 }
7090
7091 static int __init vmx_check_processor_compat(void)
7092 {
7093         struct vmcs_config vmcs_conf;
7094         struct vmx_capability vmx_cap;
7095
7096         if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
7097             !this_cpu_has(X86_FEATURE_VMX)) {
7098                 pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
7099                 return -EIO;
7100         }
7101
7102         if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
7103                 return -EIO;
7104         if (nested)
7105                 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, vmx_cap.ept);
7106         if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
7107                 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
7108                                 smp_processor_id());
7109                 return -EIO;
7110         }
7111         return 0;
7112 }
7113
7114 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
7115 {
7116         u8 cache;
7117         u64 ipat = 0;
7118
7119         /* We wanted to honor guest CD/MTRR/PAT, but doing so could result in
7120          * memory aliases with conflicting memory types and sometimes MCEs.
7121          * We have to be careful as to what are honored and when.
7122          *
7123          * For MMIO, guest CD/MTRR are ignored.  The EPT memory type is set to
7124          * UC.  The effective memory type is UC or WC depending on guest PAT.
7125          * This was historically the source of MCEs and we want to be
7126          * conservative.
7127          *
7128          * When there is no need to deal with noncoherent DMA (e.g., no VT-d
7129          * or VT-d has snoop control), guest CD/MTRR/PAT are all ignored.  The
7130          * EPT memory type is set to WB.  The effective memory type is forced
7131          * WB.
7132          *
7133          * Otherwise, we trust guest.  Guest CD/MTRR/PAT are all honored.  The
7134          * EPT memory type is used to emulate guest CD/MTRR.
7135          */
7136
7137         if (is_mmio) {
7138                 cache = MTRR_TYPE_UNCACHABLE;
7139                 goto exit;
7140         }
7141
7142         if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
7143                 ipat = VMX_EPT_IPAT_BIT;
7144                 cache = MTRR_TYPE_WRBACK;
7145                 goto exit;
7146         }
7147
7148         if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
7149                 ipat = VMX_EPT_IPAT_BIT;
7150                 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
7151                         cache = MTRR_TYPE_WRBACK;
7152                 else
7153                         cache = MTRR_TYPE_UNCACHABLE;
7154                 goto exit;
7155         }
7156
7157         cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
7158
7159 exit:
7160         return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
7161 }
7162
7163 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx)
7164 {
7165         /*
7166          * These bits in the secondary execution controls field
7167          * are dynamic, the others are mostly based on the hypervisor
7168          * architecture and the guest's CPUID.  Do not touch the
7169          * dynamic bits.
7170          */
7171         u32 mask =
7172                 SECONDARY_EXEC_SHADOW_VMCS |
7173                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
7174                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
7175                 SECONDARY_EXEC_DESC;
7176
7177         u32 new_ctl = vmx->secondary_exec_control;
7178         u32 cur_ctl = secondary_exec_controls_get(vmx);
7179
7180         secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask));
7181 }
7182
7183 /*
7184  * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
7185  * (indicating "allowed-1") if they are supported in the guest's CPUID.
7186  */
7187 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
7188 {
7189         struct vcpu_vmx *vmx = to_vmx(vcpu);
7190         struct kvm_cpuid_entry2 *entry;
7191
7192         vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
7193         vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
7194
7195 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do {            \
7196         if (entry && (entry->_reg & (_cpuid_mask)))                     \
7197                 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask);     \
7198 } while (0)
7199
7200         entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
7201         cr4_fixed1_update(X86_CR4_VME,        edx, feature_bit(VME));
7202         cr4_fixed1_update(X86_CR4_PVI,        edx, feature_bit(VME));
7203         cr4_fixed1_update(X86_CR4_TSD,        edx, feature_bit(TSC));
7204         cr4_fixed1_update(X86_CR4_DE,         edx, feature_bit(DE));
7205         cr4_fixed1_update(X86_CR4_PSE,        edx, feature_bit(PSE));
7206         cr4_fixed1_update(X86_CR4_PAE,        edx, feature_bit(PAE));
7207         cr4_fixed1_update(X86_CR4_MCE,        edx, feature_bit(MCE));
7208         cr4_fixed1_update(X86_CR4_PGE,        edx, feature_bit(PGE));
7209         cr4_fixed1_update(X86_CR4_OSFXSR,     edx, feature_bit(FXSR));
7210         cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
7211         cr4_fixed1_update(X86_CR4_VMXE,       ecx, feature_bit(VMX));
7212         cr4_fixed1_update(X86_CR4_SMXE,       ecx, feature_bit(SMX));
7213         cr4_fixed1_update(X86_CR4_PCIDE,      ecx, feature_bit(PCID));
7214         cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, feature_bit(XSAVE));
7215
7216         entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
7217         cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, feature_bit(FSGSBASE));
7218         cr4_fixed1_update(X86_CR4_SMEP,       ebx, feature_bit(SMEP));
7219         cr4_fixed1_update(X86_CR4_SMAP,       ebx, feature_bit(SMAP));
7220         cr4_fixed1_update(X86_CR4_PKE,        ecx, feature_bit(PKU));
7221         cr4_fixed1_update(X86_CR4_UMIP,       ecx, feature_bit(UMIP));
7222         cr4_fixed1_update(X86_CR4_LA57,       ecx, feature_bit(LA57));
7223
7224 #undef cr4_fixed1_update
7225 }
7226
7227 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
7228 {
7229         struct vcpu_vmx *vmx = to_vmx(vcpu);
7230
7231         if (kvm_mpx_supported()) {
7232                 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
7233
7234                 if (mpx_enabled) {
7235                         vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
7236                         vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
7237                 } else {
7238                         vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
7239                         vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
7240                 }
7241         }
7242 }
7243
7244 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
7245 {
7246         struct vcpu_vmx *vmx = to_vmx(vcpu);
7247         struct kvm_cpuid_entry2 *best = NULL;
7248         int i;
7249
7250         for (i = 0; i < PT_CPUID_LEAVES; i++) {
7251                 best = kvm_find_cpuid_entry(vcpu, 0x14, i);
7252                 if (!best)
7253                         return;
7254                 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax;
7255                 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx;
7256                 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx;
7257                 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx;
7258         }
7259
7260         /* Get the number of configurable Address Ranges for filtering */
7261         vmx->pt_desc.addr_range = intel_pt_validate_cap(vmx->pt_desc.caps,
7262                                                 PT_CAP_num_address_ranges);
7263
7264         /* Initialize and clear the no dependency bits */
7265         vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS |
7266                         RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC);
7267
7268         /*
7269          * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise
7270          * will inject an #GP
7271          */
7272         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering))
7273                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN;
7274
7275         /*
7276          * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and
7277          * PSBFreq can be set
7278          */
7279         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc))
7280                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC |
7281                                 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ);
7282
7283         /*
7284          * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn BranchEn and
7285          * MTCFreq can be set
7286          */
7287         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc))
7288                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN |
7289                                 RTIT_CTL_BRANCH_EN | RTIT_CTL_MTC_RANGE);
7290
7291         /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */
7292         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite))
7293                 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW |
7294                                                         RTIT_CTL_PTW_EN);
7295
7296         /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */
7297         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace))
7298                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN;
7299
7300         /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */
7301         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output))
7302                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA;
7303
7304         /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabircEn can be set */
7305         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys))
7306                 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN;
7307
7308         /* unmask address range configure area */
7309         for (i = 0; i < vmx->pt_desc.addr_range; i++)
7310                 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
7311 }
7312
7313 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
7314 {
7315         struct vcpu_vmx *vmx = to_vmx(vcpu);
7316
7317         /* xsaves_enabled is recomputed in vmx_compute_secondary_exec_control(). */
7318         vcpu->arch.xsaves_enabled = false;
7319
7320         if (cpu_has_secondary_exec_ctrls()) {
7321                 vmx_compute_secondary_exec_control(vmx);
7322                 vmcs_set_secondary_exec_control(vmx);
7323         }
7324
7325         if (nested_vmx_allowed(vcpu))
7326                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7327                         FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7328                         FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
7329         else
7330                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7331                         ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
7332                           FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
7333
7334         if (nested_vmx_allowed(vcpu)) {
7335                 nested_vmx_cr_fixed1_bits_update(vcpu);
7336                 nested_vmx_entry_exit_ctls_update(vcpu);
7337         }
7338
7339         if (boot_cpu_has(X86_FEATURE_INTEL_PT) &&
7340                         guest_cpuid_has(vcpu, X86_FEATURE_INTEL_PT))
7341                 update_intel_pt_cfg(vcpu);
7342
7343         if (boot_cpu_has(X86_FEATURE_RTM)) {
7344                 struct shared_msr_entry *msr;
7345                 msr = find_msr_entry(vmx, MSR_IA32_TSX_CTRL);
7346                 if (msr) {
7347                         bool enabled = guest_cpuid_has(vcpu, X86_FEATURE_RTM);
7348                         vmx_set_guest_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE);
7349                 }
7350         }
7351 }
7352
7353 static __init void vmx_set_cpu_caps(void)
7354 {
7355         kvm_set_cpu_caps();
7356
7357         /* CPUID 0x1 */
7358         if (nested)
7359                 kvm_cpu_cap_set(X86_FEATURE_VMX);
7360
7361         /* CPUID 0x7 */
7362         if (kvm_mpx_supported())
7363                 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX);
7364         if (cpu_has_vmx_invpcid())
7365                 kvm_cpu_cap_check_and_set(X86_FEATURE_INVPCID);
7366         if (vmx_pt_mode_is_host_guest())
7367                 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT);
7368
7369         if (vmx_umip_emulated())
7370                 kvm_cpu_cap_set(X86_FEATURE_UMIP);
7371
7372         /* CPUID 0xD.1 */
7373         supported_xss = 0;
7374         if (!vmx_xsaves_supported())
7375                 kvm_cpu_cap_clear(X86_FEATURE_XSAVES);
7376
7377         /* CPUID 0x80000001 */
7378         if (!cpu_has_vmx_rdtscp())
7379                 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP);
7380
7381         if (vmx_waitpkg_supported())
7382                 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG);
7383 }
7384
7385 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
7386 {
7387         to_vmx(vcpu)->req_immediate_exit = true;
7388 }
7389
7390 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
7391                                   struct x86_instruction_info *info)
7392 {
7393         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7394         unsigned short port;
7395         bool intercept;
7396         int size;
7397
7398         if (info->intercept == x86_intercept_in ||
7399             info->intercept == x86_intercept_ins) {
7400                 port = info->src_val;
7401                 size = info->dst_bytes;
7402         } else {
7403                 port = info->dst_val;
7404                 size = info->src_bytes;
7405         }
7406
7407         /*
7408          * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
7409          * VM-exits depend on the 'unconditional IO exiting' VM-execution
7410          * control.
7411          *
7412          * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
7413          */
7414         if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
7415                 intercept = nested_cpu_has(vmcs12,
7416                                            CPU_BASED_UNCOND_IO_EXITING);
7417         else
7418                 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
7419
7420         /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED.  */
7421         return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
7422 }
7423
7424 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
7425                                struct x86_instruction_info *info,
7426                                enum x86_intercept_stage stage,
7427                                struct x86_exception *exception)
7428 {
7429         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7430
7431         switch (info->intercept) {
7432         /*
7433          * RDPID causes #UD if disabled through secondary execution controls.
7434          * Because it is marked as EmulateOnUD, we need to intercept it here.
7435          */
7436         case x86_intercept_rdtscp:
7437                 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
7438                         exception->vector = UD_VECTOR;
7439                         exception->error_code_valid = false;
7440                         return X86EMUL_PROPAGATE_FAULT;
7441                 }
7442                 break;
7443
7444         case x86_intercept_in:
7445         case x86_intercept_ins:
7446         case x86_intercept_out:
7447         case x86_intercept_outs:
7448                 return vmx_check_intercept_io(vcpu, info);
7449
7450         case x86_intercept_lgdt:
7451         case x86_intercept_lidt:
7452         case x86_intercept_lldt:
7453         case x86_intercept_ltr:
7454         case x86_intercept_sgdt:
7455         case x86_intercept_sidt:
7456         case x86_intercept_sldt:
7457         case x86_intercept_str:
7458                 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
7459                         return X86EMUL_CONTINUE;
7460
7461                 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED.  */
7462                 break;
7463
7464         /* TODO: check more intercepts... */
7465         default:
7466                 break;
7467         }
7468
7469         return X86EMUL_UNHANDLEABLE;
7470 }
7471
7472 #ifdef CONFIG_X86_64
7473 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
7474 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
7475                                   u64 divisor, u64 *result)
7476 {
7477         u64 low = a << shift, high = a >> (64 - shift);
7478
7479         /* To avoid the overflow on divq */
7480         if (high >= divisor)
7481                 return 1;
7482
7483         /* Low hold the result, high hold rem which is discarded */
7484         asm("divq %2\n\t" : "=a" (low), "=d" (high) :
7485             "rm" (divisor), "0" (low), "1" (high));
7486         *result = low;
7487
7488         return 0;
7489 }
7490
7491 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc,
7492                             bool *expired)
7493 {
7494         struct vcpu_vmx *vmx;
7495         u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
7496         struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer;
7497
7498         vmx = to_vmx(vcpu);
7499         tscl = rdtsc();
7500         guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
7501         delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
7502         lapic_timer_advance_cycles = nsec_to_cycles(vcpu,
7503                                                     ktimer->timer_advance_ns);
7504
7505         if (delta_tsc > lapic_timer_advance_cycles)
7506                 delta_tsc -= lapic_timer_advance_cycles;
7507         else
7508                 delta_tsc = 0;
7509
7510         /* Convert to host delta tsc if tsc scaling is enabled */
7511         if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
7512             delta_tsc && u64_shl_div_u64(delta_tsc,
7513                                 kvm_tsc_scaling_ratio_frac_bits,
7514                                 vcpu->arch.tsc_scaling_ratio, &delta_tsc))
7515                 return -ERANGE;
7516
7517         /*
7518          * If the delta tsc can't fit in the 32 bit after the multi shift,
7519          * we can't use the preemption timer.
7520          * It's possible that it fits on later vmentries, but checking
7521          * on every vmentry is costly so we just use an hrtimer.
7522          */
7523         if (delta_tsc >> (cpu_preemption_timer_multi + 32))
7524                 return -ERANGE;
7525
7526         vmx->hv_deadline_tsc = tscl + delta_tsc;
7527         *expired = !delta_tsc;
7528         return 0;
7529 }
7530
7531 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
7532 {
7533         to_vmx(vcpu)->hv_deadline_tsc = -1;
7534 }
7535 #endif
7536
7537 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
7538 {
7539         if (!kvm_pause_in_guest(vcpu->kvm))
7540                 shrink_ple_window(vcpu);
7541 }
7542
7543 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
7544                                      struct kvm_memory_slot *slot)
7545 {
7546         if (!kvm_dirty_log_manual_protect_and_init_set(kvm))
7547                 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
7548         kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
7549 }
7550
7551 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
7552                                        struct kvm_memory_slot *slot)
7553 {
7554         kvm_mmu_slot_set_dirty(kvm, slot);
7555 }
7556
7557 static void vmx_flush_log_dirty(struct kvm *kvm)
7558 {
7559         kvm_flush_pml_buffers(kvm);
7560 }
7561
7562 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
7563                                            struct kvm_memory_slot *memslot,
7564                                            gfn_t offset, unsigned long mask)
7565 {
7566         kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
7567 }
7568
7569 static void __pi_post_block(struct kvm_vcpu *vcpu)
7570 {
7571         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7572         struct pi_desc old, new;
7573         unsigned int dest;
7574
7575         do {
7576                 old.control = new.control = pi_desc->control;
7577                 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
7578                      "Wakeup handler not enabled while the VCPU is blocked\n");
7579
7580                 dest = cpu_physical_id(vcpu->cpu);
7581
7582                 if (x2apic_enabled())
7583                         new.ndst = dest;
7584                 else
7585                         new.ndst = (dest << 8) & 0xFF00;
7586
7587                 /* set 'NV' to 'notification vector' */
7588                 new.nv = POSTED_INTR_VECTOR;
7589         } while (cmpxchg64(&pi_desc->control, old.control,
7590                            new.control) != old.control);
7591
7592         if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
7593                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7594                 list_del(&vcpu->blocked_vcpu_list);
7595                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7596                 vcpu->pre_pcpu = -1;
7597         }
7598 }
7599
7600 /*
7601  * This routine does the following things for vCPU which is going
7602  * to be blocked if VT-d PI is enabled.
7603  * - Store the vCPU to the wakeup list, so when interrupts happen
7604  *   we can find the right vCPU to wake up.
7605  * - Change the Posted-interrupt descriptor as below:
7606  *      'NDST' <-- vcpu->pre_pcpu
7607  *      'NV' <-- POSTED_INTR_WAKEUP_VECTOR
7608  * - If 'ON' is set during this process, which means at least one
7609  *   interrupt is posted for this vCPU, we cannot block it, in
7610  *   this case, return 1, otherwise, return 0.
7611  *
7612  */
7613 static int pi_pre_block(struct kvm_vcpu *vcpu)
7614 {
7615         unsigned int dest;
7616         struct pi_desc old, new;
7617         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7618
7619         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
7620                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
7621                 !kvm_vcpu_apicv_active(vcpu))
7622                 return 0;
7623
7624         WARN_ON(irqs_disabled());
7625         local_irq_disable();
7626         if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
7627                 vcpu->pre_pcpu = vcpu->cpu;
7628                 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7629                 list_add_tail(&vcpu->blocked_vcpu_list,
7630                               &per_cpu(blocked_vcpu_on_cpu,
7631                                        vcpu->pre_pcpu));
7632                 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
7633         }
7634
7635         do {
7636                 old.control = new.control = pi_desc->control;
7637
7638                 WARN((pi_desc->sn == 1),
7639                      "Warning: SN field of posted-interrupts "
7640                      "is set before blocking\n");
7641
7642                 /*
7643                  * Since vCPU can be preempted during this process,
7644                  * vcpu->cpu could be different with pre_pcpu, we
7645                  * need to set pre_pcpu as the destination of wakeup
7646                  * notification event, then we can find the right vCPU
7647                  * to wakeup in wakeup handler if interrupts happen
7648                  * when the vCPU is in blocked state.
7649                  */
7650                 dest = cpu_physical_id(vcpu->pre_pcpu);
7651
7652                 if (x2apic_enabled())
7653                         new.ndst = dest;
7654                 else
7655                         new.ndst = (dest << 8) & 0xFF00;
7656
7657                 /* set 'NV' to 'wakeup vector' */
7658                 new.nv = POSTED_INTR_WAKEUP_VECTOR;
7659         } while (cmpxchg64(&pi_desc->control, old.control,
7660                            new.control) != old.control);
7661
7662         /* We should not block the vCPU if an interrupt is posted for it.  */
7663         if (pi_test_on(pi_desc) == 1)
7664                 __pi_post_block(vcpu);
7665
7666         local_irq_enable();
7667         return (vcpu->pre_pcpu == -1);
7668 }
7669
7670 static int vmx_pre_block(struct kvm_vcpu *vcpu)
7671 {
7672         if (pi_pre_block(vcpu))
7673                 return 1;
7674
7675         if (kvm_lapic_hv_timer_in_use(vcpu))
7676                 kvm_lapic_switch_to_sw_timer(vcpu);
7677
7678         return 0;
7679 }
7680
7681 static void pi_post_block(struct kvm_vcpu *vcpu)
7682 {
7683         if (vcpu->pre_pcpu == -1)
7684                 return;
7685
7686         WARN_ON(irqs_disabled());
7687         local_irq_disable();
7688         __pi_post_block(vcpu);
7689         local_irq_enable();
7690 }
7691
7692 static void vmx_post_block(struct kvm_vcpu *vcpu)
7693 {
7694         if (kvm_x86_ops.set_hv_timer)
7695                 kvm_lapic_switch_to_hv_timer(vcpu);
7696
7697         pi_post_block(vcpu);
7698 }
7699
7700 /*
7701  * vmx_update_pi_irte - set IRTE for Posted-Interrupts
7702  *
7703  * @kvm: kvm
7704  * @host_irq: host irq of the interrupt
7705  * @guest_irq: gsi of the interrupt
7706  * @set: set or unset PI
7707  * returns 0 on success, < 0 on failure
7708  */
7709 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
7710                               uint32_t guest_irq, bool set)
7711 {
7712         struct kvm_kernel_irq_routing_entry *e;
7713         struct kvm_irq_routing_table *irq_rt;
7714         struct kvm_lapic_irq irq;
7715         struct kvm_vcpu *vcpu;
7716         struct vcpu_data vcpu_info;
7717         int idx, ret = 0;
7718
7719         if (!kvm_arch_has_assigned_device(kvm) ||
7720                 !irq_remapping_cap(IRQ_POSTING_CAP) ||
7721                 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
7722                 return 0;
7723
7724         idx = srcu_read_lock(&kvm->irq_srcu);
7725         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
7726         if (guest_irq >= irq_rt->nr_rt_entries ||
7727             hlist_empty(&irq_rt->map[guest_irq])) {
7728                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
7729                              guest_irq, irq_rt->nr_rt_entries);
7730                 goto out;
7731         }
7732
7733         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
7734                 if (e->type != KVM_IRQ_ROUTING_MSI)
7735                         continue;
7736                 /*
7737                  * VT-d PI cannot support posting multicast/broadcast
7738                  * interrupts to a vCPU, we still use interrupt remapping
7739                  * for these kind of interrupts.
7740                  *
7741                  * For lowest-priority interrupts, we only support
7742                  * those with single CPU as the destination, e.g. user
7743                  * configures the interrupts via /proc/irq or uses
7744                  * irqbalance to make the interrupts single-CPU.
7745                  *
7746                  * We will support full lowest-priority interrupt later.
7747                  *
7748                  * In addition, we can only inject generic interrupts using
7749                  * the PI mechanism, refuse to route others through it.
7750                  */
7751
7752                 kvm_set_msi_irq(kvm, e, &irq);
7753                 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
7754                     !kvm_irq_is_postable(&irq)) {
7755                         /*
7756                          * Make sure the IRTE is in remapped mode if
7757                          * we don't handle it in posted mode.
7758                          */
7759                         ret = irq_set_vcpu_affinity(host_irq, NULL);
7760                         if (ret < 0) {
7761                                 printk(KERN_INFO
7762                                    "failed to back to remapped mode, irq: %u\n",
7763                                    host_irq);
7764                                 goto out;
7765                         }
7766
7767                         continue;
7768                 }
7769
7770                 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
7771                 vcpu_info.vector = irq.vector;
7772
7773                 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
7774                                 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
7775
7776                 if (set)
7777                         ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
7778                 else
7779                         ret = irq_set_vcpu_affinity(host_irq, NULL);
7780
7781                 if (ret < 0) {
7782                         printk(KERN_INFO "%s: failed to update PI IRTE\n",
7783                                         __func__);
7784                         goto out;
7785                 }
7786         }
7787
7788         ret = 0;
7789 out:
7790         srcu_read_unlock(&kvm->irq_srcu, idx);
7791         return ret;
7792 }
7793
7794 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
7795 {
7796         if (vcpu->arch.mcg_cap & MCG_LMCE_P)
7797                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
7798                         FEAT_CTL_LMCE_ENABLED;
7799         else
7800                 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
7801                         ~FEAT_CTL_LMCE_ENABLED;
7802 }
7803
7804 static int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
7805 {
7806         /* we need a nested vmexit to enter SMM, postpone if run is pending */
7807         if (to_vmx(vcpu)->nested.nested_run_pending)
7808                 return -EBUSY;
7809         return !is_smm(vcpu);
7810 }
7811
7812 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
7813 {
7814         struct vcpu_vmx *vmx = to_vmx(vcpu);
7815
7816         vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
7817         if (vmx->nested.smm.guest_mode)
7818                 nested_vmx_vmexit(vcpu, -1, 0, 0);
7819
7820         vmx->nested.smm.vmxon = vmx->nested.vmxon;
7821         vmx->nested.vmxon = false;
7822         vmx_clear_hlt(vcpu);
7823         return 0;
7824 }
7825
7826 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
7827 {
7828         struct vcpu_vmx *vmx = to_vmx(vcpu);
7829         int ret;
7830
7831         if (vmx->nested.smm.vmxon) {
7832                 vmx->nested.vmxon = true;
7833                 vmx->nested.smm.vmxon = false;
7834         }
7835
7836         if (vmx->nested.smm.guest_mode) {
7837                 ret = nested_vmx_enter_non_root_mode(vcpu, false);
7838                 if (ret)
7839                         return ret;
7840
7841                 vmx->nested.smm.guest_mode = false;
7842         }
7843         return 0;
7844 }
7845
7846 static void enable_smi_window(struct kvm_vcpu *vcpu)
7847 {
7848         /* RSM will cause a vmexit anyway.  */
7849 }
7850
7851 static bool vmx_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7852 {
7853         return false;
7854 }
7855
7856 static bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7857 {
7858         return to_vmx(vcpu)->nested.vmxon;
7859 }
7860
7861 static void vmx_migrate_timers(struct kvm_vcpu *vcpu)
7862 {
7863         if (is_guest_mode(vcpu)) {
7864                 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer;
7865
7866                 if (hrtimer_try_to_cancel(timer) == 1)
7867                         hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
7868         }
7869 }
7870
7871 static void hardware_unsetup(void)
7872 {
7873         if (nested)
7874                 nested_vmx_hardware_unsetup();
7875
7876         free_kvm_area();
7877 }
7878
7879 static bool vmx_check_apicv_inhibit_reasons(ulong bit)
7880 {
7881         ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7882                           BIT(APICV_INHIBIT_REASON_HYPERV);
7883
7884         return supported & BIT(bit);
7885 }
7886
7887 static struct kvm_x86_ops vmx_x86_ops __initdata = {
7888         .hardware_unsetup = hardware_unsetup,
7889
7890         .hardware_enable = hardware_enable,
7891         .hardware_disable = hardware_disable,
7892         .cpu_has_accelerated_tpr = report_flexpriority,
7893         .has_emulated_msr = vmx_has_emulated_msr,
7894
7895         .vm_size = sizeof(struct kvm_vmx),
7896         .vm_init = vmx_vm_init,
7897
7898         .vcpu_create = vmx_create_vcpu,
7899         .vcpu_free = vmx_free_vcpu,
7900         .vcpu_reset = vmx_vcpu_reset,
7901
7902         .prepare_guest_switch = vmx_prepare_switch_to_guest,
7903         .vcpu_load = vmx_vcpu_load,
7904         .vcpu_put = vmx_vcpu_put,
7905
7906         .update_exception_bitmap = update_exception_bitmap,
7907         .get_msr_feature = vmx_get_msr_feature,
7908         .get_msr = vmx_get_msr,
7909         .set_msr = vmx_set_msr,
7910         .get_segment_base = vmx_get_segment_base,
7911         .get_segment = vmx_get_segment,
7912         .set_segment = vmx_set_segment,
7913         .get_cpl = vmx_get_cpl,
7914         .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
7915         .set_cr0 = vmx_set_cr0,
7916         .set_cr4 = vmx_set_cr4,
7917         .set_efer = vmx_set_efer,
7918         .get_idt = vmx_get_idt,
7919         .set_idt = vmx_set_idt,
7920         .get_gdt = vmx_get_gdt,
7921         .set_gdt = vmx_set_gdt,
7922         .set_dr7 = vmx_set_dr7,
7923         .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
7924         .cache_reg = vmx_cache_reg,
7925         .get_rflags = vmx_get_rflags,
7926         .set_rflags = vmx_set_rflags,
7927
7928         .tlb_flush_all = vmx_flush_tlb_all,
7929         .tlb_flush_current = vmx_flush_tlb_current,
7930         .tlb_flush_gva = vmx_flush_tlb_gva,
7931         .tlb_flush_guest = vmx_flush_tlb_guest,
7932
7933         .run = vmx_vcpu_run,
7934         .handle_exit = vmx_handle_exit,
7935         .skip_emulated_instruction = vmx_skip_emulated_instruction,
7936         .update_emulated_instruction = vmx_update_emulated_instruction,
7937         .set_interrupt_shadow = vmx_set_interrupt_shadow,
7938         .get_interrupt_shadow = vmx_get_interrupt_shadow,
7939         .patch_hypercall = vmx_patch_hypercall,
7940         .set_irq = vmx_inject_irq,
7941         .set_nmi = vmx_inject_nmi,
7942         .queue_exception = vmx_queue_exception,
7943         .cancel_injection = vmx_cancel_injection,
7944         .interrupt_allowed = vmx_interrupt_allowed,
7945         .nmi_allowed = vmx_nmi_allowed,
7946         .get_nmi_mask = vmx_get_nmi_mask,
7947         .set_nmi_mask = vmx_set_nmi_mask,
7948         .enable_nmi_window = enable_nmi_window,
7949         .enable_irq_window = enable_irq_window,
7950         .update_cr8_intercept = update_cr8_intercept,
7951         .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
7952         .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
7953         .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
7954         .load_eoi_exitmap = vmx_load_eoi_exitmap,
7955         .apicv_post_state_restore = vmx_apicv_post_state_restore,
7956         .check_apicv_inhibit_reasons = vmx_check_apicv_inhibit_reasons,
7957         .hwapic_irr_update = vmx_hwapic_irr_update,
7958         .hwapic_isr_update = vmx_hwapic_isr_update,
7959         .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
7960         .sync_pir_to_irr = vmx_sync_pir_to_irr,
7961         .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
7962         .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
7963
7964         .set_tss_addr = vmx_set_tss_addr,
7965         .set_identity_map_addr = vmx_set_identity_map_addr,
7966         .get_tdp_level = vmx_get_tdp_level,
7967         .get_mt_mask = vmx_get_mt_mask,
7968
7969         .get_exit_info = vmx_get_exit_info,
7970
7971         .vcpu_after_set_cpuid = vmx_vcpu_after_set_cpuid,
7972
7973         .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
7974
7975         .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
7976
7977         .load_mmu_pgd = vmx_load_mmu_pgd,
7978
7979         .check_intercept = vmx_check_intercept,
7980         .handle_exit_irqoff = vmx_handle_exit_irqoff,
7981
7982         .request_immediate_exit = vmx_request_immediate_exit,
7983
7984         .sched_in = vmx_sched_in,
7985
7986         .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
7987         .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
7988         .flush_log_dirty = vmx_flush_log_dirty,
7989         .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
7990
7991         .pre_block = vmx_pre_block,
7992         .post_block = vmx_post_block,
7993
7994         .pmu_ops = &intel_pmu_ops,
7995         .nested_ops = &vmx_nested_ops,
7996
7997         .update_pi_irte = vmx_update_pi_irte,
7998
7999 #ifdef CONFIG_X86_64
8000         .set_hv_timer = vmx_set_hv_timer,
8001         .cancel_hv_timer = vmx_cancel_hv_timer,
8002 #endif
8003
8004         .setup_mce = vmx_setup_mce,
8005
8006         .smi_allowed = vmx_smi_allowed,
8007         .pre_enter_smm = vmx_pre_enter_smm,
8008         .pre_leave_smm = vmx_pre_leave_smm,
8009         .enable_smi_window = enable_smi_window,
8010
8011         .need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
8012         .apic_init_signal_blocked = vmx_apic_init_signal_blocked,
8013         .migrate_timers = vmx_migrate_timers,
8014 };
8015
8016 static __init int hardware_setup(void)
8017 {
8018         unsigned long host_bndcfgs;
8019         struct desc_ptr dt;
8020         int r, i, ept_lpage_level;
8021
8022         store_idt(&dt);
8023         host_idt_base = dt.address;
8024
8025         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
8026                 kvm_define_shared_msr(i, vmx_msr_index[i]);
8027
8028         if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0)
8029                 return -EIO;
8030
8031         if (boot_cpu_has(X86_FEATURE_NX))
8032                 kvm_enable_efer_bits(EFER_NX);
8033
8034         if (boot_cpu_has(X86_FEATURE_MPX)) {
8035                 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
8036                 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
8037         }
8038
8039         if (!cpu_has_vmx_mpx())
8040                 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
8041                                     XFEATURE_MASK_BNDCSR);
8042
8043         if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
8044             !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
8045                 enable_vpid = 0;
8046
8047         if (!cpu_has_vmx_ept() ||
8048             !cpu_has_vmx_ept_4levels() ||
8049             !cpu_has_vmx_ept_mt_wb() ||
8050             !cpu_has_vmx_invept_global())
8051                 enable_ept = 0;
8052
8053         if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
8054                 enable_ept_ad_bits = 0;
8055
8056         if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
8057                 enable_unrestricted_guest = 0;
8058
8059         if (!cpu_has_vmx_flexpriority())
8060                 flexpriority_enabled = 0;
8061
8062         if (!cpu_has_virtual_nmis())
8063                 enable_vnmi = 0;
8064
8065         /*
8066          * set_apic_access_page_addr() is used to reload apic access
8067          * page upon invalidation.  No need to do anything if not
8068          * using the APIC_ACCESS_ADDR VMCS field.
8069          */
8070         if (!flexpriority_enabled)
8071                 vmx_x86_ops.set_apic_access_page_addr = NULL;
8072
8073         if (!cpu_has_vmx_tpr_shadow())
8074                 vmx_x86_ops.update_cr8_intercept = NULL;
8075
8076 #if IS_ENABLED(CONFIG_HYPERV)
8077         if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
8078             && enable_ept) {
8079                 vmx_x86_ops.tlb_remote_flush = hv_remote_flush_tlb;
8080                 vmx_x86_ops.tlb_remote_flush_with_range =
8081                                 hv_remote_flush_tlb_with_range;
8082         }
8083 #endif
8084
8085         if (!cpu_has_vmx_ple()) {
8086                 ple_gap = 0;
8087                 ple_window = 0;
8088                 ple_window_grow = 0;
8089                 ple_window_max = 0;
8090                 ple_window_shrink = 0;
8091         }
8092
8093         if (!cpu_has_vmx_apicv()) {
8094                 enable_apicv = 0;
8095                 vmx_x86_ops.sync_pir_to_irr = NULL;
8096         }
8097
8098         if (cpu_has_vmx_tsc_scaling()) {
8099                 kvm_has_tsc_control = true;
8100                 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
8101                 kvm_tsc_scaling_ratio_frac_bits = 48;
8102         }
8103
8104         set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
8105
8106         if (enable_ept)
8107                 vmx_enable_tdp();
8108
8109         if (!enable_ept)
8110                 ept_lpage_level = 0;
8111         else if (cpu_has_vmx_ept_1g_page())
8112                 ept_lpage_level = PG_LEVEL_1G;
8113         else if (cpu_has_vmx_ept_2m_page())
8114                 ept_lpage_level = PG_LEVEL_2M;
8115         else
8116                 ept_lpage_level = PG_LEVEL_4K;
8117         kvm_configure_mmu(enable_ept, ept_lpage_level);
8118
8119         /*
8120          * Only enable PML when hardware supports PML feature, and both EPT
8121          * and EPT A/D bit features are enabled -- PML depends on them to work.
8122          */
8123         if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
8124                 enable_pml = 0;
8125
8126         if (!enable_pml) {
8127                 vmx_x86_ops.slot_enable_log_dirty = NULL;
8128                 vmx_x86_ops.slot_disable_log_dirty = NULL;
8129                 vmx_x86_ops.flush_log_dirty = NULL;
8130                 vmx_x86_ops.enable_log_dirty_pt_masked = NULL;
8131         }
8132
8133         if (!cpu_has_vmx_preemption_timer())
8134                 enable_preemption_timer = false;
8135
8136         if (enable_preemption_timer) {
8137                 u64 use_timer_freq = 5000ULL * 1000 * 1000;
8138                 u64 vmx_msr;
8139
8140                 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
8141                 cpu_preemption_timer_multi =
8142                         vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
8143
8144                 if (tsc_khz)
8145                         use_timer_freq = (u64)tsc_khz * 1000;
8146                 use_timer_freq >>= cpu_preemption_timer_multi;
8147
8148                 /*
8149                  * KVM "disables" the preemption timer by setting it to its max
8150                  * value.  Don't use the timer if it might cause spurious exits
8151                  * at a rate faster than 0.1 Hz (of uninterrupted guest time).
8152                  */
8153                 if (use_timer_freq > 0xffffffffu / 10)
8154                         enable_preemption_timer = false;
8155         }
8156
8157         if (!enable_preemption_timer) {
8158                 vmx_x86_ops.set_hv_timer = NULL;
8159                 vmx_x86_ops.cancel_hv_timer = NULL;
8160                 vmx_x86_ops.request_immediate_exit = __kvm_request_immediate_exit;
8161         }
8162
8163         kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8164
8165         kvm_mce_cap_supported |= MCG_LMCE_P;
8166
8167         if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST)
8168                 return -EINVAL;
8169         if (!enable_ept || !cpu_has_vmx_intel_pt())
8170                 pt_mode = PT_MODE_SYSTEM;
8171
8172         if (nested) {
8173                 nested_vmx_setup_ctls_msrs(&vmcs_config.nested,
8174                                            vmx_capability.ept);
8175
8176                 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
8177                 if (r)
8178                         return r;
8179         }
8180
8181         vmx_set_cpu_caps();
8182
8183         r = alloc_kvm_area();
8184         if (r)
8185                 nested_vmx_hardware_unsetup();
8186         return r;
8187 }
8188
8189 static struct kvm_x86_init_ops vmx_init_ops __initdata = {
8190         .cpu_has_kvm_support = cpu_has_kvm_support,
8191         .disabled_by_bios = vmx_disabled_by_bios,
8192         .check_processor_compatibility = vmx_check_processor_compat,
8193         .hardware_setup = hardware_setup,
8194
8195         .runtime_ops = &vmx_x86_ops,
8196 };
8197
8198 static void vmx_cleanup_l1d_flush(void)
8199 {
8200         if (vmx_l1d_flush_pages) {
8201                 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
8202                 vmx_l1d_flush_pages = NULL;
8203         }
8204         /* Restore state so sysfs ignores VMX */
8205         l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
8206 }
8207
8208 static void vmx_exit(void)
8209 {
8210 #ifdef CONFIG_KEXEC_CORE
8211         RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
8212         synchronize_rcu();
8213 #endif
8214
8215         kvm_exit();
8216
8217 #if IS_ENABLED(CONFIG_HYPERV)
8218         if (static_branch_unlikely(&enable_evmcs)) {
8219                 int cpu;
8220                 struct hv_vp_assist_page *vp_ap;
8221                 /*
8222                  * Reset everything to support using non-enlightened VMCS
8223                  * access later (e.g. when we reload the module with
8224                  * enlightened_vmcs=0)
8225                  */
8226                 for_each_online_cpu(cpu) {
8227                         vp_ap = hv_get_vp_assist_page(cpu);
8228
8229                         if (!vp_ap)
8230                                 continue;
8231
8232                         vp_ap->nested_control.features.directhypercall = 0;
8233                         vp_ap->current_nested_vmcs = 0;
8234                         vp_ap->enlighten_vmentry = 0;
8235                 }
8236
8237                 static_branch_disable(&enable_evmcs);
8238         }
8239 #endif
8240         vmx_cleanup_l1d_flush();
8241 }
8242 module_exit(vmx_exit);
8243
8244 static int __init vmx_init(void)
8245 {
8246         int r, cpu;
8247
8248 #if IS_ENABLED(CONFIG_HYPERV)
8249         /*
8250          * Enlightened VMCS usage should be recommended and the host needs
8251          * to support eVMCS v1 or above. We can also disable eVMCS support
8252          * with module parameter.
8253          */
8254         if (enlightened_vmcs &&
8255             ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
8256             (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
8257             KVM_EVMCS_VERSION) {
8258                 int cpu;
8259
8260                 /* Check that we have assist pages on all online CPUs */
8261                 for_each_online_cpu(cpu) {
8262                         if (!hv_get_vp_assist_page(cpu)) {
8263                                 enlightened_vmcs = false;
8264                                 break;
8265                         }
8266                 }
8267
8268                 if (enlightened_vmcs) {
8269                         pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
8270                         static_branch_enable(&enable_evmcs);
8271                 }
8272
8273                 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH)
8274                         vmx_x86_ops.enable_direct_tlbflush
8275                                 = hv_enable_direct_tlbflush;
8276
8277         } else {
8278                 enlightened_vmcs = false;
8279         }
8280 #endif
8281
8282         r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
8283                      __alignof__(struct vcpu_vmx), THIS_MODULE);
8284         if (r)
8285                 return r;
8286
8287         /*
8288          * Must be called after kvm_init() so enable_ept is properly set
8289          * up. Hand the parameter mitigation value in which was stored in
8290          * the pre module init parser. If no parameter was given, it will
8291          * contain 'auto' which will be turned into the default 'cond'
8292          * mitigation mode.
8293          */
8294         r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
8295         if (r) {
8296                 vmx_exit();
8297                 return r;
8298         }
8299
8300         for_each_possible_cpu(cpu) {
8301                 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
8302                 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
8303                 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
8304         }
8305
8306 #ifdef CONFIG_KEXEC_CORE
8307         rcu_assign_pointer(crash_vmclear_loaded_vmcss,
8308                            crash_vmclear_local_loaded_vmcss);
8309 #endif
8310         vmx_check_vmcs12_offsets();
8311
8312         /*
8313          * Intel processors don't have problems with
8314          * GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable
8315          * it for VMX by default
8316          */
8317         allow_smaller_maxphyaddr = true;
8318
8319         return 0;
8320 }
8321 module_init(vmx_init);