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