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