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