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