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