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