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