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