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