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