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