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