~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/x86/kvm/vmx/vmx.c

Version: ~ [ linux-5.6-rc1 ] ~ [ linux-5.5.2 ] ~ [ linux-5.4.17 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.102 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.170 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.213 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.213 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.81 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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                 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
250                 if (!page)
251                         return -ENOMEM;
252                 vmx_l1d_flush_pages = page_address(page);
253 
254                 /*
255                  * Initialize each page with a different pattern in
256                  * order to protect against KSM in the nested
257                  * virtualization case.
258                  */
259                 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
260                         memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
261                                PAGE_SIZE);
262                 }
263         }
264 
265         l1tf_vmx_mitigation = l1tf;
266 
267         if (l1tf != VMENTER_L1D_FLUSH_NEVER)
268                 static_branch_enable(&vmx_l1d_should_flush);
269         else
270                 static_branch_disable(&vmx_l1d_should_flush);
271 
272         if (l1tf == VMENTER_L1D_FLUSH_COND)
273                 static_branch_enable(&vmx_l1d_flush_cond);
274         else
275                 static_branch_disable(&vmx_l1d_flush_cond);
276         return 0;
277 }
278 
279 static int vmentry_l1d_flush_parse(const char *s)
280 {
281         unsigned int i;
282 
283         if (s) {
284                 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
285                         if (vmentry_l1d_param[i].for_parse &&
286                             sysfs_streq(s, vmentry_l1d_param[i].option))
287                                 return i;
288                 }
289         }
290         return -EINVAL;
291 }
292 
293 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
294 {
295         int l1tf, ret;
296 
297         l1tf = vmentry_l1d_flush_parse(s);
298         if (l1tf < 0)
299                 return l1tf;
300 
301         if (!boot_cpu_has(X86_BUG_L1TF))
302                 return 0;
303 
304         /*
305          * Has vmx_init() run already? If not then this is the pre init
306          * parameter parsing. In that case just store the value and let
307          * vmx_init() do the proper setup after enable_ept has been
308          * established.
309          */
310         if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
311                 vmentry_l1d_flush_param = l1tf;
312                 return 0;
313         }
314 
315         mutex_lock(&vmx_l1d_flush_mutex);
316         ret = vmx_setup_l1d_flush(l1tf);
317         mutex_unlock(&vmx_l1d_flush_mutex);
318         return ret;
319 }
320 
321 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
322 {
323         if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
324                 return sprintf(s, "???\n");
325 
326         return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
327 }
328 
329 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
330         .set = vmentry_l1d_flush_set,
331         .get = vmentry_l1d_flush_get,
332 };
333 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
334 
335 static bool guest_state_valid(struct kvm_vcpu *vcpu);
336 static u32 vmx_segment_access_rights(struct kvm_segment *var);
337 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
338                                                           u32 msr, int type);
339 
340 void vmx_vmexit(void);
341 
342 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
343 DEFINE_PER_CPU(struct vmcs *, current_vmcs);
344 /*
345  * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
346  * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
347  */
348 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
349 
350 /*
351  * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
352  * can find which vCPU should be waken up.
353  */
354 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
355 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
356 
357 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
358 static DEFINE_SPINLOCK(vmx_vpid_lock);
359 
360 struct vmcs_config vmcs_config;
361 struct vmx_capability vmx_capability;
362 
363 #define VMX_SEGMENT_FIELD(seg)                                  \
364         [VCPU_SREG_##seg] = {                                   \
365                 .selector = GUEST_##seg##_SELECTOR,             \
366                 .base = GUEST_##seg##_BASE,                     \
367                 .limit = GUEST_##seg##_LIMIT,                   \
368                 .ar_bytes = GUEST_##seg##_AR_BYTES,             \
369         }
370 
371 static const struct kvm_vmx_segment_field {
372         unsigned selector;
373         unsigned base;
374         unsigned limit;
375         unsigned ar_bytes;
376 } kvm_vmx_segment_fields[] = {
377         VMX_SEGMENT_FIELD(CS),
378         VMX_SEGMENT_FIELD(DS),
379         VMX_SEGMENT_FIELD(ES),
380         VMX_SEGMENT_FIELD(FS),
381         VMX_SEGMENT_FIELD(GS),
382         VMX_SEGMENT_FIELD(SS),
383         VMX_SEGMENT_FIELD(TR),
384         VMX_SEGMENT_FIELD(LDTR),
385 };
386 
387 u64 host_efer;
388 
389 /*
390  * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm
391  * will emulate SYSCALL in legacy mode if the vendor string in guest
392  * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To
393  * support this emulation, IA32_STAR must always be included in
394  * vmx_msr_index[], even in i386 builds.
395  */
396 const u32 vmx_msr_index[] = {
397 #ifdef CONFIG_X86_64
398         MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
399 #endif
400         MSR_EFER, MSR_TSC_AUX, MSR_STAR,
401 };
402 
403 #if IS_ENABLED(CONFIG_HYPERV)
404 static bool __read_mostly enlightened_vmcs = true;
405 module_param(enlightened_vmcs, bool, 0444);
406 
407 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
408 static void check_ept_pointer_match(struct kvm *kvm)
409 {
410         struct kvm_vcpu *vcpu;
411         u64 tmp_eptp = INVALID_PAGE;
412         int i;
413 
414         kvm_for_each_vcpu(i, vcpu, kvm) {
415                 if (!VALID_PAGE(tmp_eptp)) {
416                         tmp_eptp = to_vmx(vcpu)->ept_pointer;
417                 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
418                         to_kvm_vmx(kvm)->ept_pointers_match
419                                 = EPT_POINTERS_MISMATCH;
420                         return;
421                 }
422         }
423 
424         to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
425 }
426 
427 static int kvm_fill_hv_flush_list_func(struct hv_guest_mapping_flush_list *flush,
428                 void *data)
429 {
430         struct kvm_tlb_range *range = data;
431 
432         return hyperv_fill_flush_guest_mapping_list(flush, range->start_gfn,
433                         range->pages);
434 }
435 
436 static inline int __hv_remote_flush_tlb_with_range(struct kvm *kvm,
437                 struct kvm_vcpu *vcpu, struct kvm_tlb_range *range)
438 {
439         u64 ept_pointer = to_vmx(vcpu)->ept_pointer;
440 
441         /*
442          * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs address
443          * of the base of EPT PML4 table, strip off EPT configuration
444          * information.
445          */
446         if (range)
447                 return hyperv_flush_guest_mapping_range(ept_pointer & PAGE_MASK,
448                                 kvm_fill_hv_flush_list_func, (void *)range);
449         else
450                 return hyperv_flush_guest_mapping(ept_pointer & PAGE_MASK);
451 }
452 
453 static int hv_remote_flush_tlb_with_range(struct kvm *kvm,
454                 struct kvm_tlb_range *range)
455 {
456         struct kvm_vcpu *vcpu;
457         int ret = 0, i;
458 
459         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
460 
461         if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
462                 check_ept_pointer_match(kvm);
463 
464         if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
465                 kvm_for_each_vcpu(i, vcpu, kvm) {
466                         /* If ept_pointer is invalid pointer, bypass flush request. */
467                         if (VALID_PAGE(to_vmx(vcpu)->ept_pointer))
468                                 ret |= __hv_remote_flush_tlb_with_range(
469                                         kvm, vcpu, range);
470                 }
471         } else {
472                 ret = __hv_remote_flush_tlb_with_range(kvm,
473                                 kvm_get_vcpu(kvm, 0), range);
474         }
475 
476         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
477         return ret;
478 }
479 static int hv_remote_flush_tlb(struct kvm *kvm)
480 {
481         return hv_remote_flush_tlb_with_range(kvm, NULL);
482 }
483 
484 #endif /* IS_ENABLED(CONFIG_HYPERV) */
485 
486 /*
487  * Comment's format: document - errata name - stepping - processor name.
488  * Refer from
489  * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
490  */
491 static u32 vmx_preemption_cpu_tfms[] = {
492 /* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
493 0x000206E6,
494 /* 323056.pdf - AAX65  - C2 - Xeon L3406 */
495 /* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
496 /* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
497 0x00020652,
498 /* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
499 0x00020655,
500 /* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
501 /* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
502 /*
503  * 320767.pdf - AAP86  - B1 -
504  * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
505  */
506 0x000106E5,
507 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
508 0x000106A0,
509 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
510 0x000106A1,
511 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
512 0x000106A4,
513  /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
514  /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
515  /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
516 0x000106A5,
517  /* Xeon E3-1220 V2 */
518 0x000306A8,
519 };
520 
521 static inline bool cpu_has_broken_vmx_preemption_timer(void)
522 {
523         u32 eax = cpuid_eax(0x00000001), i;
524 
525         /* Clear the reserved bits */
526         eax &= ~(0x3U << 14 | 0xfU << 28);
527         for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
528                 if (eax == vmx_preemption_cpu_tfms[i])
529                         return true;
530 
531         return false;
532 }
533 
534 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
535 {
536         return flexpriority_enabled && lapic_in_kernel(vcpu);
537 }
538 
539 static inline bool report_flexpriority(void)
540 {
541         return flexpriority_enabled;
542 }
543 
544 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
545 {
546         int i;
547 
548         for (i = 0; i < vmx->nmsrs; ++i)
549                 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
550                         return i;
551         return -1;
552 }
553 
554 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
555 {
556         int i;
557 
558         i = __find_msr_index(vmx, msr);
559         if (i >= 0)
560                 return &vmx->guest_msrs[i];
561         return NULL;
562 }
563 
564 void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
565 {
566         vmcs_clear(loaded_vmcs->vmcs);
567         if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
568                 vmcs_clear(loaded_vmcs->shadow_vmcs);
569         loaded_vmcs->cpu = -1;
570         loaded_vmcs->launched = 0;
571 }
572 
573 #ifdef CONFIG_KEXEC_CORE
574 /*
575  * This bitmap is used to indicate whether the vmclear
576  * operation is enabled on all cpus. All disabled by
577  * default.
578  */
579 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
580 
581 static inline void crash_enable_local_vmclear(int cpu)
582 {
583         cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
584 }
585 
586 static inline void crash_disable_local_vmclear(int cpu)
587 {
588         cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
589 }
590 
591 static inline int crash_local_vmclear_enabled(int cpu)
592 {
593         return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
594 }
595 
596 static void crash_vmclear_local_loaded_vmcss(void)
597 {
598         int cpu = raw_smp_processor_id();
599         struct loaded_vmcs *v;
600 
601         if (!crash_local_vmclear_enabled(cpu))
602                 return;
603 
604         list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
605                             loaded_vmcss_on_cpu_link)
606                 vmcs_clear(v->vmcs);
607 }
608 #else
609 static inline void crash_enable_local_vmclear(int cpu) { }
610 static inline void crash_disable_local_vmclear(int cpu) { }
611 #endif /* CONFIG_KEXEC_CORE */
612 
613 static void __loaded_vmcs_clear(void *arg)
614 {
615         struct loaded_vmcs *loaded_vmcs = arg;
616         int cpu = raw_smp_processor_id();
617 
618         if (loaded_vmcs->cpu != cpu)
619                 return; /* vcpu migration can race with cpu offline */
620         if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
621                 per_cpu(current_vmcs, cpu) = NULL;
622         crash_disable_local_vmclear(cpu);
623         list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
624 
625         /*
626          * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
627          * is before setting loaded_vmcs->vcpu to -1 which is done in
628          * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
629          * then adds the vmcs into percpu list before it is deleted.
630          */
631         smp_wmb();
632 
633         loaded_vmcs_init(loaded_vmcs);
634         crash_enable_local_vmclear(cpu);
635 }
636 
637 void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
638 {
639         int cpu = loaded_vmcs->cpu;
640 
641         if (cpu != -1)
642                 smp_call_function_single(cpu,
643                          __loaded_vmcs_clear, loaded_vmcs, 1);
644 }
645 
646 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
647                                        unsigned field)
648 {
649         bool ret;
650         u32 mask = 1 << (seg * SEG_FIELD_NR + field);
651 
652         if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
653                 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
654                 vmx->segment_cache.bitmask = 0;
655         }
656         ret = vmx->segment_cache.bitmask & mask;
657         vmx->segment_cache.bitmask |= mask;
658         return ret;
659 }
660 
661 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
662 {
663         u16 *p = &vmx->segment_cache.seg[seg].selector;
664 
665         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
666                 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
667         return *p;
668 }
669 
670 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
671 {
672         ulong *p = &vmx->segment_cache.seg[seg].base;
673 
674         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
675                 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
676         return *p;
677 }
678 
679 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
680 {
681         u32 *p = &vmx->segment_cache.seg[seg].limit;
682 
683         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
684                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
685         return *p;
686 }
687 
688 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
689 {
690         u32 *p = &vmx->segment_cache.seg[seg].ar;
691 
692         if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
693                 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
694         return *p;
695 }
696 
697 void update_exception_bitmap(struct kvm_vcpu *vcpu)
698 {
699         u32 eb;
700 
701         eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
702              (1u << DB_VECTOR) | (1u << AC_VECTOR);
703         /*
704          * Guest access to VMware backdoor ports could legitimately
705          * trigger #GP because of TSS I/O permission bitmap.
706          * We intercept those #GP and allow access to them anyway
707          * as VMware does.
708          */
709         if (enable_vmware_backdoor)
710                 eb |= (1u << GP_VECTOR);
711         if ((vcpu->guest_debug &
712              (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
713             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
714                 eb |= 1u << BP_VECTOR;
715         if (to_vmx(vcpu)->rmode.vm86_active)
716                 eb = ~0;
717         if (enable_ept)
718                 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
719 
720         /* When we are running a nested L2 guest and L1 specified for it a
721          * certain exception bitmap, we must trap the same exceptions and pass
722          * them to L1. When running L2, we will only handle the exceptions
723          * specified above if L1 did not want them.
724          */
725         if (is_guest_mode(vcpu))
726                 eb |= get_vmcs12(vcpu)->exception_bitmap;
727 
728         vmcs_write32(EXCEPTION_BITMAP, eb);
729 }
730 
731 /*
732  * Check if MSR is intercepted for currently loaded MSR bitmap.
733  */
734 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
735 {
736         unsigned long *msr_bitmap;
737         int f = sizeof(unsigned long);
738 
739         if (!cpu_has_vmx_msr_bitmap())
740                 return true;
741 
742         msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
743 
744         if (msr <= 0x1fff) {
745                 return !!test_bit(msr, msr_bitmap + 0x800 / f);
746         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
747                 msr &= 0x1fff;
748                 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
749         }
750 
751         return true;
752 }
753 
754 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
755                 unsigned long entry, unsigned long exit)
756 {
757         vm_entry_controls_clearbit(vmx, entry);
758         vm_exit_controls_clearbit(vmx, exit);
759 }
760 
761 static int find_msr(struct vmx_msrs *m, unsigned int msr)
762 {
763         unsigned int i;
764 
765         for (i = 0; i < m->nr; ++i) {
766                 if (m->val[i].index == msr)
767                         return i;
768         }
769         return -ENOENT;
770 }
771 
772 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
773 {
774         int i;
775         struct msr_autoload *m = &vmx->msr_autoload;
776 
777         switch (msr) {
778         case MSR_EFER:
779                 if (cpu_has_load_ia32_efer()) {
780                         clear_atomic_switch_msr_special(vmx,
781                                         VM_ENTRY_LOAD_IA32_EFER,
782                                         VM_EXIT_LOAD_IA32_EFER);
783                         return;
784                 }
785                 break;
786         case MSR_CORE_PERF_GLOBAL_CTRL:
787                 if (cpu_has_load_perf_global_ctrl()) {
788                         clear_atomic_switch_msr_special(vmx,
789                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
790                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
791                         return;
792                 }
793                 break;
794         }
795         i = find_msr(&m->guest, msr);
796         if (i < 0)
797                 goto skip_guest;
798         --m->guest.nr;
799         m->guest.val[i] = m->guest.val[m->guest.nr];
800         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
801 
802 skip_guest:
803         i = find_msr(&m->host, msr);
804         if (i < 0)
805                 return;
806 
807         --m->host.nr;
808         m->host.val[i] = m->host.val[m->host.nr];
809         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
810 }
811 
812 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
813                 unsigned long entry, unsigned long exit,
814                 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
815                 u64 guest_val, u64 host_val)
816 {
817         vmcs_write64(guest_val_vmcs, guest_val);
818         if (host_val_vmcs != HOST_IA32_EFER)
819                 vmcs_write64(host_val_vmcs, host_val);
820         vm_entry_controls_setbit(vmx, entry);
821         vm_exit_controls_setbit(vmx, exit);
822 }
823 
824 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
825                                   u64 guest_val, u64 host_val, bool entry_only)
826 {
827         int i, j = 0;
828         struct msr_autoload *m = &vmx->msr_autoload;
829 
830         switch (msr) {
831         case MSR_EFER:
832                 if (cpu_has_load_ia32_efer()) {
833                         add_atomic_switch_msr_special(vmx,
834                                         VM_ENTRY_LOAD_IA32_EFER,
835                                         VM_EXIT_LOAD_IA32_EFER,
836                                         GUEST_IA32_EFER,
837                                         HOST_IA32_EFER,
838                                         guest_val, host_val);
839                         return;
840                 }
841                 break;
842         case MSR_CORE_PERF_GLOBAL_CTRL:
843                 if (cpu_has_load_perf_global_ctrl()) {
844                         add_atomic_switch_msr_special(vmx,
845                                         VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
846                                         VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
847                                         GUEST_IA32_PERF_GLOBAL_CTRL,
848                                         HOST_IA32_PERF_GLOBAL_CTRL,
849                                         guest_val, host_val);
850                         return;
851                 }
852                 break;
853         case MSR_IA32_PEBS_ENABLE:
854                 /* PEBS needs a quiescent period after being disabled (to write
855                  * a record).  Disabling PEBS through VMX MSR swapping doesn't
856                  * provide that period, so a CPU could write host's record into
857                  * guest's memory.
858                  */
859                 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
860         }
861 
862         i = find_msr(&m->guest, msr);
863         if (!entry_only)
864                 j = find_msr(&m->host, msr);
865 
866         if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
867                 (j < 0 &&  m->host.nr == NR_AUTOLOAD_MSRS)) {
868                 printk_once(KERN_WARNING "Not enough msr switch entries. "
869                                 "Can't add msr %x\n", msr);
870                 return;
871         }
872         if (i < 0) {
873                 i = m->guest.nr++;
874                 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
875         }
876         m->guest.val[i].index = msr;
877         m->guest.val[i].value = guest_val;
878 
879         if (entry_only)
880                 return;
881 
882         if (j < 0) {
883                 j = m->host.nr++;
884                 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
885         }
886         m->host.val[j].index = msr;
887         m->host.val[j].value = host_val;
888 }
889 
890 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
891 {
892         u64 guest_efer = vmx->vcpu.arch.efer;
893         u64 ignore_bits = 0;
894 
895         if (!enable_ept) {
896                 /*
897                  * NX is needed to handle CR0.WP=1, CR4.SMEP=1.  Testing
898                  * host CPUID is more efficient than testing guest CPUID
899                  * or CR4.  Host SMEP is anyway a requirement for guest SMEP.
900                  */
901                 if (boot_cpu_has(X86_FEATURE_SMEP))
902                         guest_efer |= EFER_NX;
903                 else if (!(guest_efer & EFER_NX))
904                         ignore_bits |= EFER_NX;
905         }
906 
907         /*
908          * LMA and LME handled by hardware; SCE meaningless outside long mode.
909          */
910         ignore_bits |= EFER_SCE;
911 #ifdef CONFIG_X86_64
912         ignore_bits |= EFER_LMA | EFER_LME;
913         /* SCE is meaningful only in long mode on Intel */
914         if (guest_efer & EFER_LMA)
915                 ignore_bits &= ~(u64)EFER_SCE;
916 #endif
917 
918         /*
919          * On EPT, we can't emulate NX, so we must switch EFER atomically.
920          * On CPUs that support "load IA32_EFER", always switch EFER
921          * atomically, since it's faster than switching it manually.
922          */
923         if (cpu_has_load_ia32_efer() ||
924             (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
925                 if (!(guest_efer & EFER_LMA))
926                         guest_efer &= ~EFER_LME;
927                 if (guest_efer != host_efer)
928                         add_atomic_switch_msr(vmx, MSR_EFER,
929                                               guest_efer, host_efer, false);
930                 else
931                         clear_atomic_switch_msr(vmx, MSR_EFER);
932                 return false;
933         } else {
934                 clear_atomic_switch_msr(vmx, MSR_EFER);
935 
936                 guest_efer &= ~ignore_bits;
937                 guest_efer |= host_efer & ignore_bits;
938 
939                 vmx->guest_msrs[efer_offset].data = guest_efer;
940                 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
941 
942                 return true;
943         }
944 }
945 
946 #ifdef CONFIG_X86_32
947 /*
948  * On 32-bit kernels, VM exits still load the FS and GS bases from the
949  * VMCS rather than the segment table.  KVM uses this helper to figure
950  * out the current bases to poke them into the VMCS before entry.
951  */
952 static unsigned long segment_base(u16 selector)
953 {
954         struct desc_struct *table;
955         unsigned long v;
956 
957         if (!(selector & ~SEGMENT_RPL_MASK))
958                 return 0;
959 
960         table = get_current_gdt_ro();
961 
962         if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
963                 u16 ldt_selector = kvm_read_ldt();
964 
965                 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
966                         return 0;
967 
968                 table = (struct desc_struct *)segment_base(ldt_selector);
969         }
970         v = get_desc_base(&table[selector >> 3]);
971         return v;
972 }
973 #endif
974 
975 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
976 {
977         u32 i;
978 
979         wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
980         wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
981         wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
982         wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
983         for (i = 0; i < addr_range; i++) {
984                 wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
985                 wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
986         }
987 }
988 
989 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
990 {
991         u32 i;
992 
993         rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
994         rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
995         rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
996         rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
997         for (i = 0; i < addr_range; i++) {
998                 rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
999                 rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1000         }
1001 }
1002 
1003 static void pt_guest_enter(struct vcpu_vmx *vmx)
1004 {
1005         if (pt_mode == PT_MODE_SYSTEM)
1006                 return;
1007 
1008         /*
1009          * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1010          * Save host state before VM entry.
1011          */
1012         rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1013         if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1014                 wrmsrl(MSR_IA32_RTIT_CTL, 0);
1015                 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1016                 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1017         }
1018 }
1019 
1020 static void pt_guest_exit(struct vcpu_vmx *vmx)
1021 {
1022         if (pt_mode == PT_MODE_SYSTEM)
1023                 return;
1024 
1025         if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1026                 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1027                 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1028         }
1029 
1030         /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1031         wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1032 }
1033 
1034 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1035 {
1036         struct vcpu_vmx *vmx = to_vmx(vcpu);
1037         struct vmcs_host_state *host_state;
1038 #ifdef CONFIG_X86_64
1039         int cpu = raw_smp_processor_id();
1040 #endif
1041         unsigned long fs_base, gs_base;
1042         u16 fs_sel, gs_sel;
1043         int i;
1044 
1045         vmx->req_immediate_exit = false;
1046 
1047         /*
1048          * Note that guest MSRs to be saved/restored can also be changed
1049          * when guest state is loaded. This happens when guest transitions
1050          * to/from long-mode by setting MSR_EFER.LMA.
1051          */
1052         if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
1053                 vmx->guest_msrs_dirty = false;
1054                 for (i = 0; i < vmx->save_nmsrs; ++i)
1055                         kvm_set_shared_msr(vmx->guest_msrs[i].index,
1056                                            vmx->guest_msrs[i].data,
1057                                            vmx->guest_msrs[i].mask);
1058 
1059         }
1060 
1061         if (vmx->loaded_cpu_state)
1062                 return;
1063 
1064         vmx->loaded_cpu_state = vmx->loaded_vmcs;
1065         host_state = &vmx->loaded_cpu_state->host_state;
1066 
1067         /*
1068          * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1069          * allow segment selectors with cpl > 0 or ti == 1.
1070          */
1071         host_state->ldt_sel = kvm_read_ldt();
1072 
1073 #ifdef CONFIG_X86_64
1074         savesegment(ds, host_state->ds_sel);
1075         savesegment(es, host_state->es_sel);
1076 
1077         gs_base = cpu_kernelmode_gs_base(cpu);
1078         if (likely(is_64bit_mm(current->mm))) {
1079                 save_fsgs_for_kvm();
1080                 fs_sel = current->thread.fsindex;
1081                 gs_sel = current->thread.gsindex;
1082                 fs_base = current->thread.fsbase;
1083                 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1084         } else {
1085                 savesegment(fs, fs_sel);
1086                 savesegment(gs, gs_sel);
1087                 fs_base = read_msr(MSR_FS_BASE);
1088                 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1089         }
1090 
1091         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1092 #else
1093         savesegment(fs, fs_sel);
1094         savesegment(gs, gs_sel);
1095         fs_base = segment_base(fs_sel);
1096         gs_base = segment_base(gs_sel);
1097 #endif
1098 
1099         if (unlikely(fs_sel != host_state->fs_sel)) {
1100                 if (!(fs_sel & 7))
1101                         vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1102                 else
1103                         vmcs_write16(HOST_FS_SELECTOR, 0);
1104                 host_state->fs_sel = fs_sel;
1105         }
1106         if (unlikely(gs_sel != host_state->gs_sel)) {
1107                 if (!(gs_sel & 7))
1108                         vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1109                 else
1110                         vmcs_write16(HOST_GS_SELECTOR, 0);
1111                 host_state->gs_sel = gs_sel;
1112         }
1113         if (unlikely(fs_base != host_state->fs_base)) {
1114                 vmcs_writel(HOST_FS_BASE, fs_base);
1115                 host_state->fs_base = fs_base;
1116         }
1117         if (unlikely(gs_base != host_state->gs_base)) {
1118                 vmcs_writel(HOST_GS_BASE, gs_base);
1119                 host_state->gs_base = gs_base;
1120         }
1121 }
1122 
1123 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1124 {
1125         struct vmcs_host_state *host_state;
1126 
1127         if (!vmx->loaded_cpu_state)
1128                 return;
1129 
1130         WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
1131         host_state = &vmx->loaded_cpu_state->host_state;
1132 
1133         ++vmx->vcpu.stat.host_state_reload;
1134         vmx->loaded_cpu_state = NULL;
1135 
1136 #ifdef CONFIG_X86_64
1137         rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1138 #endif
1139         if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1140                 kvm_load_ldt(host_state->ldt_sel);
1141 #ifdef CONFIG_X86_64
1142                 load_gs_index(host_state->gs_sel);
1143 #else
1144                 loadsegment(gs, host_state->gs_sel);
1145 #endif
1146         }
1147         if (host_state->fs_sel & 7)
1148                 loadsegment(fs, host_state->fs_sel);
1149 #ifdef CONFIG_X86_64
1150         if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1151                 loadsegment(ds, host_state->ds_sel);
1152                 loadsegment(es, host_state->es_sel);
1153         }
1154 #endif
1155         invalidate_tss_limit();
1156 #ifdef CONFIG_X86_64
1157         wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1158 #endif
1159         load_fixmap_gdt(raw_smp_processor_id());
1160 }
1161 
1162 #ifdef CONFIG_X86_64
1163 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1164 {
1165         preempt_disable();
1166         if (vmx->loaded_cpu_state)
1167                 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1168         preempt_enable();
1169         return vmx->msr_guest_kernel_gs_base;
1170 }
1171 
1172 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1173 {
1174         preempt_disable();
1175         if (vmx->loaded_cpu_state)
1176                 wrmsrl(MSR_KERNEL_GS_BASE, data);
1177         preempt_enable();
1178         vmx->msr_guest_kernel_gs_base = data;
1179 }
1180 #endif
1181 
1182 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
1183 {
1184         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1185         struct pi_desc old, new;
1186         unsigned int dest;
1187 
1188         /*
1189          * In case of hot-plug or hot-unplug, we may have to undo
1190          * vmx_vcpu_pi_put even if there is no assigned device.  And we
1191          * always keep PI.NDST up to date for simplicity: it makes the
1192          * code easier, and CPU migration is not a fast path.
1193          */
1194         if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
1195                 return;
1196 
1197         /* The full case.  */
1198         do {
1199                 old.control = new.control = pi_desc->control;
1200 
1201                 dest = cpu_physical_id(cpu);
1202 
1203                 if (x2apic_enabled())
1204                         new.ndst = dest;
1205                 else
1206                         new.ndst = (dest << 8) & 0xFF00;
1207 
1208                 new.sn = 0;
1209         } while (cmpxchg64(&pi_desc->control, old.control,
1210                            new.control) != old.control);
1211 
1212         /*
1213          * Clear SN before reading the bitmap.  The VT-d firmware
1214          * writes the bitmap and reads SN atomically (5.2.3 in the
1215          * spec), so it doesn't really have a memory barrier that
1216          * pairs with this, but we cannot do that and we need one.
1217          */
1218         smp_mb__after_atomic();
1219 
1220         if (!bitmap_empty((unsigned long *)pi_desc->pir, NR_VECTORS))
1221                 pi_set_on(pi_desc);
1222 }
1223 
1224 /*
1225  * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1226  * vcpu mutex is already taken.
1227  */
1228 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1229 {
1230         struct vcpu_vmx *vmx = to_vmx(vcpu);
1231         bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1232 
1233         if (!already_loaded) {
1234                 loaded_vmcs_clear(vmx->loaded_vmcs);
1235                 local_irq_disable();
1236                 crash_disable_local_vmclear(cpu);
1237 
1238                 /*
1239                  * Read loaded_vmcs->cpu should be before fetching
1240                  * loaded_vmcs->loaded_vmcss_on_cpu_link.
1241                  * See the comments in __loaded_vmcs_clear().
1242                  */
1243                 smp_rmb();
1244 
1245                 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1246                          &per_cpu(loaded_vmcss_on_cpu, cpu));
1247                 crash_enable_local_vmclear(cpu);
1248                 local_irq_enable();
1249         }
1250 
1251         if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
1252                 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1253                 vmcs_load(vmx->loaded_vmcs->vmcs);
1254                 indirect_branch_prediction_barrier();
1255         }
1256 
1257         if (!already_loaded) {
1258                 void *gdt = get_current_gdt_ro();
1259                 unsigned long sysenter_esp;
1260 
1261                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1262 
1263                 /*
1264                  * Linux uses per-cpu TSS and GDT, so set these when switching
1265                  * processors.  See 22.2.4.
1266                  */
1267                 vmcs_writel(HOST_TR_BASE,
1268                             (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1269                 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
1270 
1271                 /*
1272                  * VM exits change the host TR limit to 0x67 after a VM
1273                  * exit.  This is okay, since 0x67 covers everything except
1274                  * the IO bitmap and have have code to handle the IO bitmap
1275                  * being lost after a VM exit.
1276                  */
1277                 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
1278 
1279                 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1280                 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1281 
1282                 vmx->loaded_vmcs->cpu = cpu;
1283         }
1284 
1285         /* Setup TSC multiplier */
1286         if (kvm_has_tsc_control &&
1287             vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
1288                 decache_tsc_multiplier(vmx);
1289 
1290         vmx_vcpu_pi_load(vcpu, cpu);
1291         vmx->host_pkru = read_pkru();
1292         vmx->host_debugctlmsr = get_debugctlmsr();
1293 }
1294 
1295 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
1296 {
1297         struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
1298 
1299         if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
1300                 !irq_remapping_cap(IRQ_POSTING_CAP)  ||
1301                 !kvm_vcpu_apicv_active(vcpu))
1302                 return;
1303 
1304         /* Set SN when the vCPU is preempted */
1305         if (vcpu->preempted)
1306                 pi_set_sn(pi_desc);
1307 }
1308 
1309 void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1310 {
1311         vmx_vcpu_pi_put(vcpu);
1312 
1313         vmx_prepare_switch_to_host(to_vmx(vcpu));
1314 }
1315 
1316 static bool emulation_required(struct kvm_vcpu *vcpu)
1317 {
1318         return emulate_invalid_guest_state && !guest_state_valid(vcpu);
1319 }
1320 
1321 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
1322 
1323 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1324 {
1325         unsigned long rflags, save_rflags;
1326 
1327         if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
1328                 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1329                 rflags = vmcs_readl(GUEST_RFLAGS);
1330                 if (to_vmx(vcpu)->rmode.vm86_active) {
1331                         rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1332                         save_rflags = to_vmx(vcpu)->rmode.save_rflags;
1333                         rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1334                 }
1335                 to_vmx(vcpu)->rflags = rflags;
1336         }
1337         return to_vmx(vcpu)->rflags;
1338 }
1339 
1340 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1341 {
1342         unsigned long old_rflags = vmx_get_rflags(vcpu);
1343 
1344         __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
1345         to_vmx(vcpu)->rflags = rflags;
1346         if (to_vmx(vcpu)->rmode.vm86_active) {
1347                 to_vmx(vcpu)->rmode.save_rflags = rflags;
1348                 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1349         }
1350         vmcs_writel(GUEST_RFLAGS, rflags);
1351 
1352         if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
1353                 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
1354 }
1355 
1356 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1357 {
1358         u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1359         int ret = 0;
1360 
1361         if (interruptibility & GUEST_INTR_STATE_STI)
1362                 ret |= KVM_X86_SHADOW_INT_STI;
1363         if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1364                 ret |= KVM_X86_SHADOW_INT_MOV_SS;
1365 
1366         return ret;
1367 }
1368 
1369 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1370 {
1371         u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1372         u32 interruptibility = interruptibility_old;
1373 
1374         interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1375 
1376         if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1377                 interruptibility |= GUEST_INTR_STATE_MOV_SS;
1378         else if (mask & KVM_X86_SHADOW_INT_STI)
1379                 interruptibility |= GUEST_INTR_STATE_STI;
1380 
1381         if ((interruptibility != interruptibility_old))
1382                 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1383 }
1384 
1385 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1386 {
1387         struct vcpu_vmx *vmx = to_vmx(vcpu);
1388         unsigned long value;
1389 
1390         /*
1391          * Any MSR write that attempts to change bits marked reserved will
1392          * case a #GP fault.
1393          */
1394         if (data & vmx->pt_desc.ctl_bitmask)
1395                 return 1;
1396 
1397         /*
1398          * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1399          * result in a #GP unless the same write also clears TraceEn.
1400          */
1401         if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1402                 ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1403                 return 1;
1404 
1405         /*
1406          * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1407          * and FabricEn would cause #GP, if
1408          * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1409          */
1410         if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1411                 !(data & RTIT_CTL_FABRIC_EN) &&
1412                 !intel_pt_validate_cap(vmx->pt_desc.caps,
1413                                         PT_CAP_single_range_output))
1414                 return 1;
1415 
1416         /*
1417          * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1418          * utilize encodings marked reserved will casue a #GP fault.
1419          */
1420         value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1421         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1422                         !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1423                         RTIT_CTL_MTC_RANGE_OFFSET, &value))
1424                 return 1;
1425         value = intel_pt_validate_cap(vmx->pt_desc.caps,
1426                                                 PT_CAP_cycle_thresholds);
1427         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1428                         !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1429                         RTIT_CTL_CYC_THRESH_OFFSET, &value))
1430                 return 1;
1431         value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1432         if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1433                         !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1434                         RTIT_CTL_PSB_FREQ_OFFSET, &value))
1435                 return 1;
1436 
1437         /*
1438          * If ADDRx_CFG is reserved or the encodings is >2 will
1439          * cause a #GP fault.
1440          */
1441         value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1442         if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1443                 return 1;
1444         value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1445         if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1446                 return 1;
1447         value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1448         if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1449                 return 1;
1450         value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1451         if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1452                 return 1;
1453 
1454         return 0;
1455 }
1456 
1457 
1458 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
1459 {
1460         unsigned long rip;
1461 
1462         rip = kvm_rip_read(vcpu);
1463         rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1464         kvm_rip_write(vcpu, rip);
1465 
1466         /* skipping an emulated instruction also counts */
1467         vmx_set_interrupt_shadow(vcpu, 0);
1468 }
1469 
1470 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1471 {
1472         /*
1473          * Ensure that we clear the HLT state in the VMCS.  We don't need to
1474          * explicitly skip the instruction because if the HLT state is set,
1475          * then the instruction is already executing and RIP has already been
1476          * advanced.
1477          */
1478         if (kvm_hlt_in_guest(vcpu->kvm) &&
1479                         vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1480                 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1481 }
1482 
1483 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1484 {
1485         struct vcpu_vmx *vmx = to_vmx(vcpu);
1486         unsigned nr = vcpu->arch.exception.nr;
1487         bool has_error_code = vcpu->arch.exception.has_error_code;
1488         u32 error_code = vcpu->arch.exception.error_code;
1489         u32 intr_info = nr | INTR_INFO_VALID_MASK;
1490 
1491         kvm_deliver_exception_payload(vcpu);
1492 
1493         if (has_error_code) {
1494                 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1495                 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1496         }
1497 
1498         if (vmx->rmode.vm86_active) {
1499                 int inc_eip = 0;
1500                 if (kvm_exception_is_soft(nr))
1501                         inc_eip = vcpu->arch.event_exit_inst_len;
1502                 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
1503                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1504                 return;
1505         }
1506 
1507         WARN_ON_ONCE(vmx->emulation_required);
1508 
1509         if (kvm_exception_is_soft(nr)) {
1510                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1511                              vmx->vcpu.arch.event_exit_inst_len);
1512                 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1513         } else
1514                 intr_info |= INTR_TYPE_HARD_EXCEPTION;
1515 
1516         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1517 
1518         vmx_clear_hlt(vcpu);
1519 }
1520 
1521 static bool vmx_rdtscp_supported(void)
1522 {
1523         return cpu_has_vmx_rdtscp();
1524 }
1525 
1526 static bool vmx_invpcid_supported(void)
1527 {
1528         return cpu_has_vmx_invpcid();
1529 }
1530 
1531 /*
1532  * Swap MSR entry in host/guest MSR entry array.
1533  */
1534 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
1535 {
1536         struct shared_msr_entry tmp;
1537 
1538         tmp = vmx->guest_msrs[to];
1539         vmx->guest_msrs[to] = vmx->guest_msrs[from];
1540         vmx->guest_msrs[from] = tmp;
1541 }
1542 
1543 /*
1544  * Set up the vmcs to automatically save and restore system
1545  * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1546  * mode, as fiddling with msrs is very expensive.
1547  */
1548 static void setup_msrs(struct vcpu_vmx *vmx)
1549 {
1550         int save_nmsrs, index;
1551 
1552         save_nmsrs = 0;
1553 #ifdef CONFIG_X86_64
1554         /*
1555          * The SYSCALL MSRs are only needed on long mode guests, and only
1556          * when EFER.SCE is set.
1557          */
1558         if (is_long_mode(&vmx->vcpu) && (vmx->vcpu.arch.efer & EFER_SCE)) {
1559                 index = __find_msr_index(vmx, MSR_STAR);
1560                 if (index >= 0)
1561                         move_msr_up(vmx, index, save_nmsrs++);
1562                 index = __find_msr_index(vmx, MSR_LSTAR);
1563                 if (index >= 0)
1564                         move_msr_up(vmx, index, save_nmsrs++);
1565                 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
1566                 if (index >= 0)
1567                         move_msr_up(vmx, index, save_nmsrs++);
1568         }
1569 #endif
1570         index = __find_msr_index(vmx, MSR_EFER);
1571         if (index >= 0 && update_transition_efer(vmx, index))
1572                 move_msr_up(vmx, index, save_nmsrs++);
1573         index = __find_msr_index(vmx, MSR_TSC_AUX);
1574         if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
1575                 move_msr_up(vmx, index, save_nmsrs++);
1576 
1577         vmx->save_nmsrs = save_nmsrs;
1578         vmx->guest_msrs_dirty = true;
1579 
1580         if (cpu_has_vmx_msr_bitmap())
1581                 vmx_update_msr_bitmap(&vmx->vcpu);
1582 }
1583 
1584 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1585 {
1586         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1587 
1588         if (is_guest_mode(vcpu) &&
1589             (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1590                 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
1591 
1592         return vcpu->arch.tsc_offset;
1593 }
1594 
1595 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1596 {
1597         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1598         u64 g_tsc_offset = 0;
1599 
1600         /*
1601          * We're here if L1 chose not to trap WRMSR to TSC. According
1602          * to the spec, this should set L1's TSC; The offset that L1
1603          * set for L2 remains unchanged, and still needs to be added
1604          * to the newly set TSC to get L2's TSC.
1605          */
1606         if (is_guest_mode(vcpu) &&
1607             (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
1608                 g_tsc_offset = vmcs12->tsc_offset;
1609 
1610         trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1611                                    vcpu->arch.tsc_offset - g_tsc_offset,
1612                                    offset);
1613         vmcs_write64(TSC_OFFSET, offset + g_tsc_offset);
1614         return offset + g_tsc_offset;
1615 }
1616 
1617 /*
1618  * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1619  * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1620  * all guests if the "nested" module option is off, and can also be disabled
1621  * for a single guest by disabling its VMX cpuid bit.
1622  */
1623 bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1624 {
1625         return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1626 }
1627 
1628 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1629                                                  uint64_t val)
1630 {
1631         uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1632 
1633         return !(val & ~valid_bits);
1634 }
1635 
1636 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1637 {
1638         switch (msr->index) {
1639         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1640                 if (!nested)
1641                         return 1;
1642                 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1643         default:
1644                 return 1;
1645         }
1646 
1647         return 0;
1648 }
1649 
1650 /*
1651  * Reads an msr value (of 'msr_index') into 'pdata'.
1652  * Returns 0 on success, non-0 otherwise.
1653  * Assumes vcpu_load() was already called.
1654  */
1655 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1656 {
1657         struct vcpu_vmx *vmx = to_vmx(vcpu);
1658         struct shared_msr_entry *msr;
1659         u32 index;
1660 
1661         switch (msr_info->index) {
1662 #ifdef CONFIG_X86_64
1663         case MSR_FS_BASE:
1664                 msr_info->data = vmcs_readl(GUEST_FS_BASE);
1665                 break;
1666         case MSR_GS_BASE:
1667                 msr_info->data = vmcs_readl(GUEST_GS_BASE);
1668                 break;
1669         case MSR_KERNEL_GS_BASE:
1670                 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1671                 break;
1672 #endif
1673         case MSR_EFER:
1674                 return kvm_get_msr_common(vcpu, msr_info);
1675         case MSR_IA32_SPEC_CTRL:
1676                 if (!msr_info->host_initiated &&
1677                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1678                         return 1;
1679 
1680                 msr_info->data = to_vmx(vcpu)->spec_ctrl;
1681                 break;
1682         case MSR_IA32_SYSENTER_CS:
1683                 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1684                 break;
1685         case MSR_IA32_SYSENTER_EIP:
1686                 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1687                 break;
1688         case MSR_IA32_SYSENTER_ESP:
1689                 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1690                 break;
1691         case MSR_IA32_BNDCFGS:
1692                 if (!kvm_mpx_supported() ||
1693                     (!msr_info->host_initiated &&
1694                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1695                         return 1;
1696                 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1697                 break;
1698         case MSR_IA32_MCG_EXT_CTL:
1699                 if (!msr_info->host_initiated &&
1700                     !(vmx->msr_ia32_feature_control &
1701                       FEATURE_CONTROL_LMCE))
1702                         return 1;
1703                 msr_info->data = vcpu->arch.mcg_ext_ctl;
1704                 break;
1705         case MSR_IA32_FEATURE_CONTROL:
1706                 msr_info->data = vmx->msr_ia32_feature_control;
1707                 break;
1708         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1709                 if (!nested_vmx_allowed(vcpu))
1710                         return 1;
1711                 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1712                                        &msr_info->data);
1713         case MSR_IA32_XSS:
1714                 if (!vmx_xsaves_supported())
1715                         return 1;
1716                 msr_info->data = vcpu->arch.ia32_xss;
1717                 break;
1718         case MSR_IA32_RTIT_CTL:
1719                 if (pt_mode != PT_MODE_HOST_GUEST)
1720                         return 1;
1721                 msr_info->data = vmx->pt_desc.guest.ctl;
1722                 break;
1723         case MSR_IA32_RTIT_STATUS:
1724                 if (pt_mode != PT_MODE_HOST_GUEST)
1725                         return 1;
1726                 msr_info->data = vmx->pt_desc.guest.status;
1727                 break;
1728         case MSR_IA32_RTIT_CR3_MATCH:
1729                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1730                         !intel_pt_validate_cap(vmx->pt_desc.caps,
1731                                                 PT_CAP_cr3_filtering))
1732                         return 1;
1733                 msr_info->data = vmx->pt_desc.guest.cr3_match;
1734                 break;
1735         case MSR_IA32_RTIT_OUTPUT_BASE:
1736                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1737                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1738                                         PT_CAP_topa_output) &&
1739                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1740                                         PT_CAP_single_range_output)))
1741                         return 1;
1742                 msr_info->data = vmx->pt_desc.guest.output_base;
1743                 break;
1744         case MSR_IA32_RTIT_OUTPUT_MASK:
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_mask;
1752                 break;
1753         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1754                 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1755                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1756                         (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1757                                         PT_CAP_num_address_ranges)))
1758                         return 1;
1759                 if (index % 2)
1760                         msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1761                 else
1762                         msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1763                 break;
1764         case MSR_TSC_AUX:
1765                 if (!msr_info->host_initiated &&
1766                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1767                         return 1;
1768                 /* Else, falls through */
1769         default:
1770                 msr = find_msr_entry(vmx, msr_info->index);
1771                 if (msr) {
1772                         msr_info->data = msr->data;
1773                         break;
1774                 }
1775                 return kvm_get_msr_common(vcpu, msr_info);
1776         }
1777 
1778         return 0;
1779 }
1780 
1781 /*
1782  * Writes msr value into into the appropriate "register".
1783  * Returns 0 on success, non-0 otherwise.
1784  * Assumes vcpu_load() was already called.
1785  */
1786 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1787 {
1788         struct vcpu_vmx *vmx = to_vmx(vcpu);
1789         struct shared_msr_entry *msr;
1790         int ret = 0;
1791         u32 msr_index = msr_info->index;
1792         u64 data = msr_info->data;
1793         u32 index;
1794 
1795         switch (msr_index) {
1796         case MSR_EFER:
1797                 ret = kvm_set_msr_common(vcpu, msr_info);
1798                 break;
1799 #ifdef CONFIG_X86_64
1800         case MSR_FS_BASE:
1801                 vmx_segment_cache_clear(vmx);
1802                 vmcs_writel(GUEST_FS_BASE, data);
1803                 break;
1804         case MSR_GS_BASE:
1805                 vmx_segment_cache_clear(vmx);
1806                 vmcs_writel(GUEST_GS_BASE, data);
1807                 break;
1808         case MSR_KERNEL_GS_BASE:
1809                 vmx_write_guest_kernel_gs_base(vmx, data);
1810                 break;
1811 #endif
1812         case MSR_IA32_SYSENTER_CS:
1813                 vmcs_write32(GUEST_SYSENTER_CS, data);
1814                 break;
1815         case MSR_IA32_SYSENTER_EIP:
1816                 vmcs_writel(GUEST_SYSENTER_EIP, data);
1817                 break;
1818         case MSR_IA32_SYSENTER_ESP:
1819                 vmcs_writel(GUEST_SYSENTER_ESP, data);
1820                 break;
1821         case MSR_IA32_BNDCFGS:
1822                 if (!kvm_mpx_supported() ||
1823                     (!msr_info->host_initiated &&
1824                      !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1825                         return 1;
1826                 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
1827                     (data & MSR_IA32_BNDCFGS_RSVD))
1828                         return 1;
1829                 vmcs_write64(GUEST_BNDCFGS, data);
1830                 break;
1831         case MSR_IA32_SPEC_CTRL:
1832                 if (!msr_info->host_initiated &&
1833                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1834                         return 1;
1835 
1836                 /* The STIBP bit doesn't fault even if it's not advertised */
1837                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
1838                         return 1;
1839 
1840                 vmx->spec_ctrl = data;
1841 
1842                 if (!data)
1843                         break;
1844 
1845                 /*
1846                  * For non-nested:
1847                  * When it's written (to non-zero) for the first time, pass
1848                  * it through.
1849                  *
1850                  * For nested:
1851                  * The handling of the MSR bitmap for L2 guests is done in
1852                  * nested_vmx_merge_msr_bitmap. We should not touch the
1853                  * vmcs02.msr_bitmap here since it gets completely overwritten
1854                  * in the merging. We update the vmcs01 here for L1 as well
1855                  * since it will end up touching the MSR anyway now.
1856                  */
1857                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
1858                                               MSR_IA32_SPEC_CTRL,
1859                                               MSR_TYPE_RW);
1860                 break;
1861         case MSR_IA32_PRED_CMD:
1862                 if (!msr_info->host_initiated &&
1863                     !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
1864                         return 1;
1865 
1866                 if (data & ~PRED_CMD_IBPB)
1867                         return 1;
1868 
1869                 if (!data)
1870                         break;
1871 
1872                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
1873 
1874                 /*
1875                  * For non-nested:
1876                  * When it's written (to non-zero) for the first time, pass
1877                  * it through.
1878                  *
1879                  * For nested:
1880                  * The handling of the MSR bitmap for L2 guests is done in
1881                  * nested_vmx_merge_msr_bitmap. We should not touch the
1882                  * vmcs02.msr_bitmap here since it gets completely overwritten
1883                  * in the merging.
1884                  */
1885                 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
1886                                               MSR_TYPE_W);
1887                 break;
1888         case MSR_IA32_CR_PAT:
1889                 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
1890                         if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
1891                                 return 1;
1892                         vmcs_write64(GUEST_IA32_PAT, data);
1893                         vcpu->arch.pat = data;
1894                         break;
1895                 }
1896                 ret = kvm_set_msr_common(vcpu, msr_info);
1897                 break;
1898         case MSR_IA32_TSC_ADJUST:
1899                 ret = kvm_set_msr_common(vcpu, msr_info);
1900                 break;
1901         case MSR_IA32_MCG_EXT_CTL:
1902                 if ((!msr_info->host_initiated &&
1903                      !(to_vmx(vcpu)->msr_ia32_feature_control &
1904                        FEATURE_CONTROL_LMCE)) ||
1905                     (data & ~MCG_EXT_CTL_LMCE_EN))
1906                         return 1;
1907                 vcpu->arch.mcg_ext_ctl = data;
1908                 break;
1909         case MSR_IA32_FEATURE_CONTROL:
1910                 if (!vmx_feature_control_msr_valid(vcpu, data) ||
1911                     (to_vmx(vcpu)->msr_ia32_feature_control &
1912                      FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
1913                         return 1;
1914                 vmx->msr_ia32_feature_control = data;
1915                 if (msr_info->host_initiated && data == 0)
1916                         vmx_leave_nested(vcpu);
1917                 break;
1918         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1919                 if (!msr_info->host_initiated)
1920                         return 1; /* they are read-only */
1921                 if (!nested_vmx_allowed(vcpu))
1922                         return 1;
1923                 return vmx_set_vmx_msr(vcpu, msr_index, data);
1924         case MSR_IA32_XSS:
1925                 if (!vmx_xsaves_supported())
1926                         return 1;
1927                 /*
1928                  * The only supported bit as of Skylake is bit 8, but
1929                  * it is not supported on KVM.
1930                  */
1931                 if (data != 0)
1932                         return 1;
1933                 vcpu->arch.ia32_xss = data;
1934                 if (vcpu->arch.ia32_xss != host_xss)
1935                         add_atomic_switch_msr(vmx, MSR_IA32_XSS,
1936                                 vcpu->arch.ia32_xss, host_xss, false);
1937                 else
1938                         clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
1939                 break;
1940         case MSR_IA32_RTIT_CTL:
1941                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1942                         vmx_rtit_ctl_check(vcpu, data) ||
1943                         vmx->nested.vmxon)
1944                         return 1;
1945                 vmcs_write64(GUEST_IA32_RTIT_CTL, data);
1946                 vmx->pt_desc.guest.ctl = data;
1947                 pt_update_intercept_for_msr(vmx);
1948                 break;
1949         case MSR_IA32_RTIT_STATUS:
1950                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1951                         (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1952                         (data & MSR_IA32_RTIT_STATUS_MASK))
1953                         return 1;
1954                 vmx->pt_desc.guest.status = data;
1955                 break;
1956         case MSR_IA32_RTIT_CR3_MATCH:
1957                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1958                         (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1959                         !intel_pt_validate_cap(vmx->pt_desc.caps,
1960                                                 PT_CAP_cr3_filtering))
1961                         return 1;
1962                 vmx->pt_desc.guest.cr3_match = data;
1963                 break;
1964         case MSR_IA32_RTIT_OUTPUT_BASE:
1965                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1966                         (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1967                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1968                                         PT_CAP_topa_output) &&
1969                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1970                                         PT_CAP_single_range_output)) ||
1971                         (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
1972                         return 1;
1973                 vmx->pt_desc.guest.output_base = data;
1974                 break;
1975         case MSR_IA32_RTIT_OUTPUT_MASK:
1976                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1977                         (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1978                         (!intel_pt_validate_cap(vmx->pt_desc.caps,
1979                                         PT_CAP_topa_output) &&
1980                          !intel_pt_validate_cap(vmx->pt_desc.caps,
1981                                         PT_CAP_single_range_output)))
1982                         return 1;
1983                 vmx->pt_desc.guest.output_mask = data;
1984                 break;
1985         case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1986                 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1987                 if ((pt_mode != PT_MODE_HOST_GUEST) ||
1988                         (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
1989                         (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1990                                         PT_CAP_num_address_ranges)))
1991                         return 1;
1992                 if (index % 2)
1993                         vmx->pt_desc.guest.addr_b[index / 2] = data;
1994                 else
1995                         vmx->pt_desc.guest.addr_a[index / 2] = data;
1996                 break;
1997         case MSR_TSC_AUX:
1998                 if (!msr_info->host_initiated &&
1999                     !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
2000                         return 1;
2001                 /* Check reserved bit, higher 32 bits should be zero */
2002                 if ((data >> 32) != 0)
2003                         return 1;
2004                 /* Else, falls through */
2005         default:
2006                 msr = find_msr_entry(vmx, msr_index);
2007                 if (msr) {
2008                         u64 old_msr_data = msr->data;
2009                         msr->data = data;
2010                         if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
2011                                 preempt_disable();
2012                                 ret = kvm_set_shared_msr(msr->index, msr->data,
2013                                                          msr->mask);
2014                                 preempt_enable();
2015                                 if (ret)
2016                                         msr->data = old_msr_data;
2017                         }
2018                         break;
2019                 }
2020                 ret = kvm_set_msr_common(vcpu, msr_info);
2021         }
2022 
2023         return ret;
2024 }
2025 
2026 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2027 {
2028         __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
2029         switch (reg) {
2030         case VCPU_REGS_RSP:
2031                 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2032                 break;
2033         case VCPU_REGS_RIP:
2034                 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2035                 break;
2036         case VCPU_EXREG_PDPTR:
2037                 if (enable_ept)
2038                         ept_save_pdptrs(vcpu);
2039                 break;
2040         default:
2041                 break;
2042         }
2043 }
2044 
2045 static __init int cpu_has_kvm_support(void)
2046 {
2047         return cpu_has_vmx();
2048 }
2049 
2050 static __init int vmx_disabled_by_bios(void)
2051 {
2052         u64 msr;
2053 
2054         rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
2055         if (msr & FEATURE_CONTROL_LOCKED) {
2056                 /* launched w/ TXT and VMX disabled */
2057                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2058                         && tboot_enabled())
2059                         return 1;
2060                 /* launched w/o TXT and VMX only enabled w/ TXT */
2061                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2062                         && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
2063                         && !tboot_enabled()) {
2064                         printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
2065                                 "activate TXT before enabling KVM\n");
2066                         return 1;
2067                 }
2068                 /* launched w/o TXT and VMX disabled */
2069                 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
2070                         && !tboot_enabled())
2071                         return 1;
2072         }
2073 
2074         return 0;
2075 }
2076 
2077 static void kvm_cpu_vmxon(u64 addr)
2078 {
2079         cr4_set_bits(X86_CR4_VMXE);
2080         intel_pt_handle_vmx(1);
2081 
2082         asm volatile ("vmxon %0" : : "m"(addr));
2083 }
2084 
2085 static int hardware_enable(void)
2086 {
2087         int cpu = raw_smp_processor_id();
2088         u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2089         u64 old, test_bits;
2090 
2091         if (cr4_read_shadow() & X86_CR4_VMXE)
2092                 return -EBUSY;
2093 
2094         /*
2095          * This can happen if we hot-added a CPU but failed to allocate
2096          * VP assist page for it.
2097          */
2098         if (static_branch_unlikely(&enable_evmcs) &&
2099             !hv_get_vp_assist_page(cpu))
2100                 return -EFAULT;
2101 
2102         INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
2103         INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
2104         spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
2105 
2106         /*
2107          * Now we can enable the vmclear operation in kdump
2108          * since the loaded_vmcss_on_cpu list on this cpu
2109          * has been initialized.
2110          *
2111          * Though the cpu is not in VMX operation now, there
2112          * is no problem to enable the vmclear operation
2113          * for the loaded_vmcss_on_cpu list is empty!
2114          */
2115         crash_enable_local_vmclear(cpu);
2116 
2117         rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
2118 
2119         test_bits = FEATURE_CONTROL_LOCKED;
2120         test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
2121         if (tboot_enabled())
2122                 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
2123 
2124         if ((old & test_bits) != test_bits) {
2125                 /* enable and lock */
2126                 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
2127         }
2128         kvm_cpu_vmxon(phys_addr);
2129         if (enable_ept)
2130                 ept_sync_global();
2131 
2132         return 0;
2133 }
2134 
2135 static void vmclear_local_loaded_vmcss(void)
2136 {
2137         int cpu = raw_smp_processor_id();
2138         struct loaded_vmcs *v, *n;
2139 
2140         list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2141                                  loaded_vmcss_on_cpu_link)
2142                 __loaded_vmcs_clear(v);
2143 }
2144 
2145 
2146 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
2147  * tricks.
2148  */
2149 static void kvm_cpu_vmxoff(void)
2150 {
2151         asm volatile (__ex("vmxoff"));
2152 
2153         intel_pt_handle_vmx(0);
2154         cr4_clear_bits(X86_CR4_VMXE);
2155 }
2156 
2157 static void hardware_disable(void)
2158 {
2159         vmclear_local_loaded_vmcss();
2160         kvm_cpu_vmxoff();
2161 }
2162 
2163 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2164                                       u32 msr, u32 *result)
2165 {
2166         u32 vmx_msr_low, vmx_msr_high;
2167         u32 ctl = ctl_min | ctl_opt;
2168 
2169         rdmsr(msr, vmx_msr_low, vmx_msr_high);
2170 
2171         ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2172         ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2173 
2174         /* Ensure minimum (required) set of control bits are supported. */
2175         if (ctl_min & ~ctl)
2176                 return -EIO;
2177 
2178         *result = ctl;
2179         return 0;
2180 }
2181 
2182 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2183                                     struct vmx_capability *vmx_cap)
2184 {
2185         u32 vmx_msr_low, vmx_msr_high;
2186         u32 min, opt, min2, opt2;
2187         u32 _pin_based_exec_control = 0;
2188         u32 _cpu_based_exec_control = 0;
2189         u32 _cpu_based_2nd_exec_control = 0;
2190         u32 _vmexit_control = 0;
2191         u32 _vmentry_control = 0;
2192 
2193         memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2194         min = CPU_BASED_HLT_EXITING |
2195 #ifdef CONFIG_X86_64
2196               CPU_BASED_CR8_LOAD_EXITING |
2197               CPU_BASED_CR8_STORE_EXITING |
2198 #endif
2199               CPU_BASED_CR3_LOAD_EXITING |
2200               CPU_BASED_CR3_STORE_EXITING |
2201               CPU_BASED_UNCOND_IO_EXITING |
2202               CPU_BASED_MOV_DR_EXITING |
2203               CPU_BASED_USE_TSC_OFFSETING |
2204               CPU_BASED_MWAIT_EXITING |
2205               CPU_BASED_MONITOR_EXITING |
2206               CPU_BASED_INVLPG_EXITING |
2207               CPU_BASED_RDPMC_EXITING;
2208 
2209         opt = CPU_BASED_TPR_SHADOW |
2210               CPU_BASED_USE_MSR_BITMAPS |
2211               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2212         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2213                                 &_cpu_based_exec_control) < 0)
2214                 return -EIO;
2215 #ifdef CONFIG_X86_64
2216         if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2217                 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2218                                            ~CPU_BASED_CR8_STORE_EXITING;
2219 #endif
2220         if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2221                 min2 = 0;
2222                 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2223                         SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2224                         SECONDARY_EXEC_WBINVD_EXITING |
2225                         SECONDARY_EXEC_ENABLE_VPID |
2226                         SECONDARY_EXEC_ENABLE_EPT |
2227                         SECONDARY_EXEC_UNRESTRICTED_GUEST |
2228                         SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2229                         SECONDARY_EXEC_DESC |
2230                         SECONDARY_EXEC_RDTSCP |
2231                         SECONDARY_EXEC_ENABLE_INVPCID |
2232                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
2233                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2234                         SECONDARY_EXEC_SHADOW_VMCS |
2235                         SECONDARY_EXEC_XSAVES |
2236                         SECONDARY_EXEC_RDSEED_EXITING |
2237                         SECONDARY_EXEC_RDRAND_EXITING |
2238                         SECONDARY_EXEC_ENABLE_PML |
2239                         SECONDARY_EXEC_TSC_SCALING |
2240                         SECONDARY_EXEC_PT_USE_GPA |
2241                         SECONDARY_EXEC_PT_CONCEAL_VMX |
2242                         SECONDARY_EXEC_ENABLE_VMFUNC |
2243                         SECONDARY_EXEC_ENCLS_EXITING;
2244                 if (adjust_vmx_controls(min2, opt2,
2245                                         MSR_IA32_VMX_PROCBASED_CTLS2,
2246                                         &_cpu_based_2nd_exec_control) < 0)
2247                         return -EIO;
2248         }
2249 #ifndef CONFIG_X86_64
2250         if (!(_cpu_based_2nd_exec_control &
2251                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2252                 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2253 #endif
2254 
2255         if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2256                 _cpu_based_2nd_exec_control &= ~(
2257                                 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2258                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2259                                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2260 
2261         rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2262                 &vmx_cap->ept, &vmx_cap->vpid);
2263 
2264         if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2265                 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2266                    enabled */
2267                 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2268                                              CPU_BASED_CR3_STORE_EXITING |
2269                                              CPU_BASED_INVLPG_EXITING);
2270         } else if (vmx_cap->ept) {
2271                 vmx_cap->ept = 0;
2272                 pr_warn_once("EPT CAP should not exist if not support "
2273                                 "1-setting enable EPT VM-execution control\n");
2274         }
2275         if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2276                 vmx_cap->vpid) {
2277                 vmx_cap->vpid = 0;
2278                 pr_warn_once("VPID CAP should not exist if not support "
2279                                 "1-setting enable VPID VM-execution control\n");
2280         }
2281 
2282         min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2283 #ifdef CONFIG_X86_64
2284         min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2285 #endif
2286         opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2287               VM_EXIT_SAVE_IA32_PAT |
2288               VM_EXIT_LOAD_IA32_PAT |
2289               VM_EXIT_LOAD_IA32_EFER |
2290               VM_EXIT_CLEAR_BNDCFGS |
2291               VM_EXIT_PT_CONCEAL_PIP |
2292               VM_EXIT_CLEAR_IA32_RTIT_CTL;
2293         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2294                                 &_vmexit_control) < 0)
2295                 return -EIO;
2296 
2297         min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2298         opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2299                  PIN_BASED_VMX_PREEMPTION_TIMER;
2300         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2301                                 &_pin_based_exec_control) < 0)
2302                 return -EIO;
2303 
2304         if (cpu_has_broken_vmx_preemption_timer())
2305                 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2306         if (!(_cpu_based_2nd_exec_control &
2307                 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2308                 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2309 
2310         min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2311         opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2312               VM_ENTRY_LOAD_IA32_PAT |
2313               VM_ENTRY_LOAD_IA32_EFER |
2314               VM_ENTRY_LOAD_BNDCFGS |
2315               VM_ENTRY_PT_CONCEAL_PIP |
2316               VM_ENTRY_LOAD_IA32_RTIT_CTL;
2317         if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2318                                 &_vmentry_control) < 0)
2319                 return -EIO;
2320 
2321         /*
2322          * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2323          * can't be used due to an errata where VM Exit may incorrectly clear
2324          * IA32_PERF_GLOBAL_CTRL[34:32].  Workaround the errata by using the
2325          * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2326          */
2327         if (boot_cpu_data.x86 == 0x6) {
2328                 switch (boot_cpu_data.x86_model) {
2329                 case 26: /* AAK155 */
2330                 case 30: /* AAP115 */
2331                 case 37: /* AAT100 */
2332                 case 44: /* BC86,AAY89,BD102 */
2333                 case 46: /* BA97 */
2334                         _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2335                         _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2336                         pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2337                                         "does not work properly. Using workaround\n");
2338                         break;
2339                 default:
2340                         break;
2341                 }
2342         }
2343 
2344 
2345         rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2346 
2347         /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2348         if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2349                 return -EIO;
2350 
2351 #ifdef CONFIG_X86_64
2352         /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2353         if (vmx_msr_high & (1u<<16))
2354                 return -EIO;
2355 #endif
2356 
2357         /* Require Write-Back (WB) memory type for VMCS accesses. */
2358         if (((vmx_msr_high >> 18) & 15) != 6)
2359                 return -EIO;
2360 
2361         vmcs_conf->size = vmx_msr_high & 0x1fff;
2362         vmcs_conf->order = get_order(vmcs_conf->size);
2363         vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2364 
2365         vmcs_conf->revision_id = vmx_msr_low;
2366 
2367         vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2368         vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2369         vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2370         vmcs_conf->vmexit_ctrl         = _vmexit_control;
2371         vmcs_conf->vmentry_ctrl        = _vmentry_control;
2372 
2373         if (static_branch_unlikely(&enable_evmcs))
2374                 evmcs_sanitize_exec_ctrls(vmcs_conf);
2375 
2376         return 0;
2377 }
2378 
2379 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
2380 {
2381         int node = cpu_to_node(cpu);
2382         struct page *pages;
2383         struct vmcs *vmcs;
2384 
2385         pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
2386         if (!pages)
2387                 return NULL;
2388         vmcs = page_address(pages);
2389         memset(vmcs, 0, vmcs_config.size);
2390 
2391         /* KVM supports Enlightened VMCS v1 only */
2392         if (static_branch_unlikely(&enable_evmcs))
2393                 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2394         else
2395                 vmcs->hdr.revision_id = vmcs_config.revision_id;
2396 
2397         if (shadow)
2398                 vmcs->hdr.shadow_vmcs = 1;
2399         return vmcs;
2400 }
2401 
2402 void free_vmcs(struct vmcs *vmcs)
2403 {
2404         free_pages((unsigned long)vmcs, vmcs_config.order);
2405 }
2406 
2407 /*
2408  * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2409  */
2410 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2411 {
2412         if (!loaded_vmcs->vmcs)
2413                 return;
2414         loaded_vmcs_clear(loaded_vmcs);
2415         free_vmcs(loaded_vmcs->vmcs);
2416         loaded_vmcs->vmcs = NULL;
2417         if (loaded_vmcs->msr_bitmap)
2418                 free_page((unsigned long)loaded_vmcs->msr_bitmap);
2419         WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2420 }
2421 
2422 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2423 {
2424         loaded_vmcs->vmcs = alloc_vmcs(false);
2425         if (!loaded_vmcs->vmcs)
2426                 return -ENOMEM;
2427 
2428         loaded_vmcs->shadow_vmcs = NULL;
2429         loaded_vmcs_init(loaded_vmcs);
2430 
2431         if (cpu_has_vmx_msr_bitmap()) {
2432                 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
2433                 if (!loaded_vmcs->msr_bitmap)
2434                         goto out_vmcs;
2435                 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2436 
2437                 if (IS_ENABLED(CONFIG_HYPERV) &&
2438                     static_branch_unlikely(&enable_evmcs) &&
2439                     (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2440                         struct hv_enlightened_vmcs *evmcs =
2441                                 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2442 
2443                         evmcs->hv_enlightenments_control.msr_bitmap = 1;
2444                 }
2445         }
2446 
2447         memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2448 
2449         return 0;
2450 
2451 out_vmcs:
2452         free_loaded_vmcs(loaded_vmcs);
2453         return -ENOMEM;
2454 }
2455 
2456 static void free_kvm_area(void)
2457 {
2458         int cpu;
2459 
2460         for_each_possible_cpu(cpu) {
2461                 free_vmcs(per_cpu(vmxarea, cpu));
2462                 per_cpu(vmxarea, cpu) = NULL;
2463         }
2464 }
2465 
2466 static __init int alloc_kvm_area(void)
2467 {
2468         int cpu;
2469 
2470         for_each_possible_cpu(cpu) {
2471                 struct vmcs *vmcs;
2472 
2473                 vmcs = alloc_vmcs_cpu(false, cpu);
2474                 if (!vmcs) {
2475                         free_kvm_area();
2476                         return -ENOMEM;
2477                 }
2478 
2479                 /*
2480                  * When eVMCS is enabled, alloc_vmcs_cpu() sets
2481                  * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2482                  * revision_id reported by MSR_IA32_VMX_BASIC.
2483                  *
2484                  * However, even though not explicitly documented by
2485                  * TLFS, VMXArea passed as VMXON argument should
2486                  * still be marked with revision_id reported by
2487                  * physical CPU.
2488                  */
2489                 if (static_branch_unlikely(&enable_evmcs))
2490                         vmcs->hdr.revision_id = vmcs_config.revision_id;
2491 
2492                 per_cpu(vmxarea, cpu) = vmcs;
2493         }
2494         return 0;
2495 }
2496 
2497 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2498                 struct kvm_segment *save)
2499 {
2500         if (!emulate_invalid_guest_state) {
2501                 /*
2502                  * CS and SS RPL should be equal during guest entry according
2503                  * to VMX spec, but in reality it is not always so. Since vcpu
2504                  * is in the middle of the transition from real mode to
2505                  * protected mode it is safe to assume that RPL 0 is a good
2506                  * default value.
2507                  */
2508                 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2509                         save->selector &= ~SEGMENT_RPL_MASK;
2510                 save->dpl = save->selector & SEGMENT_RPL_MASK;
2511                 save->s = 1;
2512         }
2513         vmx_set_segment(vcpu, save, seg);
2514 }
2515 
2516 static void enter_pmode(struct kvm_vcpu *vcpu)
2517 {
2518         unsigned long flags;
2519         struct vcpu_vmx *vmx = to_vmx(vcpu);
2520 
2521         /*
2522          * Update real mode segment cache. It may be not up-to-date if sement
2523          * register was written while vcpu was in a guest mode.
2524          */
2525         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2526         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2527         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2528         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2529         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2530         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2531 
2532         vmx->rmode.vm86_active = 0;
2533 
2534         vmx_segment_cache_clear(vmx);
2535 
2536         vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2537 
2538         flags = vmcs_readl(GUEST_RFLAGS);
2539         flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2540         flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2541         vmcs_writel(GUEST_RFLAGS, flags);
2542 
2543         vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2544                         (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2545 
2546         update_exception_bitmap(vcpu);
2547 
2548         fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2549         fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2550         fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2551         fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2552         fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2553         fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2554 }
2555 
2556 static void fix_rmode_seg(int seg, struct kvm_segment *save)
2557 {
2558         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2559         struct kvm_segment var = *save;
2560 
2561         var.dpl = 0x3;
2562         if (seg == VCPU_SREG_CS)
2563                 var.type = 0x3;
2564 
2565         if (!emulate_invalid_guest_state) {
2566                 var.selector = var.base >> 4;
2567                 var.base = var.base & 0xffff0;
2568                 var.limit = 0xffff;
2569                 var.g = 0;
2570                 var.db = 0;
2571                 var.present = 1;
2572                 var.s = 1;
2573                 var.l = 0;
2574                 var.unusable = 0;
2575                 var.type = 0x3;
2576                 var.avl = 0;
2577                 if (save->base & 0xf)
2578                         printk_once(KERN_WARNING "kvm: segment base is not "
2579                                         "paragraph aligned when entering "
2580                                         "protected mode (seg=%d)", seg);
2581         }
2582 
2583         vmcs_write16(sf->selector, var.selector);
2584         vmcs_writel(sf->base, var.base);
2585         vmcs_write32(sf->limit, var.limit);
2586         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2587 }
2588 
2589 static void enter_rmode(struct kvm_vcpu *vcpu)
2590 {
2591         unsigned long flags;
2592         struct vcpu_vmx *vmx = to_vmx(vcpu);
2593         struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2594 
2595         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2596         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2597         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2598         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2599         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2600         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2601         vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2602 
2603         vmx->rmode.vm86_active = 1;
2604 
2605         /*
2606          * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2607          * vcpu. Warn the user that an update is overdue.
2608          */
2609         if (!kvm_vmx->tss_addr)
2610                 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2611                              "called before entering vcpu\n");
2612 
2613         vmx_segment_cache_clear(vmx);
2614 
2615         vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2616         vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2617         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2618 
2619         flags = vmcs_readl(GUEST_RFLAGS);
2620         vmx->rmode.save_rflags = flags;
2621 
2622         flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2623 
2624         vmcs_writel(GUEST_RFLAGS, flags);
2625         vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2626         update_exception_bitmap(vcpu);
2627 
2628         fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2629         fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2630         fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2631         fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2632         fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2633         fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2634 
2635         kvm_mmu_reset_context(vcpu);
2636 }
2637 
2638 void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2639 {
2640         struct vcpu_vmx *vmx = to_vmx(vcpu);
2641         struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
2642 
2643         if (!msr)
2644                 return;
2645 
2646         vcpu->arch.efer = efer;
2647         if (efer & EFER_LMA) {
2648                 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2649                 msr->data = efer;
2650         } else {
2651                 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2652 
2653                 msr->data = efer & ~EFER_LME;
2654         }
2655         setup_msrs(vmx);
2656 }
2657 
2658 #ifdef CONFIG_X86_64
2659 
2660 static void enter_lmode(struct kvm_vcpu *vcpu)
2661 {
2662         u32 guest_tr_ar;
2663 
2664         vmx_segment_cache_clear(to_vmx(vcpu));
2665 
2666         guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2667         if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2668                 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2669                                      __func__);
2670                 vmcs_write32(GUEST_TR_AR_BYTES,
2671                              (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2672                              | VMX_AR_TYPE_BUSY_64_TSS);
2673         }
2674         vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2675 }
2676 
2677 static void exit_lmode(struct kvm_vcpu *vcpu)
2678 {
2679         vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2680         vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2681 }
2682 
2683 #endif
2684 
2685 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2686 {
2687         int vpid = to_vmx(vcpu)->vpid;
2688 
2689         if (!vpid_sync_vcpu_addr(vpid, addr))
2690                 vpid_sync_context(vpid);
2691 
2692         /*
2693          * If VPIDs are not supported or enabled, then the above is a no-op.
2694          * But we don't really need a TLB flush in that case anyway, because
2695          * each VM entry/exit includes an implicit flush when VPID is 0.
2696          */
2697 }
2698 
2699 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2700 {
2701         ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2702 
2703         vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
2704         vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
2705 }
2706 
2707 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
2708 {
2709         if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
2710                 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2711         __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
2712 }
2713 
2714 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2715 {
2716         ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2717 
2718         vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
2719         vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
2720 }
2721 
2722 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
2723 {
2724         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2725 
2726         if (!test_bit(VCPU_EXREG_PDPTR,
2727                       (unsigned long *)&vcpu->arch.regs_dirty))
2728                 return;
2729 
2730         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2731                 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2732                 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2733                 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2734                 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2735         }
2736 }
2737 
2738 void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2739 {
2740         struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2741 
2742         if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
2743                 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2744                 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2745                 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2746                 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2747         }
2748 
2749         __set_bit(VCPU_EXREG_PDPTR,
2750                   (unsigned long *)&vcpu->arch.regs_avail);
2751         __set_bit(VCPU_EXREG_PDPTR,
2752                   (unsigned long *)&vcpu->arch.regs_dirty);
2753 }
2754 
2755 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
2756                                         unsigned long cr0,
2757                                         struct kvm_vcpu *vcpu)
2758 {
2759         if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
2760                 vmx_decache_cr3(vcpu);
2761         if (!(cr0 & X86_CR0_PG)) {
2762                 /* From paging/starting to nonpaging */
2763                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2764                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
2765                              (CPU_BASED_CR3_LOAD_EXITING |
2766                               CPU_BASED_CR3_STORE_EXITING));
2767                 vcpu->arch.cr0 = cr0;
2768                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2769         } else if (!is_paging(vcpu)) {
2770                 /* From nonpaging to paging */
2771                 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
2772                              vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
2773                              ~(CPU_BASED_CR3_LOAD_EXITING |
2774                                CPU_BASED_CR3_STORE_EXITING));
2775                 vcpu->arch.cr0 = cr0;
2776                 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
2777         }
2778 
2779         if (!(cr0 & X86_CR0_WP))
2780                 *hw_cr0 &= ~X86_CR0_WP;
2781 }
2782 
2783 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2784 {
2785         struct vcpu_vmx *vmx = to_vmx(vcpu);
2786         unsigned long hw_cr0;
2787 
2788         hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
2789         if (enable_unrestricted_guest)
2790                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
2791         else {
2792                 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
2793 
2794                 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
2795                         enter_pmode(vcpu);
2796 
2797                 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
2798                         enter_rmode(vcpu);
2799         }
2800 
2801 #ifdef CONFIG_X86_64
2802         if (vcpu->arch.efer & EFER_LME) {
2803                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
2804                         enter_lmode(vcpu);
2805                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
2806                         exit_lmode(vcpu);
2807         }
2808 #endif
2809 
2810         if (enable_ept && !enable_unrestricted_guest)
2811                 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
2812 
2813         vmcs_writel(CR0_READ_SHADOW, cr0);
2814         vmcs_writel(GUEST_CR0, hw_cr0);
2815         vcpu->arch.cr0 = cr0;
2816 
2817         /* depends on vcpu->arch.cr0 to be set to a new value */
2818         vmx->emulation_required = emulation_required(vcpu);
2819 }
2820 
2821 static int get_ept_level(struct kvm_vcpu *vcpu)
2822 {
2823         if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
2824                 return 5;
2825         return 4;
2826 }
2827 
2828 u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
2829 {
2830         u64 eptp = VMX_EPTP_MT_WB;
2831 
2832         eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
2833 
2834         if (enable_ept_ad_bits &&
2835             (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
2836                 eptp |= VMX_EPTP_AD_ENABLE_BIT;
2837         eptp |= (root_hpa & PAGE_MASK);
2838 
2839         return eptp;
2840 }
2841 
2842 void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
2843 {
2844         struct kvm *kvm = vcpu->kvm;
2845         unsigned long guest_cr3;
2846         u64 eptp;
2847 
2848         guest_cr3 = cr3;
2849         if (enable_ept) {
2850                 eptp = construct_eptp(vcpu, cr3);
2851                 vmcs_write64(EPT_POINTER, eptp);
2852 
2853                 if (kvm_x86_ops->tlb_remote_flush) {
2854                         spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2855                         to_vmx(vcpu)->ept_pointer = eptp;
2856                         to_kvm_vmx(kvm)->ept_pointers_match
2857                                 = EPT_POINTERS_CHECK;
2858                         spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
2859                 }
2860 
2861                 if (enable_unrestricted_guest || is_paging(vcpu) ||
2862                     is_guest_mode(vcpu))
2863                         guest_cr3 = kvm_read_cr3(vcpu);
2864                 else
2865                         guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
2866                 ept_load_pdptrs(vcpu);
2867         }
2868 
2869         vmcs_writel(GUEST_CR3, guest_cr3);
2870 }
2871 
2872 int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2873 {
2874         /*
2875          * Pass through host's Machine Check Enable value to hw_cr4, which
2876          * is in force while we are in guest mode.  Do not let guests control
2877          * this bit, even if host CR4.MCE == 0.
2878          */
2879         unsigned long hw_cr4;
2880 
2881         hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
2882         if (enable_unrestricted_guest)
2883                 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
2884         else if (to_vmx(vcpu)->rmode.vm86_active)
2885                 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
2886         else
2887                 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
2888 
2889         if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
2890                 if (cr4 & X86_CR4_UMIP) {
2891                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
2892                                 SECONDARY_EXEC_DESC);
2893                         hw_cr4 &= ~X86_CR4_UMIP;
2894                 } else if (!is_guest_mode(vcpu) ||
2895                         !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
2896                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
2897                                         SECONDARY_EXEC_DESC);
2898         }
2899 
2900         if (cr4 & X86_CR4_VMXE) {
2901                 /*
2902                  * To use VMXON (and later other VMX instructions), a guest
2903                  * must first be able to turn on cr4.VMXE (see handle_vmon()).
2904                  * So basically the check on whether to allow nested VMX
2905                  * is here.  We operate under the default treatment of SMM,
2906                  * so VMX cannot be enabled under SMM.
2907                  */
2908                 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
2909                         return 1;
2910         }
2911 
2912         if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
2913                 return 1;
2914 
2915         vcpu->arch.cr4 = cr4;
2916 
2917         if (!enable_unrestricted_guest) {
2918                 if (enable_ept) {
2919                         if (!is_paging(vcpu)) {
2920                                 hw_cr4 &= ~X86_CR4_PAE;
2921                                 hw_cr4 |= X86_CR4_PSE;
2922                         } else if (!(cr4 & X86_CR4_PAE)) {
2923                                 hw_cr4 &= ~X86_CR4_PAE;
2924                         }
2925                 }
2926 
2927                 /*
2928                  * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
2929                  * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
2930                  * to be manually disabled when guest switches to non-paging
2931                  * mode.
2932                  *
2933                  * If !enable_unrestricted_guest, the CPU is always running
2934                  * with CR0.PG=1 and CR4 needs to be modified.
2935                  * If enable_unrestricted_guest, the CPU automatically
2936                  * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
2937                  */
2938                 if (!is_paging(vcpu))
2939                         hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
2940         }
2941 
2942         vmcs_writel(CR4_READ_SHADOW, cr4);
2943         vmcs_writel(GUEST_CR4, hw_cr4);
2944         return 0;
2945 }
2946 
2947 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
2948 {
2949         struct vcpu_vmx *vmx = to_vmx(vcpu);
2950         u32 ar;
2951 
2952         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
2953                 *var = vmx->rmode.segs[seg];
2954                 if (seg == VCPU_SREG_TR
2955                     || var->selector == vmx_read_guest_seg_selector(vmx, seg))
2956                         return;
2957                 var->base = vmx_read_guest_seg_base(vmx, seg);
2958                 var->selector = vmx_read_guest_seg_selector(vmx, seg);
2959                 return;
2960         }
2961         var->base = vmx_read_guest_seg_base(vmx, seg);
2962         var->limit = vmx_read_guest_seg_limit(vmx, seg);
2963         var->selector = vmx_read_guest_seg_selector(vmx, seg);
2964         ar = vmx_read_guest_seg_ar(vmx, seg);
2965         var->unusable = (ar >> 16) & 1;
2966         var->type = ar & 15;
2967         var->s = (ar >> 4) & 1;
2968         var->dpl = (ar >> 5) & 3;
2969         /*
2970          * Some userspaces do not preserve unusable property. Since usable
2971          * segment has to be present according to VMX spec we can use present
2972          * property to amend userspace bug by making unusable segment always
2973          * nonpresent. vmx_segment_access_rights() already marks nonpresent
2974          * segment as unusable.
2975          */
2976         var->present = !var->unusable;
2977         var->avl = (ar >> 12) & 1;
2978         var->l = (ar >> 13) & 1;
2979         var->db = (ar >> 14) & 1;
2980         var->g = (ar >> 15) & 1;
2981 }
2982 
2983 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2984 {
2985         struct kvm_segment s;
2986 
2987         if (to_vmx(vcpu)->rmode.vm86_active) {
2988                 vmx_get_segment(vcpu, &s, seg);
2989                 return s.base;
2990         }
2991         return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
2992 }
2993 
2994 int vmx_get_cpl(struct kvm_vcpu *vcpu)
2995 {
2996         struct vcpu_vmx *vmx = to_vmx(vcpu);
2997 
2998         if (unlikely(vmx->rmode.vm86_active))
2999                 return 0;
3000         else {
3001                 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3002                 return VMX_AR_DPL(ar);
3003         }
3004 }
3005 
3006 static u32 vmx_segment_access_rights(struct kvm_segment *var)
3007 {
3008         u32 ar;
3009 
3010         if (var->unusable || !var->present)
3011                 ar = 1 << 16;
3012         else {
3013                 ar = var->type & 15;
3014                 ar |= (var->s & 1) << 4;
3015                 ar |= (var->dpl & 3) << 5;
3016                 ar |= (var->present & 1) << 7;
3017                 ar |= (var->avl & 1) << 12;
3018                 ar |= (var->l & 1) << 13;
3019                 ar |= (var->db & 1) << 14;
3020                 ar |= (var->g & 1) << 15;
3021         }
3022 
3023         return ar;
3024 }
3025 
3026 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3027 {
3028         struct vcpu_vmx *vmx = to_vmx(vcpu);
3029         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3030 
3031         vmx_segment_cache_clear(vmx);
3032 
3033         if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3034                 vmx->rmode.segs[seg] = *var;
3035                 if (seg == VCPU_SREG_TR)
3036                         vmcs_write16(sf->selector, var->selector);
3037                 else if (var->s)
3038                         fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3039                 goto out;
3040         }
3041 
3042         vmcs_writel(sf->base, var->base);
3043         vmcs_write32(sf->limit, var->limit);
3044         vmcs_write16(sf->selector, var->selector);
3045 
3046         /*
3047          *   Fix the "Accessed" bit in AR field of segment registers for older
3048          * qemu binaries.
3049          *   IA32 arch specifies that at the time of processor reset the
3050          * "Accessed" bit in the AR field of segment registers is 1. And qemu
3051          * is setting it to 0 in the userland code. This causes invalid guest
3052          * state vmexit when "unrestricted guest" mode is turned on.
3053          *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3054          * tree. Newer qemu binaries with that qemu fix would not need this
3055          * kvm hack.
3056          */
3057         if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
3058                 var->type |= 0x1; /* Accessed */
3059 
3060         vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3061 
3062 out:
3063         vmx->emulation_required = emulation_required(vcpu);
3064 }
3065 
3066 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3067 {
3068         u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3069 
3070         *db = (ar >> 14) & 1;
3071         *l = (ar >> 13) & 1;
3072 }
3073 
3074 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3075 {
3076         dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3077         dt->address = vmcs_readl(GUEST_IDTR_BASE);
3078 }
3079 
3080 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3081 {
3082         vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3083         vmcs_writel(GUEST_IDTR_BASE, dt->address);
3084 }
3085 
3086 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3087 {
3088         dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3089         dt->address = vmcs_readl(GUEST_GDTR_BASE);
3090 }
3091 
3092 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3093 {
3094         vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3095         vmcs_writel(GUEST_GDTR_BASE, dt->address);
3096 }
3097 
3098 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3099 {
3100         struct kvm_segment var;
3101         u32 ar;
3102 
3103         vmx_get_segment(vcpu, &var, seg);
3104         var.dpl = 0x3;
3105         if (seg == VCPU_SREG_CS)
3106                 var.type = 0x3;
3107         ar = vmx_segment_access_rights(&var);
3108 
3109         if (var.base != (var.selector << 4))
3110                 return false;
3111         if (var.limit != 0xffff)
3112                 return false;
3113         if (ar != 0xf3)
3114                 return false;
3115 
3116         return true;
3117 }
3118 
3119 static bool code_segment_valid(struct kvm_vcpu *vcpu)
3120 {
3121         struct kvm_segment cs;
3122         unsigned int cs_rpl;
3123 
3124         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3125         cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3126 
3127         if (cs.unusable)
3128                 return false;
3129         if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3130                 return false;
3131         if (!cs.s)
3132                 return false;
3133         if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3134                 if (cs.dpl > cs_rpl)
3135                         return false;
3136         } else {
3137                 if (cs.dpl != cs_rpl)
3138                         return false;
3139         }
3140         if (!cs.present)
3141                 return false;
3142 
3143         /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3144         return true;
3145 }
3146 
3147 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3148 {
3149         struct kvm_segment ss;
3150         unsigned int ss_rpl;
3151 
3152         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3153         ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3154 
3155         if (ss.unusable)
3156                 return true;
3157         if (ss.type != 3 && ss.type != 7)
3158                 return false;
3159         if (!ss.s)
3160                 return false;
3161         if (ss.dpl != ss_rpl) /* DPL != RPL */
3162                 return false;
3163         if (!ss.present)
3164                 return false;
3165 
3166         return true;
3167 }
3168 
3169 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3170 {
3171         struct kvm_segment var;
3172         unsigned int rpl;
3173 
3174         vmx_get_segment(vcpu, &var, seg);
3175         rpl = var.selector & SEGMENT_RPL_MASK;
3176 
3177         if (var.unusable)
3178                 return true;
3179         if (!var.s)
3180                 return false;
3181         if (!var.present)
3182                 return false;
3183         if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3184                 if (var.dpl < rpl) /* DPL < RPL */
3185                         return false;
3186         }
3187 
3188         /* TODO: Add other members to kvm_segment_field to allow checking for other access
3189          * rights flags
3190          */
3191         return true;
3192 }
3193 
3194 static bool tr_valid(struct kvm_vcpu *vcpu)
3195 {
3196         struct kvm_segment tr;
3197 
3198         vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3199 
3200         if (tr.unusable)
3201                 return false;
3202         if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
3203                 return false;
3204         if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3205                 return false;
3206         if (!tr.present)
3207                 return false;
3208 
3209         return true;
3210 }
3211 
3212 static bool ldtr_valid(struct kvm_vcpu *vcpu)
3213 {
3214         struct kvm_segment ldtr;
3215 
3216         vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3217 
3218         if (ldtr.unusable)
3219                 return true;
3220         if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
3221                 return false;
3222         if (ldtr.type != 2)
3223                 return false;
3224         if (!ldtr.present)
3225                 return false;
3226 
3227         return true;
3228 }
3229 
3230 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3231 {
3232         struct kvm_segment cs, ss;
3233 
3234         vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3235         vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3236 
3237         return ((cs.selector & SEGMENT_RPL_MASK) ==
3238                  (ss.selector & SEGMENT_RPL_MASK));
3239 }
3240 
3241 /*
3242  * Check if guest state is valid. Returns true if valid, false if
3243  * not.
3244  * We assume that registers are always usable
3245  */
3246 static bool guest_state_valid(struct kvm_vcpu *vcpu)
3247 {
3248         if (enable_unrestricted_guest)
3249                 return true;
3250 
3251         /* real mode guest state checks */
3252         if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3253                 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3254                         return false;
3255                 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3256                         return false;
3257                 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3258                         return false;
3259                 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3260                         return false;
3261                 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3262                         return false;
3263                 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3264                         return false;
3265         } else {
3266         /* protected mode guest state checks */
3267                 if (!cs_ss_rpl_check(vcpu))
3268                         return false;
3269                 if (!code_segment_valid(vcpu))
3270                         return false;
3271                 if (!stack_segment_valid(vcpu))
3272                         return false;
3273                 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3274                         return false;
3275                 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3276                         return false;
3277                 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3278                         return false;
3279                 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3280                         return false;
3281                 if (!tr_valid(vcpu))
3282                         return false;
3283                 if (!ldtr_valid(vcpu))
3284                         return false;
3285         }
3286         /* TODO:
3287          * - Add checks on RIP
3288          * - Add checks on RFLAGS
3289          */
3290 
3291         return true;
3292 }
3293 
3294 static int init_rmode_tss(struct kvm *kvm)
3295 {
3296         gfn_t fn;
3297         u16 data = 0;
3298         int idx, r;
3299 
3300         idx = srcu_read_lock(&kvm->srcu);
3301         fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
3302         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3303         if (r < 0)
3304                 goto out;
3305         data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3306         r = kvm_write_guest_page(kvm, fn++, &data,
3307                         TSS_IOPB_BASE_OFFSET, sizeof(u16));
3308         if (r < 0)
3309                 goto out;
3310         r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
3311         if (r < 0)
3312                 goto out;
3313         r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
3314         if (r < 0)
3315                 goto out;
3316         data = ~0;
3317         r = kvm_write_guest_page(kvm, fn, &data,
3318                                  RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
3319                                  sizeof(u8));
3320 out:
3321         srcu_read_unlock(&kvm->srcu, idx);
3322         return r;
3323 }
3324 
3325 static int init_rmode_identity_map(struct kvm *kvm)
3326 {
3327         struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3328         int i, idx, r = 0;
3329         kvm_pfn_t identity_map_pfn;
3330         u32 tmp;
3331 
3332         /* Protect kvm_vmx->ept_identity_pagetable_done. */
3333         mutex_lock(&kvm->slots_lock);
3334 
3335         if (likely(kvm_vmx->ept_identity_pagetable_done))
3336                 goto out2;
3337 
3338         if (!kvm_vmx->ept_identity_map_addr)
3339                 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3340         identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
3341 
3342         r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3343                                     kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
3344         if (r < 0)
3345                 goto out2;
3346 
3347         idx = srcu_read_lock(&kvm->srcu);
3348         r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
3349         if (r < 0)
3350                 goto out;
3351         /* Set up identity-mapping pagetable for EPT in real mode */
3352         for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3353                 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3354                         _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3355                 r = kvm_write_guest_page(kvm, identity_map_pfn,
3356                                 &tmp, i * sizeof(tmp), sizeof(tmp));
3357                 if (r < 0)
3358                         goto out;
3359         }
3360         kvm_vmx->ept_identity_pagetable_done = true;
3361 
3362 out:
3363         srcu_read_unlock(&kvm->srcu, idx);
3364 
3365 out2:
3366         mutex_unlock(&kvm->slots_lock);
3367         return r;
3368 }
3369 
3370 static void seg_setup(int seg)
3371 {
3372         const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3373         unsigned int ar;
3374 
3375         vmcs_write16(sf->selector, 0);
3376         vmcs_writel(sf->base, 0);
3377         vmcs_write32(sf->limit, 0xffff);
3378         ar = 0x93;
3379         if (seg == VCPU_SREG_CS)
3380                 ar |= 0x08; /* code segment */
3381 
3382         vmcs_write32(sf->ar_bytes, ar);
3383 }
3384 
3385 static int alloc_apic_access_page(struct kvm *kvm)
3386 {
3387         struct page *page;
3388         int r = 0;
3389 
3390         mutex_lock(&kvm->slots_lock);
3391         if (kvm->arch.apic_access_page_done)
3392                 goto out;
3393         r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3394                                     APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3395         if (r)
3396                 goto out;
3397 
3398         page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3399         if (is_error_page(page)) {
3400                 r = -EFAULT;
3401                 goto out;
3402         }
3403 
3404         /*
3405          * Do not pin the page in memory, so that memory hot-unplug
3406          * is able to migrate it.
3407          */
3408         put_page(page);
3409         kvm->arch.apic_access_page_done = true;
3410 out:
3411         mutex_unlock(&kvm->slots_lock);
3412         return r;
3413 }
3414 
3415 int allocate_vpid(void)
3416 {
3417         int vpid;
3418 
3419         if (!enable_vpid)
3420                 return 0;
3421         spin_lock(&vmx_vpid_lock);
3422         vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3423         if (vpid < VMX_NR_VPIDS)
3424                 __set_bit(vpid, vmx_vpid_bitmap);
3425         else
3426                 vpid = 0;
3427         spin_unlock(&vmx_vpid_lock);
3428         return vpid;
3429 }
3430 
3431 void free_vpid(int vpid)
3432 {
3433         if (!enable_vpid || vpid == 0)
3434                 return;
3435         spin_lock(&vmx_vpid_lock);
3436         __clear_bit(vpid, vmx_vpid_bitmap);
3437         spin_unlock(&vmx_vpid_lock);
3438 }
3439 
3440 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
3441                                                           u32 msr, int type)
3442 {
3443         int f = sizeof(unsigned long);
3444 
3445         if (!cpu_has_vmx_msr_bitmap())
3446                 return;
3447 
3448         if (static_branch_unlikely(&enable_evmcs))
3449                 evmcs_touch_msr_bitmap();
3450 
3451         /*
3452          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3453          * have the write-low and read-high bitmap offsets the wrong way round.
3454          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3455          */
3456         if (msr <= 0x1fff) {
3457                 if (type & MSR_TYPE_R)
3458                         /* read-low */
3459                         __clear_bit(msr, msr_bitmap + 0x000 / f);
3460 
3461                 if (type & MSR_TYPE_W)
3462                         /* write-low */
3463                         __clear_bit(msr, msr_bitmap + 0x800 / f);
3464 
3465         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3466                 msr &= 0x1fff;
3467                 if (type & MSR_TYPE_R)
3468                         /* read-high */
3469                         __clear_bit(msr, msr_bitmap + 0x400 / f);
3470 
3471                 if (type & MSR_TYPE_W)
3472                         /* write-high */
3473                         __clear_bit(msr, msr_bitmap + 0xc00 / f);
3474 
3475         }
3476 }
3477 
3478 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
3479                                                          u32 msr, int type)
3480 {
3481         int f = sizeof(unsigned long);
3482 
3483         if (!cpu_has_vmx_msr_bitmap())
3484                 return;
3485 
3486         if (static_branch_unlikely(&enable_evmcs))
3487                 evmcs_touch_msr_bitmap();
3488 
3489         /*
3490          * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
3491          * have the write-low and read-high bitmap offsets the wrong way round.
3492          * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
3493          */
3494         if (msr <= 0x1fff) {
3495                 if (type & MSR_TYPE_R)
3496                         /* read-low */
3497                         __set_bit(msr, msr_bitmap + 0x000 / f);
3498 
3499                 if (type & MSR_TYPE_W)
3500                         /* write-low */
3501                         __set_bit(msr, msr_bitmap + 0x800 / f);
3502 
3503         } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
3504                 msr &= 0x1fff;
3505                 if (type & MSR_TYPE_R)
3506                         /* read-high */
3507                         __set_bit(msr, msr_bitmap + 0x400 / f);
3508 
3509                 if (type & MSR_TYPE_W)
3510                         /* write-high */
3511                         __set_bit(msr, msr_bitmap + 0xc00 / f);
3512 
3513         }
3514 }
3515 
3516 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
3517                                                       u32 msr, int type, bool value)
3518 {
3519         if (value)
3520                 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
3521         else
3522                 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
3523 }
3524 
3525 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3526 {
3527         u8 mode = 0;
3528 
3529         if (cpu_has_secondary_exec_ctrls() &&
3530             (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
3531              SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3532                 mode |= MSR_BITMAP_MODE_X2APIC;
3533                 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3534                         mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3535         }
3536 
3537         return mode;
3538 }
3539 
3540 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
3541                                          u8 mode)
3542 {
3543         int msr;
3544 
3545         for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3546                 unsigned word = msr / BITS_PER_LONG;
3547                 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3548                 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
3549         }
3550 
3551         if (mode & MSR_BITMAP_MODE_X2APIC) {
3552                 /*
3553                  * TPR reads and writes can be virtualized even if virtual interrupt
3554                  * delivery is not in use.
3555                  */
3556                 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
3557                 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3558                         vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
3559                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3560                         vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3561                 }
3562         }
3563 }
3564 
3565 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3566 {
3567         struct vcpu_vmx *vmx = to_vmx(vcpu);
3568         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3569         u8 mode = vmx_msr_bitmap_mode(vcpu);
3570         u8 changed = mode ^ vmx->msr_bitmap_mode;
3571 
3572         if (!changed)
3573                 return;
3574 
3575         if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3576                 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
3577 
3578         vmx->msr_bitmap_mode = mode;
3579 }
3580 
3581 void pt_update_intercept_for_msr(struct vcpu_vmx *vmx)
3582 {
3583         unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3584         bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3585         u32 i;
3586 
3587         vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_STATUS,
3588                                                         MSR_TYPE_RW, flag);
3589         vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_BASE,
3590                                                         MSR_TYPE_RW, flag);
3591         vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_OUTPUT_MASK,
3592                                                         MSR_TYPE_RW, flag);
3593         vmx_set_intercept_for_msr(msr_bitmap, MSR_IA32_RTIT_CR3_MATCH,
3594                                                         MSR_TYPE_RW, flag);
3595         for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3596                 vmx_set_intercept_for_msr(msr_bitmap,
3597                         MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3598                 vmx_set_intercept_for_msr(msr_bitmap,
3599                         MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3600         }
3601 }
3602 
3603 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
3604 {
3605         return enable_apicv;
3606 }
3607 
3608 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3609 {
3610         struct vcpu_vmx *vmx = to_vmx(vcpu);
3611         void *vapic_page;
3612         u32 vppr;
3613         int rvi;
3614 
3615         if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3616                 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3617                 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
3618                 return false;
3619 
3620         rvi = vmx_get_rvi();
3621 
3622         vapic_page = kmap(vmx->nested.virtual_apic_page);
3623         vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3624         kunmap(vmx->nested.virtual_apic_page);
3625 
3626         return ((rvi & 0xf0) > (vppr & 0xf0));
3627 }
3628 
3629 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3630                                                      bool nested)
3631 {
3632 #ifdef CONFIG_SMP
3633         int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3634 
3635         if (vcpu->mode == IN_GUEST_MODE) {
3636                 /*
3637                  * The vector of interrupt to be delivered to vcpu had
3638                  * been set in PIR before this function.
3639                  *
3640                  * Following cases will be reached in this block, and
3641                  * we always send a notification event in all cases as
3642                  * explained below.
3643                  *
3644                  * Case 1: vcpu keeps in non-root mode. Sending a
3645                  * notification event posts the interrupt to vcpu.
3646                  *
3647                  * Case 2: vcpu exits to root mode and is still
3648                  * runnable. PIR will be synced to vIRR before the
3649                  * next vcpu entry. Sending a notification event in
3650                  * this case has no effect, as vcpu is not in root
3651                  * mode.
3652                  *
3653                  * Case 3: vcpu exits to root mode and is blocked.
3654                  * vcpu_block() has already synced PIR to vIRR and
3655                  * never blocks vcpu if vIRR is not cleared. Therefore,
3656                  * a blocked vcpu here does not wait for any requested
3657                  * interrupts in PIR, and sending a notification event
3658                  * which has no effect is safe here.
3659                  */
3660 
3661                 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3662                 return true;
3663         }
3664 #endif
3665         return false;
3666 }
3667 
3668 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3669                                                 int vector)
3670 {
3671         struct vcpu_vmx *vmx = to_vmx(vcpu);
3672 
3673         if (is_guest_mode(vcpu) &&
3674             vector == vmx->nested.posted_intr_nv) {
3675                 /*
3676                  * If a posted intr is not recognized by hardware,
3677                  * we will accomplish it in the next vmentry.
3678                  */
3679                 vmx->nested.pi_pending = true;
3680                 kvm_make_request(KVM_REQ_EVENT, vcpu);
3681                 /* the PIR and ON have been set by L1. */
3682                 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3683                         kvm_vcpu_kick(vcpu);
3684                 return 0;
3685         }
3686         return -1;
3687 }
3688 /*
3689  * Send interrupt to vcpu via posted interrupt way.
3690  * 1. If target vcpu is running(non-root mode), send posted interrupt
3691  * notification to vcpu and hardware will sync PIR to vIRR atomically.
3692  * 2. If target vcpu isn't running(root mode), kick it to pick up the
3693  * interrupt from PIR in next vmentry.
3694  */
3695 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3696 {
3697         struct vcpu_vmx *vmx = to_vmx(vcpu);
3698         int r;
3699 
3700         r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3701         if (!r)
3702                 return;
3703 
3704         if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3705                 return;
3706 
3707         /* If a previous notification has sent the IPI, nothing to do.  */
3708         if (pi_test_and_set_on(&vmx->pi_desc))
3709                 return;
3710 
3711         if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
3712                 kvm_vcpu_kick(vcpu);
3713 }
3714 
3715 /*
3716  * Set up the vmcs's constant host-state fields, i.e., host-state fields that
3717  * will not change in the lifetime of the guest.
3718  * Note that host-state that does change is set elsewhere. E.g., host-state
3719  * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
3720  */
3721 void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
3722 {
3723         u32 low32, high32;
3724         unsigned long tmpl;
3725         struct desc_ptr dt;
3726         unsigned long cr0, cr3, cr4;
3727 
3728         cr0 = read_cr0();
3729         WARN_ON(cr0 & X86_CR0_TS);
3730         vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
3731 
3732         /*
3733          * Save the most likely value for this task's CR3 in the VMCS.
3734          * We can't use __get_current_cr3_fast() because we're not atomic.
3735          */
3736         cr3 = __read_cr3();
3737         vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
3738         vmx->loaded_vmcs->host_state.cr3 = cr3;
3739 
3740         /* Save the most likely value for this task's CR4 in the VMCS. */
3741         cr4 = cr4_read_shadow();
3742         vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
3743         vmx->loaded_vmcs->host_state.cr4 = cr4;
3744 
3745         vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
3746 #ifdef CONFIG_X86_64
3747         /*
3748          * Load null selectors, so we can avoid reloading them in
3749          * vmx_prepare_switch_to_host(), in case userspace uses
3750          * the null selectors too (the expected case).
3751          */
3752         vmcs_write16(HOST_DS_SELECTOR, 0);
3753         vmcs_write16(HOST_ES_SELECTOR, 0);
3754 #else
3755         vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3756         vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3757 #endif
3758         vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
3759         vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
3760 
3761         store_idt(&dt);
3762         vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
3763         vmx->host_idt_base = dt.address;
3764 
3765         vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
3766 
3767         rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
3768         vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
3769         rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
3770         vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
3771 
3772         if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
3773                 rdmsr(MSR_IA32_CR_PAT, low32, high32);
3774                 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
3775         }
3776 
3777         if (cpu_has_load_ia32_efer())
3778                 vmcs_write64(HOST_IA32_EFER, host_efer);
3779 }
3780 
3781 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
3782 {
3783         vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
3784         if (enable_ept)
3785                 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
3786         if (is_guest_mode(&vmx->vcpu))
3787                 vmx->vcpu.arch.cr4_guest_owned_bits &=
3788                         ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
3789         vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
3790 }
3791 
3792 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
3793 {
3794         u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
3795 
3796         if (!kvm_vcpu_apicv_active(&vmx->vcpu))
3797                 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
3798 
3799         if (!enable_vnmi)
3800                 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
3801 
3802         /* Enable the preemption timer dynamically */
3803         pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3804         return pin_based_exec_ctrl;
3805 }
3806 
3807 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
3808 {
3809         struct vcpu_vmx *vmx = to_vmx(vcpu);
3810 
3811         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
3812         if (cpu_has_secondary_exec_ctrls()) {
3813                 if (kvm_vcpu_apicv_active(vcpu))
3814                         vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
3815                                       SECONDARY_EXEC_APIC_REGISTER_VIRT |
3816                                       SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3817                 else
3818                         vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
3819                                         SECONDARY_EXEC_APIC_REGISTER_VIRT |
3820                                         SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3821         }
3822 
3823         if (cpu_has_vmx_msr_bitmap())
3824                 vmx_update_msr_bitmap(vcpu);
3825 }
3826 
3827 u32 vmx_exec_control(struct vcpu_vmx *vmx)
3828 {
3829         u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
3830 
3831         if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
3832                 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
3833 
3834         if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
3835                 exec_control &= ~CPU_BASED_TPR_SHADOW;
3836 #ifdef CONFIG_X86_64
3837                 exec_control |= CPU_BASED_CR8_STORE_EXITING |
3838                                 CPU_BASED_CR8_LOAD_EXITING;
3839 #endif
3840         }
3841         if (!enable_ept)
3842                 exec_control |= CPU_BASED_CR3_STORE_EXITING |
3843                                 CPU_BASED_CR3_LOAD_EXITING  |
3844                                 CPU_BASED_INVLPG_EXITING;
3845         if (kvm_mwait_in_guest(vmx->vcpu.kvm))
3846                 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
3847                                 CPU_BASED_MONITOR_EXITING);
3848         if (kvm_hlt_in_guest(vmx->vcpu.kvm))
3849                 exec_control &= ~CPU_BASED_HLT_EXITING;
3850         return exec_control;
3851 }
3852 
3853 
3854 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
3855 {
3856         struct kvm_vcpu *vcpu = &vmx->vcpu;
3857 
3858         u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
3859 
3860         if (pt_mode == PT_MODE_SYSTEM)
3861                 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
3862         if (!cpu_need_virtualize_apic_accesses(vcpu))
3863                 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3864         if (vmx->vpid == 0)
3865                 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
3866         if (!enable_ept) {
3867                 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
3868                 enable_unrestricted_guest = 0;
3869         }
3870         if (!enable_unrestricted_guest)
3871                 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
3872         if (kvm_pause_in_guest(vmx->vcpu.kvm))
3873                 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
3874         if (!kvm_vcpu_apicv_active(vcpu))
3875                 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
3876                                   SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3877         exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
3878 
3879         /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
3880          * in vmx_set_cr4.  */
3881         exec_control &= ~SECONDARY_EXEC_DESC;
3882 
3883         /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
3884            (handle_vmptrld).
3885            We can NOT enable shadow_vmcs here because we don't have yet
3886            a current VMCS12
3887         */
3888         exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
3889 
3890         if (!enable_pml)
3891                 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
3892 
3893         if (vmx_xsaves_supported()) {
3894                 /* Exposing XSAVES only when XSAVE is exposed */
3895                 bool xsaves_enabled =
3896                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
3897                         guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
3898 
3899                 if (!xsaves_enabled)
3900                         exec_control &= ~SECONDARY_EXEC_XSAVES;
3901 
3902                 if (nested) {
3903                         if (xsaves_enabled)
3904                                 vmx->nested.msrs.secondary_ctls_high |=
3905                                         SECONDARY_EXEC_XSAVES;
3906                         else
3907                                 vmx->nested.msrs.secondary_ctls_high &=
3908                                         ~SECONDARY_EXEC_XSAVES;
3909                 }
3910         }
3911 
3912         if (vmx_rdtscp_supported()) {
3913                 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
3914                 if (!rdtscp_enabled)
3915                         exec_control &= ~SECONDARY_EXEC_RDTSCP;
3916 
3917                 if (nested) {
3918                         if (rdtscp_enabled)
3919                                 vmx->nested.msrs.secondary_ctls_high |=
3920                                         SECONDARY_EXEC_RDTSCP;
3921                         else
3922                                 vmx->nested.msrs.secondary_ctls_high &=
3923                                         ~SECONDARY_EXEC_RDTSCP;
3924                 }
3925         }
3926 
3927         if (vmx_invpcid_supported()) {
3928                 /* Exposing INVPCID only when PCID is exposed */
3929                 bool invpcid_enabled =
3930                         guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
3931                         guest_cpuid_has(vcpu, X86_FEATURE_PCID);
3932 
3933                 if (!invpcid_enabled) {
3934                         exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
3935                         guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
3936                 }
3937 
3938                 if (nested) {
3939                         if (invpcid_enabled)
3940                                 vmx->nested.msrs.secondary_ctls_high |=
3941                                         SECONDARY_EXEC_ENABLE_INVPCID;
3942                         else
3943                                 vmx->nested.msrs.secondary_ctls_high &=
3944                                         ~SECONDARY_EXEC_ENABLE_INVPCID;
3945                 }
3946         }
3947 
3948         if (vmx_rdrand_supported()) {
3949                 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
3950                 if (rdrand_enabled)
3951                         exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
3952 
3953                 if (nested) {
3954                         if (rdrand_enabled)
3955                                 vmx->nested.msrs.secondary_ctls_high |=
3956                                         SECONDARY_EXEC_RDRAND_EXITING;
3957                         else
3958                                 vmx->nested.msrs.secondary_ctls_high &=
3959                                         ~SECONDARY_EXEC_RDRAND_EXITING;
3960                 }
3961         }
3962 
3963         if (vmx_rdseed_supported()) {
3964                 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
3965                 if (rdseed_enabled)
3966                         exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
3967 
3968                 if (nested) {
3969                         if (rdseed_enabled)
3970                                 vmx->nested.msrs.secondary_ctls_high |=
3971                                         SECONDARY_EXEC_RDSEED_EXITING;
3972                         else
3973                                 vmx->nested.msrs.secondary_ctls_high &=
3974                                         ~SECONDARY_EXEC_RDSEED_EXITING;
3975                 }
3976         }
3977 
3978         vmx->secondary_exec_control = exec_control;
3979 }
3980 
3981 static void ept_set_mmio_spte_mask(void)
3982 {
3983         /*
3984          * EPT Misconfigurations can be generated if the value of bits 2:0
3985          * of an EPT paging-structure entry is 110b (write/execute).
3986          */
3987         kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
3988                                    VMX_EPT_MISCONFIG_WX_VALUE);
3989 }
3990 
3991 #define VMX_XSS_EXIT_BITMAP 0
3992 
3993 /*
3994  * Sets up the vmcs for emulated real mode.
3995  */
3996 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
3997 {
3998         int i;
3999 
4000         if (nested)
4001                 nested_vmx_vcpu_setup();
4002 
4003         if (cpu_has_vmx_msr_bitmap())
4004                 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4005 
4006         vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4007 
4008         /* Control */
4009         vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
4010         vmx->hv_deadline_tsc = -1;
4011 
4012         vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
4013 
4014         if (cpu_has_secondary_exec_ctrls()) {
4015                 vmx_compute_secondary_exec_control(vmx);
4016                 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
4017                              vmx->secondary_exec_control);
4018         }
4019 
4020         if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4021                 vmcs_write64(EOI_EXIT_BITMAP0, 0);
4022                 vmcs_write64(EOI_EXIT_BITMAP1, 0);
4023                 vmcs_write64(EOI_EXIT_BITMAP2, 0);
4024                 vmcs_write64(EOI_EXIT_BITMAP3, 0);
4025 
4026                 vmcs_write16(GUEST_INTR_STATUS, 0);
4027 
4028                 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4029                 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4030         }
4031 
4032         if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4033                 vmcs_write32(PLE_GAP, ple_gap);
4034                 vmx->ple_window = ple_window;
4035                 vmx->ple_window_dirty = true;
4036         }
4037 
4038         vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4039         vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4040         vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4041 
4042         vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4043         vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4044         vmx_set_constant_host_state(vmx);
4045         vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4046         vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4047 
4048         if (cpu_has_vmx_vmfunc())
4049                 vmcs_write64(VM_FUNCTION_CONTROL, 0);
4050 
4051         vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4052         vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4053         vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4054         vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4055         vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4056 
4057         if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4058                 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4059 
4060         for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
4061                 u32 index = vmx_msr_index[i];
4062                 u32 data_low, data_high;
4063                 int j = vmx->nmsrs;
4064 
4065                 if (rdmsr_safe(index, &data_low, &data_high) < 0)
4066                         continue;
4067                 if (wrmsr_safe(index, data_low, data_high) < 0)
4068                         continue;
4069                 vmx->guest_msrs[j].index = i;
4070                 vmx->guest_msrs[j].data = 0;
4071                 vmx->guest_msrs[j].mask = -1ull;
4072                 ++vmx->nmsrs;
4073         }
4074 
4075         vm_exit_controls_init(vmx, vmx_vmexit_ctrl());
4076 
4077         /* 22.2.1, 20.8.1 */
4078         vm_entry_controls_init(vmx, vmx_vmentry_ctrl());
4079 
4080         vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
4081         vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
4082 
4083         set_cr4_guest_host_mask(vmx);
4084 
4085         if (vmx_xsaves_supported())
4086                 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4087 
4088         if (enable_pml) {
4089                 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4090                 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4091         }
4092 
4093         if (cpu_has_vmx_encls_vmexit())
4094                 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
4095 
4096         if (pt_mode == PT_MODE_HOST_GUEST) {
4097                 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4098                 /* Bit[6~0] are forced to 1, writes are ignored. */
4099                 vmx->pt_desc.guest.output_mask = 0x7F;
4100                 vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4101         }
4102 }
4103 
4104 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4105 {
4106         struct vcpu_vmx *vmx = to_vmx(vcpu);
4107         struct msr_data apic_base_msr;
4108         u64 cr0;
4109 
4110         vmx->rmode.vm86_active = 0;
4111         vmx->spec_ctrl = 0;
4112 
4113         vcpu->arch.microcode_version = 0x100000000ULL;
4114         vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4115         kvm_set_cr8(vcpu, 0);
4116 
4117         if (!init_event) {
4118                 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4119                                      MSR_IA32_APICBASE_ENABLE;
4120                 if (kvm_vcpu_is_reset_bsp(vcpu))
4121                         apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4122                 apic_base_msr.host_initiated = true;
4123                 kvm_set_apic_base(vcpu, &apic_base_msr);
4124         }
4125 
4126         vmx_segment_cache_clear(vmx);
4127 
4128         seg_setup(VCPU_SREG_CS);
4129         vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4130         vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4131 
4132         seg_setup(VCPU_SREG_DS);
4133         seg_setup(VCPU_SREG_ES);
4134         seg_setup(VCPU_SREG_FS);
4135         seg_setup(VCPU_SREG_GS);
4136         seg_setup(VCPU_SREG_SS);
4137 
4138         vmcs_write16(GUEST_TR_SELECTOR, 0);
4139         vmcs_writel(GUEST_TR_BASE, 0);
4140         vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4141         vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4142 
4143         vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4144         vmcs_writel(GUEST_LDTR_BASE, 0);
4145         vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4146         vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4147 
4148         if (!init_event) {
4149                 vmcs_write32(GUEST_SYSENTER_CS, 0);
4150                 vmcs_writel(GUEST_SYSENTER_ESP, 0);
4151                 vmcs_writel(GUEST_SYSENTER_EIP, 0);
4152                 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4153         }
4154 
4155         kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4156         kvm_rip_write(vcpu, 0xfff0);
4157 
4158         vmcs_writel(GUEST_GDTR_BASE, 0);
4159         vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4160 
4161         vmcs_writel(GUEST_IDTR_BASE, 0);
4162         vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4163 
4164         vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4165         vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4166         vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4167         if (kvm_mpx_supported())
4168                 vmcs_write64(GUEST_BNDCFGS, 0);
4169 
4170         setup_msrs(vmx);
4171 
4172         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4173 
4174         if (cpu_has_vmx_tpr_shadow() && !init_event) {
4175                 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4176                 if (cpu_need_tpr_shadow(vcpu))
4177                         vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4178                                      __pa(vcpu->arch.apic->regs));
4179                 vmcs_write32(TPR_THRESHOLD, 0);
4180         }
4181 
4182         kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4183 
4184         if (vmx->vpid != 0)
4185                 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4186 
4187         cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4188         vmx->vcpu.arch.cr0 = cr0;
4189         vmx_set_cr0(vcpu, cr0); /* enter rmode */
4190         vmx_set_cr4(vcpu, 0);
4191         vmx_set_efer(vcpu, 0);
4192 
4193         update_exception_bitmap(vcpu);
4194 
4195         vpid_sync_context(vmx->vpid);
4196         if (init_event)
4197                 vmx_clear_hlt(vcpu);
4198 }
4199 
4200 static void enable_irq_window(struct kvm_vcpu *vcpu)
4201 {
4202         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4203                       CPU_BASED_VIRTUAL_INTR_PENDING);
4204 }
4205 
4206 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4207 {
4208         if (!enable_vnmi ||
4209             vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
4210                 enable_irq_window(vcpu);
4211                 return;
4212         }
4213 
4214         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
4215                       CPU_BASED_VIRTUAL_NMI_PENDING);
4216 }
4217 
4218 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
4219 {
4220         struct vcpu_vmx *vmx = to_vmx(vcpu);
4221         uint32_t intr;
4222         int irq = vcpu->arch.interrupt.nr;
4223 
4224         trace_kvm_inj_virq(irq);
4225 
4226         ++vcpu->stat.irq_injections;
4227         if (vmx->rmode.vm86_active) {
4228                 int inc_eip = 0;
4229                 if (vcpu->arch.interrupt.soft)
4230                         inc_eip = vcpu->arch.event_exit_inst_len;
4231                 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
4232                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4233                 return;
4234         }
4235         intr = irq | INTR_INFO_VALID_MASK;
4236         if (vcpu->arch.interrupt.soft) {
4237                 intr |= INTR_TYPE_SOFT_INTR;
4238                 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
4239                              vmx->vcpu.arch.event_exit_inst_len);
4240         } else
4241                 intr |= INTR_TYPE_EXT_INTR;
4242         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
4243 
4244         vmx_clear_hlt(vcpu);
4245 }
4246 
4247 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
4248 {
4249         struct vcpu_vmx *vmx = to_vmx(vcpu);
4250 
4251         if (!enable_vnmi) {
4252                 /*
4253                  * Tracking the NMI-blocked state in software is built upon
4254                  * finding the next open IRQ window. This, in turn, depends on
4255                  * well-behaving guests: They have to keep IRQs disabled at
4256                  * least as long as the NMI handler runs. Otherwise we may
4257                  * cause NMI nesting, maybe breaking the guest. But as this is
4258                  * highly unlikely, we can live with the residual risk.
4259                  */
4260                 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
4261                 vmx->loaded_vmcs->vnmi_blocked_time = 0;
4262         }
4263 
4264         ++vcpu->stat.nmi_injections;
4265         vmx->loaded_vmcs->nmi_known_unmasked = false;
4266 
4267         if (vmx->rmode.vm86_active) {
4268                 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
4269                         kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4270                 return;
4271         }
4272 
4273         vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
4274                         INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
4275 
4276         vmx_clear_hlt(vcpu);
4277 }
4278 
4279 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
4280 {
4281         struct vcpu_vmx *vmx = to_vmx(vcpu);
4282         bool masked;
4283 
4284         if (!enable_vnmi)
4285                 return vmx->loaded_vmcs->soft_vnmi_blocked;
4286         if (vmx->loaded_vmcs->nmi_known_unmasked)
4287                 return false;
4288         masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
4289         vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4290         return masked;
4291 }
4292 
4293 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4294 {
4295         struct vcpu_vmx *vmx = to_vmx(vcpu);
4296 
4297         if (!enable_vnmi) {
4298                 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
4299                         vmx->loaded_vmcs->soft_vnmi_blocked = masked;
4300                         vmx->loaded_vmcs->vnmi_blocked_time = 0;
4301                 }
4302         } else {
4303                 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
4304                 if (masked)
4305                         vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
4306                                       GUEST_INTR_STATE_NMI);
4307                 else
4308                         vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
4309                                         GUEST_INTR_STATE_NMI);
4310         }
4311 }
4312 
4313 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
4314 {
4315         if (to_vmx(vcpu)->nested.nested_run_pending)
4316                 return 0;
4317 
4318         if (!enable_vnmi &&
4319             to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
4320                 return 0;
4321 
4322         return  !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4323                   (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
4324                    | GUEST_INTR_STATE_NMI));
4325 }
4326 
4327 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
4328 {
4329         return (!to_vmx(vcpu)->nested.nested_run_pending &&
4330                 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
4331                 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
4332                         (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
4333 }
4334 
4335 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
4336 {
4337         int ret;
4338 
4339         if (enable_unrestricted_guest)
4340                 return 0;
4341 
4342         ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
4343                                     PAGE_SIZE * 3);
4344         if (ret)
4345                 return ret;
4346         to_kvm_vmx(kvm)->tss_addr = addr;
4347         return init_rmode_tss(kvm);
4348 }
4349 
4350 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
4351 {
4352         to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
4353         return 0;
4354 }
4355 
4356 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
4357 {
4358         switch (vec) {
4359         case BP_VECTOR:
4360                 /*
4361                  * Update instruction length as we may reinject the exception
4362                  * from user space while in guest debugging mode.
4363                  */
4364                 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
4365                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4366                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
4367                         return false;
4368                 /* fall through */
4369         case DB_VECTOR:
4370                 if (vcpu->guest_debug &
4371                         (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
4372                         return false;
4373                 /* fall through */
4374         case DE_VECTOR:
4375         case OF_VECTOR:
4376         case BR_VECTOR:
4377         case UD_VECTOR:
4378         case DF_VECTOR:
4379         case SS_VECTOR:
4380         case GP_VECTOR:
4381         case MF_VECTOR:
4382                 return true;
4383         break;
4384         }
4385         return false;
4386 }
4387 
4388 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
4389                                   int vec, u32 err_code)
4390 {
4391         /*
4392          * Instruction with address size override prefix opcode 0x67
4393          * Cause the #SS fault with 0 error code in VM86 mode.
4394          */
4395         if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
4396                 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
4397                         if (vcpu->arch.halt_request) {
4398                                 vcpu->arch.halt_request = 0;
4399                                 return kvm_vcpu_halt(vcpu);
4400                         }
4401                         return 1;
4402                 }
4403                 return 0;
4404         }
4405 
4406         /*
4407          * Forward all other exceptions that are valid in real mode.
4408          * FIXME: Breaks guest debugging in real mode, needs to be fixed with
4409          *        the required debugging infrastructure rework.
4410          */
4411         kvm_queue_exception(vcpu, vec);
4412         return 1;
4413 }
4414 
4415 /*
4416  * Trigger machine check on the host. We assume all the MSRs are already set up
4417  * by the CPU and that we still run on the same CPU as the MCE occurred on.
4418  * We pass a fake environment to the machine check handler because we want
4419  * the guest to be always treated like user space, no matter what context
4420  * it used internally.
4421  */
4422 static void kvm_machine_check(void)
4423 {
4424 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
4425         struct pt_regs regs = {
4426                 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
4427                 .flags = X86_EFLAGS_IF,
4428         };
4429 
4430         do_machine_check(&regs, 0);
4431 #endif
4432 }
4433 
4434 static int handle_machine_check(struct kvm_vcpu *vcpu)
4435 {
4436         /* already handled by vcpu_run */
4437         return 1;
4438 }
4439 
4440 static int handle_exception(struct kvm_vcpu *vcpu)
4441 {
4442         struct vcpu_vmx *vmx = to_vmx(vcpu);
4443         struct kvm_run *kvm_run = vcpu->run;
4444         u32 intr_info, ex_no, error_code;
4445         unsigned long cr2, rip, dr6;
4446         u32 vect_info;
4447         enum emulation_result er;
4448 
4449         vect_info = vmx->idt_vectoring_info;
4450         intr_info = vmx->exit_intr_info;
4451 
4452         if (is_machine_check(intr_info))
4453                 return handle_machine_check(vcpu);
4454 
4455         if (is_nmi(intr_info))
4456                 return 1;  /* already handled by vmx_vcpu_run() */
4457 
4458         if (is_invalid_opcode(intr_info))
4459                 return handle_ud(vcpu);
4460 
4461         error_code = 0;
4462         if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
4463                 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
4464 
4465         if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
4466                 WARN_ON_ONCE(!enable_vmware_backdoor);
4467                 er = kvm_emulate_instruction(vcpu,
4468                         EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
4469                 if (er == EMULATE_USER_EXIT)
4470                         return 0;
4471                 else if (er != EMULATE_DONE)
4472                         kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
4473                 return 1;
4474         }
4475 
4476         /*
4477          * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
4478          * MMIO, it is better to report an internal error.
4479          * See the comments in vmx_handle_exit.
4480          */
4481         if ((vect_info & VECTORING_INFO_VALID_MASK) &&
4482             !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
4483                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4484                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
4485                 vcpu->run->internal.ndata = 3;
4486                 vcpu->run->internal.data[0] = vect_info;
4487                 vcpu->run->internal.data[1] = intr_info;
4488                 vcpu->run->internal.data[2] = error_code;
4489                 return 0;
4490         }
4491 
4492         if (is_page_fault(intr_info)) {
4493                 cr2 = vmcs_readl(EXIT_QUALIFICATION);
4494                 /* EPT won't cause page fault directly */
4495                 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
4496                 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
4497         }
4498 
4499         ex_no = intr_info & INTR_INFO_VECTOR_MASK;
4500 
4501         if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
4502                 return handle_rmode_exception(vcpu, ex_no, error_code);
4503 
4504         switch (ex_no) {
4505         case AC_VECTOR:
4506                 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
4507                 return 1;
4508         case DB_VECTOR:
4509                 dr6 = vmcs_readl(EXIT_QUALIFICATION);
4510                 if (!(vcpu->guest_debug &
4511                       (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
4512                         vcpu->arch.dr6 &= ~15;
4513                         vcpu->arch.dr6 |= dr6 | DR6_RTM;
4514                         if (is_icebp(intr_info))
4515                                 skip_emulated_instruction(vcpu);
4516 
4517                         kvm_queue_exception(vcpu, DB_VECTOR);
4518                         return 1;
4519                 }
4520                 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
4521                 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
4522                 /* fall through */
4523         case BP_VECTOR:
4524                 /*
4525                  * Update instruction length as we may reinject #BP from
4526                  * user space while in guest debugging mode. Reading it for
4527                  * #DB as well causes no harm, it is not used in that case.
4528                  */
4529                 vmx->vcpu.arch.event_exit_inst_len =
4530                         vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
4531                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
4532                 rip = kvm_rip_read(vcpu);
4533                 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
4534                 kvm_run->debug.arch.exception = ex_no;
4535                 break;
4536         default:
4537                 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
4538                 kvm_run->ex.exception = ex_no;
4539                 kvm_run->ex.error_code = error_code;
4540                 break;
4541         }
4542         return 0;
4543 }
4544 
4545 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
4546 {
4547         ++vcpu->stat.irq_exits;
4548         return 1;
4549 }
4550 
4551 static int handle_triple_fault(struct kvm_vcpu *vcpu)
4552 {
4553         vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
4554         vcpu->mmio_needed = 0;
4555         return 0;
4556 }
4557 
4558 static int handle_io(struct kvm_vcpu *vcpu)
4559 {
4560         unsigned long exit_qualification;
4561         int size, in, string;
4562         unsigned port;
4563 
4564         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4565         string = (exit_qualification & 16) != 0;
4566 
4567         ++vcpu->stat.io_exits;
4568 
4569         if (string)
4570                 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4571 
4572         port = exit_qualification >> 16;
4573         size = (exit_qualification & 7) + 1;
4574         in = (exit_qualification & 8) != 0;
4575 
4576         return kvm_fast_pio(vcpu, size, port, in);
4577 }
4578 
4579 static void
4580 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4581 {
4582         /*
4583          * Patch in the VMCALL instruction:
4584          */
4585         hypercall[0] = 0x0f;
4586         hypercall[1] = 0x01;
4587         hypercall[2] = 0xc1;
4588 }
4589 
4590 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
4591 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
4592 {
4593         if (is_guest_mode(vcpu)) {
4594                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4595                 unsigned long orig_val = val;
4596 
4597                 /*
4598                  * We get here when L2 changed cr0 in a way that did not change
4599                  * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
4600                  * but did change L0 shadowed bits. So we first calculate the
4601                  * effective cr0 value that L1 would like to write into the
4602                  * hardware. It consists of the L2-owned bits from the new
4603                  * value combined with the L1-owned bits from L1's guest_cr0.
4604                  */
4605                 val = (val & ~vmcs12->cr0_guest_host_mask) |
4606                         (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
4607 
4608                 if (!nested_guest_cr0_valid(vcpu, val))
4609                         return 1;
4610 
4611                 if (kvm_set_cr0(vcpu, val))
4612                         return 1;
4613                 vmcs_writel(CR0_READ_SHADOW, orig_val);
4614                 return 0;
4615         } else {
4616                 if (to_vmx(vcpu)->nested.vmxon &&
4617                     !nested_host_cr0_valid(vcpu, val))
4618                         return 1;
4619 
4620                 return kvm_set_cr0(vcpu, val);
4621         }
4622 }
4623 
4624 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
4625 {
4626         if (is_guest_mode(vcpu)) {
4627                 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4628                 unsigned long orig_val = val;
4629 
4630                 /* analogously to handle_set_cr0 */
4631                 val = (val & ~vmcs12->cr4_guest_host_mask) |
4632                         (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
4633                 if (kvm_set_cr4(vcpu, val))
4634                         return 1;
4635                 vmcs_writel(CR4_READ_SHADOW, orig_val);
4636                 return 0;
4637         } else
4638                 return kvm_set_cr4(vcpu, val);
4639 }
4640 
4641 static int handle_desc(struct kvm_vcpu *vcpu)
4642 {
4643         WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
4644         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4645 }
4646 
4647 static int handle_cr(struct kvm_vcpu *vcpu)
4648 {
4649         unsigned long exit_qualification, val;
4650         int cr;
4651         int reg;
4652         int err;
4653         int ret;
4654 
4655         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4656         cr = exit_qualification & 15;
4657         reg = (exit_qualification >> 8) & 15;
4658         switch ((exit_qualification >> 4) & 3) {
4659         case 0: /* mov to cr */
4660                 val = kvm_register_readl(vcpu, reg);
4661                 trace_kvm_cr_write(cr, val);
4662                 switch (cr) {
4663                 case 0:
4664                         err = handle_set_cr0(vcpu, val);
4665                         return kvm_complete_insn_gp(vcpu, err);
4666                 case 3:
4667                         WARN_ON_ONCE(enable_unrestricted_guest);
4668                         err = kvm_set_cr3(vcpu, val);
4669                         return kvm_complete_insn_gp(vcpu, err);
4670                 case 4:
4671                         err = handle_set_cr4(vcpu, val);
4672                         return kvm_complete_insn_gp(vcpu, err);
4673                 case 8: {
4674                                 u8 cr8_prev = kvm_get_cr8(vcpu);
4675                                 u8 cr8 = (u8)val;
4676                                 err = kvm_set_cr8(vcpu, cr8);
4677                                 ret = kvm_complete_insn_gp(vcpu, err);
4678                                 if (lapic_in_kernel(vcpu))
4679                                         return ret;
4680                                 if (cr8_prev <= cr8)
4681                                         return ret;
4682                                 /*
4683                                  * TODO: we might be squashing a
4684                                  * KVM_GUESTDBG_SINGLESTEP-triggered
4685                                  * KVM_EXIT_DEBUG here.
4686                                  */
4687                                 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
4688                                 return 0;
4689                         }
4690                 }
4691                 break;
4692         case 2: /* clts */
4693                 WARN_ONCE(1, "Guest should always own CR0.TS");
4694                 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
4695                 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
4696                 return kvm_skip_emulated_instruction(vcpu);
4697         case 1: /*mov from cr*/
4698                 switch (cr) {
4699                 case 3:
4700                         WARN_ON_ONCE(enable_unrestricted_guest);
4701                         val = kvm_read_cr3(vcpu);
4702                         kvm_register_write(vcpu, reg, val);
4703                         trace_kvm_cr_read(cr, val);
4704                         return kvm_skip_emulated_instruction(vcpu);
4705                 case 8:
4706                         val = kvm_get_cr8(vcpu);
4707                         kvm_register_write(vcpu, reg, val);
4708                         trace_kvm_cr_read(cr, val);
4709                         return kvm_skip_emulated_instruction(vcpu);
4710                 }
4711                 break;
4712         case 3: /* lmsw */
4713                 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
4714                 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
4715                 kvm_lmsw(vcpu, val);
4716 
4717                 return kvm_skip_emulated_instruction(vcpu);
4718         default:
4719                 break;
4720         }
4721         vcpu->run->exit_reason = 0;
4722         vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
4723                (int)(exit_qualification >> 4) & 3, cr);
4724         return 0;
4725 }
4726 
4727 static int handle_dr(struct kvm_vcpu *vcpu)
4728 {
4729         unsigned long exit_qualification;
4730         int dr, dr7, reg;
4731 
4732         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4733         dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
4734 
4735         /* First, if DR does not exist, trigger UD */
4736         if (!kvm_require_dr(vcpu, dr))
4737                 return 1;
4738 
4739         /* Do not handle if the CPL > 0, will trigger GP on re-entry */
4740         if (!kvm_require_cpl(vcpu, 0))
4741                 return 1;
4742         dr7 = vmcs_readl(GUEST_DR7);
4743         if (dr7 & DR7_GD) {
4744                 /*
4745                  * As the vm-exit takes precedence over the debug trap, we
4746                  * need to emulate the latter, either for the host or the
4747                  * guest debugging itself.
4748                  */
4749                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
4750                         vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
4751                         vcpu->run->debug.arch.dr7 = dr7;
4752                         vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
4753                         vcpu->run->debug.arch.exception = DB_VECTOR;
4754                         vcpu->run->exit_reason = KVM_EXIT_DEBUG;
4755                         return 0;
4756                 } else {
4757                         vcpu->arch.dr6 &= ~15;
4758                         vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
4759                         kvm_queue_exception(vcpu, DB_VECTOR);
4760                         return 1;
4761                 }
4762         }
4763 
4764         if (vcpu->guest_debug == 0) {
4765                 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4766                                 CPU_BASED_MOV_DR_EXITING);
4767 
4768                 /*
4769                  * No more DR vmexits; force a reload of the debug registers
4770                  * and reenter on this instruction.  The next vmexit will
4771                  * retrieve the full state of the debug registers.
4772                  */
4773                 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4774                 return 1;
4775         }
4776 
4777         reg = DEBUG_REG_ACCESS_REG(exit_qualification);
4778         if (exit_qualification & TYPE_MOV_FROM_DR) {
4779                 unsigned long val;
4780 
4781                 if (kvm_get_dr(vcpu, dr, &val))
4782                         return 1;
4783                 kvm_register_write(vcpu, reg, val);
4784         } else
4785                 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
4786                         return 1;
4787 
4788         return kvm_skip_emulated_instruction(vcpu);
4789 }
4790 
4791 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
4792 {
4793         return vcpu->arch.dr6;
4794 }
4795 
4796 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
4797 {
4798 }
4799 
4800 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
4801 {
4802         get_debugreg(vcpu->arch.db[0], 0);
4803         get_debugreg(vcpu->arch.db[1], 1);
4804         get_debugreg(vcpu->arch.db[2], 2);
4805         get_debugreg(vcpu->arch.db[3], 3);
4806         get_debugreg(vcpu->arch.dr6, 6);
4807         vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
4808 
4809         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
4810         vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
4811 }
4812 
4813 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
4814 {
4815         vmcs_writel(GUEST_DR7, val);
4816 }
4817 
4818 static int handle_cpuid(struct kvm_vcpu *vcpu)
4819 {
4820         return kvm_emulate_cpuid(vcpu);
4821 }
4822 
4823 static int handle_rdmsr(struct kvm_vcpu *vcpu)
4824 {
4825         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4826         struct msr_data msr_info;
4827 
4828         msr_info.index = ecx;
4829         msr_info.host_initiated = false;
4830         if (vmx_get_msr(vcpu, &msr_info)) {
4831                 trace_kvm_msr_read_ex(ecx);
4832                 kvm_inject_gp(vcpu, 0);
4833                 return 1;
4834         }
4835 
4836         trace_kvm_msr_read(ecx, msr_info.data);
4837 
4838         /* FIXME: handling of bits 32:63 of rax, rdx */
4839         vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
4840         vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
4841         return kvm_skip_emulated_instruction(vcpu);
4842 }
4843 
4844 static int handle_wrmsr(struct kvm_vcpu *vcpu)
4845 {
4846         struct msr_data msr;
4847         u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
4848         u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
4849                 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
4850 
4851         msr.data = data;
4852         msr.index = ecx;
4853         msr.host_initiated = false;
4854         if (kvm_set_msr(vcpu, &msr) != 0) {
4855                 trace_kvm_msr_write_ex(ecx, data);
4856                 kvm_inject_gp(vcpu, 0);
4857                 return 1;
4858         }
4859 
4860         trace_kvm_msr_write(ecx, data);
4861         return kvm_skip_emulated_instruction(vcpu);
4862 }
4863 
4864 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
4865 {
4866         kvm_apic_update_ppr(vcpu);
4867         return 1;
4868 }
4869 
4870 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
4871 {
4872         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
4873                         CPU_BASED_VIRTUAL_INTR_PENDING);
4874 
4875         kvm_make_request(KVM_REQ_EVENT, vcpu);
4876 
4877         ++vcpu->stat.irq_window_exits;
4878         return 1;
4879 }
4880 
4881 static int handle_halt(struct kvm_vcpu *vcpu)
4882 {
4883         return kvm_emulate_halt(vcpu);
4884 }
4885 
4886 static int handle_vmcall(struct kvm_vcpu *vcpu)
4887 {
4888         return kvm_emulate_hypercall(vcpu);
4889 }
4890 
4891 static int handle_invd(struct kvm_vcpu *vcpu)
4892 {
4893         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4894 }
4895 
4896 static int handle_invlpg(struct kvm_vcpu *vcpu)
4897 {
4898         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4899 
4900         kvm_mmu_invlpg(vcpu, exit_qualification);
4901         return kvm_skip_emulated_instruction(vcpu);
4902 }
4903 
4904 static int handle_rdpmc(struct kvm_vcpu *vcpu)
4905 {
4906         int err;
4907 
4908         err = kvm_rdpmc(vcpu);
4909         return kvm_complete_insn_gp(vcpu, err);
4910 }
4911 
4912 static int handle_wbinvd(struct kvm_vcpu *vcpu)
4913 {
4914         return kvm_emulate_wbinvd(vcpu);
4915 }
4916 
4917 static int handle_xsetbv(struct kvm_vcpu *vcpu)
4918 {
4919         u64 new_bv = kvm_read_edx_eax(vcpu);
4920         u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
4921 
4922         if (kvm_set_xcr(vcpu, index, new_bv) == 0)
4923                 return kvm_skip_emulated_instruction(vcpu);
4924         return 1;
4925 }
4926 
4927 static int handle_xsaves(struct kvm_vcpu *vcpu)
4928 {
4929         kvm_skip_emulated_instruction(vcpu);
4930         WARN(1, "this should never happen\n");
4931         return 1;
4932 }
4933 
4934 static int handle_xrstors(struct kvm_vcpu *vcpu)
4935 {
4936         kvm_skip_emulated_instruction(vcpu);
4937         WARN(1, "this should never happen\n");
4938         return 1;
4939 }
4940 
4941 static int handle_apic_access(struct kvm_vcpu *vcpu)
4942 {
4943         if (likely(fasteoi)) {
4944                 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4945                 int access_type, offset;
4946 
4947                 access_type = exit_qualification & APIC_ACCESS_TYPE;
4948                 offset = exit_qualification & APIC_ACCESS_OFFSET;
4949                 /*
4950                  * Sane guest uses MOV to write EOI, with written value
4951                  * not cared. So make a short-circuit here by avoiding
4952                  * heavy instruction emulation.
4953                  */
4954                 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
4955                     (offset == APIC_EOI)) {
4956                         kvm_lapic_set_eoi(vcpu);
4957                         return kvm_skip_emulated_instruction(vcpu);
4958                 }
4959         }
4960         return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
4961 }
4962 
4963 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
4964 {
4965         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4966         int vector = exit_qualification & 0xff;
4967 
4968         /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
4969         kvm_apic_set_eoi_accelerated(vcpu, vector);
4970         return 1;
4971 }
4972 
4973 static int handle_apic_write(struct kvm_vcpu *vcpu)
4974 {
4975         unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4976         u32 offset = exit_qualification & 0xfff;
4977 
4978         /* APIC-write VM exit is trap-like and thus no need to adjust IP */
4979         kvm_apic_write_nodecode(vcpu, offset);
4980         return 1;
4981 }
4982 
4983 static int handle_task_switch(struct kvm_vcpu *vcpu)
4984 {
4985         struct vcpu_vmx *vmx = to_vmx(vcpu);
4986         unsigned long exit_qualification;
4987         bool has_error_code = false;
4988         u32 error_code = 0;
4989         u16 tss_selector;
4990         int reason, type, idt_v, idt_index;
4991 
4992         idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
4993         idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
4994         type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
4995 
4996         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4997 
4998         reason = (u32)exit_qualification >> 30;
4999         if (reason == TASK_SWITCH_GATE && idt_v) {
5000                 switch (type) {
5001                 case INTR_TYPE_NMI_INTR:
5002                         vcpu->arch.nmi_injected = false;
5003                         vmx_set_nmi_mask(vcpu, true);
5004                         break;
5005                 case INTR_TYPE_EXT_INTR:
5006                 case INTR_TYPE_SOFT_INTR:
5007                         kvm_clear_interrupt_queue(vcpu);
5008                         break;
5009                 case INTR_TYPE_HARD_EXCEPTION:
5010                         if (vmx->idt_vectoring_info &
5011                             VECTORING_INFO_DELIVER_CODE_MASK) {
5012                                 has_error_code = true;
5013                                 error_code =
5014                                         vmcs_read32(IDT_VECTORING_ERROR_CODE);
5015                         }
5016                         /* fall through */
5017                 case INTR_TYPE_SOFT_EXCEPTION:
5018                         kvm_clear_exception_queue(vcpu);
5019                         break;
5020                 default:
5021                         break;
5022                 }
5023         }
5024         tss_selector = exit_qualification;
5025 
5026         if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
5027                        type != INTR_TYPE_EXT_INTR &&
5028                        type != INTR_TYPE_NMI_INTR))
5029                 skip_emulated_instruction(vcpu);
5030 
5031         if (kvm_task_switch(vcpu, tss_selector,
5032                             type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
5033                             has_error_code, error_code) == EMULATE_FAIL) {
5034                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5035                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5036                 vcpu->run->internal.ndata = 0;
5037                 return 0;
5038         }
5039 
5040         /*
5041          * TODO: What about debug traps on tss switch?
5042          *       Are we supposed to inject them and update dr6?
5043          */
5044 
5045         return 1;
5046 }
5047 
5048 static int handle_ept_violation(struct kvm_vcpu *vcpu)
5049 {
5050         unsigned long exit_qualification;
5051         gpa_t gpa;
5052         u64 error_code;
5053 
5054         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5055 
5056         /*
5057          * EPT violation happened while executing iret from NMI,
5058          * "blocked by NMI" bit has to be set before next VM entry.
5059          * There are errata that may cause this bit to not be set:
5060          * AAK134, BY25.
5061          */
5062         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5063                         enable_vnmi &&
5064                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5065                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
5066 
5067         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5068         trace_kvm_page_fault(gpa, exit_qualification);
5069 
5070         /* Is it a read fault? */
5071         error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
5072                      ? PFERR_USER_MASK : 0;
5073         /* Is it a write fault? */
5074         error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
5075                       ? PFERR_WRITE_MASK : 0;
5076         /* Is it a fetch fault? */
5077         error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
5078                       ? PFERR_FETCH_MASK : 0;
5079         /* ept page table entry is present? */
5080         error_code |= (exit_qualification &
5081                        (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
5082                         EPT_VIOLATION_EXECUTABLE))
5083                       ? PFERR_PRESENT_MASK : 0;
5084 
5085         error_code |= (exit_qualification & 0x100) != 0 ?
5086                PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
5087 
5088         vcpu->arch.exit_qualification = exit_qualification;
5089         return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
5090 }
5091 
5092 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
5093 {
5094         gpa_t gpa;
5095 
5096         /*
5097          * A nested guest cannot optimize MMIO vmexits, because we have an
5098          * nGPA here instead of the required GPA.
5099          */
5100         gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5101         if (!is_guest_mode(vcpu) &&
5102             !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
5103                 trace_kvm_fast_mmio(gpa);
5104                 /*
5105                  * Doing kvm_skip_emulated_instruction() depends on undefined
5106                  * behavior: Intel's manual doesn't mandate
5107                  * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
5108                  * occurs and while on real hardware it was observed to be set,
5109                  * other hypervisors (namely Hyper-V) don't set it, we end up
5110                  * advancing IP with some random value. Disable fast mmio when
5111                  * running nested and keep it for real hardware in hope that
5112                  * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
5113                  */
5114                 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
5115                         return kvm_skip_emulated_instruction(vcpu);
5116                 else
5117                         return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
5118                                                                 EMULATE_DONE;
5119         }
5120 
5121         return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
5122 }
5123 
5124 static int handle_nmi_window(struct kvm_vcpu *vcpu)
5125 {
5126         WARN_ON_ONCE(!enable_vnmi);
5127         vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
5128                         CPU_BASED_VIRTUAL_NMI_PENDING);
5129         ++vcpu->stat.nmi_window_exits;
5130         kvm_make_request(KVM_REQ_EVENT, vcpu);
5131 
5132         return 1;
5133 }
5134 
5135 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
5136 {
5137         struct vcpu_vmx *vmx = to_vmx(vcpu);
5138         enum emulation_result err = EMULATE_DONE;
5139         int ret = 1;
5140         u32 cpu_exec_ctrl;
5141         bool intr_window_requested;
5142         unsigned count = 130;
5143 
5144         /*
5145          * We should never reach the point where we are emulating L2
5146          * due to invalid guest state as that means we incorrectly
5147          * allowed a nested VMEntry with an invalid vmcs12.
5148          */
5149         WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
5150 
5151         cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5152         intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
5153 
5154         while (vmx->emulation_required && count-- != 0) {
5155                 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
5156                         return handle_interrupt_window(&vmx->vcpu);
5157 
5158                 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
5159                         return 1;
5160 
5161                 err = kvm_emulate_instruction(vcpu, 0);
5162 
5163                 if (err == EMULATE_USER_EXIT) {
5164                         ++vcpu->stat.mmio_exits;
5165                         ret = 0;
5166                         goto out;
5167                 }
5168 
5169                 if (err != EMULATE_DONE)
5170                         goto emulation_error;
5171 
5172                 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
5173                     vcpu->arch.exception.pending)
5174                         goto emulation_error;
5175 
5176                 if (vcpu->arch.halt_request) {
5177                         vcpu->arch.halt_request = 0;
5178                         ret = kvm_vcpu_halt(vcpu);
5179                         goto out;
5180                 }
5181 
5182                 if (signal_pending(current))
5183                         goto out;
5184                 if (need_resched())
5185                         schedule();
5186         }
5187 
5188 out:
5189         return ret;
5190 
5191 emulation_error:
5192         vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5193         vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
5194         vcpu->run->internal.ndata = 0;
5195         return 0;
5196 }
5197 
5198 static void grow_ple_window(struct kvm_vcpu *vcpu)
5199 {
5200         struct vcpu_vmx *vmx = to_vmx(vcpu);
5201         int old = vmx->ple_window;
5202 
5203         vmx->ple_window = __grow_ple_window(old, ple_window,
5204                                             ple_window_grow,
5205                                             ple_window_max);
5206 
5207         if (vmx->ple_window != old)
5208                 vmx->ple_window_dirty = true;
5209 
5210         trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
5211 }
5212 
5213 static void shrink_ple_window(struct kvm_vcpu *vcpu)
5214 {
5215         struct vcpu_vmx *vmx = to_vmx(vcpu);
5216         int old = vmx->ple_window;
5217 
5218         vmx->ple_window = __shrink_ple_window(old, ple_window,
5219                                               ple_window_shrink,
5220                                               ple_window);
5221 
5222         if (vmx->ple_window != old)
5223                 vmx->ple_window_dirty = true;
5224 
5225         trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
5226 }
5227 
5228 /*
5229  * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
5230  */
5231 static void wakeup_handler(void)
5232 {
5233         struct kvm_vcpu *vcpu;
5234         int cpu = smp_processor_id();
5235 
5236         spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5237         list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
5238                         blocked_vcpu_list) {
5239                 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
5240 
5241                 if (pi_test_on(pi_desc) == 1)
5242                         kvm_vcpu_kick(vcpu);
5243         }
5244         spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
5245 }
5246 
5247 static void vmx_enable_tdp(void)
5248 {
5249         kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
5250                 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
5251                 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
5252                 0ull, VMX_EPT_EXECUTABLE_MASK,
5253                 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
5254                 VMX_EPT_RWX_MASK, 0ull);
5255 
5256         ept_set_mmio_spte_mask();
5257         kvm_enable_tdp();
5258 }
5259 
5260 /*
5261  * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
5262  * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
5263  */
5264 static int handle_pause(struct kvm_vcpu *vcpu)
5265 {
5266         if (!kvm_pause_in_guest(vcpu->kvm))
5267                 grow_ple_window(vcpu);
5268 
5269         /*
5270          * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
5271          * VM-execution control is ignored if CPL > 0. OTOH, KVM
5272          * never set PAUSE_EXITING and just set PLE if supported,
5273          * so the vcpu must be CPL=0 if it gets a PAUSE exit.
5274          */
5275         kvm_vcpu_on_spin(vcpu, true);
5276         return kvm_skip_emulated_instruction(vcpu);
5277 }
5278 
5279 static int handle_nop(struct kvm_vcpu *vcpu)
5280 {
5281         return kvm_skip_emulated_instruction(vcpu);
5282 }
5283 
5284 static int handle_mwait(struct kvm_vcpu *vcpu)
5285 {
5286         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
5287         return handle_nop(vcpu);
5288 }
5289 
5290 static int handle_invalid_op(struct kvm_vcpu *vcpu)
5291 {
5292         kvm_queue_exception(vcpu, UD_VECTOR);
5293         return 1;
5294 }
5295 
5296 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
5297 {
5298         return 1;
5299 }
5300 
5301 static int handle_monitor(struct kvm_vcpu *vcpu)
5302 {
5303         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
5304         return handle_nop(vcpu);
5305 }
5306 
5307 static int handle_invpcid(struct kvm_vcpu *vcpu)
5308 {
5309         u32 vmx_instruction_info;
5310         unsigned long type;
5311         bool pcid_enabled;
5312         gva_t gva;
5313         struct x86_exception e;
5314         unsigned i;
5315         unsigned long roots_to_free = 0;
5316         struct {
5317                 u64 pcid;
5318                 u64 gla;
5319         } operand;
5320 
5321         if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
5322                 kvm_queue_exception(vcpu, UD_VECTOR);
5323                 return 1;
5324         }
5325 
5326         vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
5327         type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
5328 
5329         if (type > 3) {
5330                 kvm_inject_gp(vcpu, 0);
5331                 return 1;
5332         }
5333 
5334         /* According to the Intel instruction reference, the memory operand
5335          * is read even if it isn't needed (e.g., for type==all)
5336          */
5337         if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
5338                                 vmx_instruction_info, false, &gva))
5339                 return 1;
5340 
5341         if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
5342                 kvm_inject_page_fault(vcpu, &e);
5343                 return 1;
5344         }
5345 
5346         if (operand.pcid >> 12 != 0) {
5347                 kvm_inject_gp(vcpu, 0);
5348                 return 1;
5349         }
5350 
5351         pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
5352 
5353         switch (type) {
5354         case INVPCID_TYPE_INDIV_ADDR:
5355                 if ((!pcid_enabled && (operand.pcid != 0)) ||
5356                     is_noncanonical_address(operand.gla, vcpu)) {
5357                         kvm_inject_gp(vcpu, 0);
5358                         return 1;
5359                 }
5360                 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
5361                 return kvm_skip_emulated_instruction(vcpu);
5362 
5363         case INVPCID_TYPE_SINGLE_CTXT:
5364                 if (!pcid_enabled && (operand.pcid != 0)) {
5365                         kvm_inject_gp(vcpu, 0);
5366                         return 1;
5367                 }
5368 
5369                 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
5370                         kvm_mmu_sync_roots(vcpu);
5371                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5372                 }
5373 
5374                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5375                         if (kvm_get_pcid(vcpu, vcpu->arch.mmu->prev_roots[i].cr3)
5376                             == operand.pcid)
5377                                 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5378 
5379                 kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, roots_to_free);
5380                 /*
5381                  * If neither the current cr3 nor any of the prev_roots use the
5382                  * given PCID, then nothing needs to be done here because a
5383                  * resync will happen anyway before switching to any other CR3.
5384                  */
5385 
5386                 return kvm_skip_emulated_instruction(vcpu);
5387 
5388         case INVPCID_TYPE_ALL_NON_GLOBAL:
5389                 /*
5390                  * Currently, KVM doesn't mark global entries in the shadow
5391                  * page tables, so a non-global flush just degenerates to a
5392                  * global flush. If needed, we could optimize this later by
5393                  * keeping track of global entries in shadow page tables.
5394                  */
5395 
5396                 /* fall-through */
5397         case INVPCID_TYPE_ALL_INCL_GLOBAL:
5398                 kvm_mmu_unload(vcpu);
5399                 return kvm_skip_emulated_instruction(vcpu);
5400 
5401         default:
5402                 BUG(); /* We have already checked above that type <= 3 */
5403         }
5404 }
5405 
5406 static int handle_pml_full(struct kvm_vcpu *vcpu)
5407 {
5408         unsigned long exit_qualification;
5409 
5410         trace_kvm_pml_full(vcpu->vcpu_id);
5411 
5412         exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5413 
5414         /*
5415          * PML buffer FULL happened while executing iret from NMI,
5416          * "blocked by NMI" bit has to be set before next VM entry.
5417          */
5418         if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
5419                         enable_vnmi &&
5420                         (exit_qualification & INTR_INFO_UNBLOCK_NMI))
5421                 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5422                                 GUEST_INTR_STATE_NMI);
5423 
5424         /*
5425          * PML buffer already flushed at beginning of VMEXIT. Nothing to do
5426          * here.., and there's no userspace involvement needed for PML.
5427          */
5428         return 1;
5429 }
5430 
5431 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
5432 {
5433         if (!to_vmx(vcpu)->req_immediate_exit)
5434                 kvm_lapic_expired_hv_timer(vcpu);
5435         return 1;
5436 }
5437 
5438 /*
5439  * When nested=0, all VMX instruction VM Exits filter here.  The handlers
5440  * are overwritten by nested_vmx_setup() when nested=1.
5441  */
5442 static int handle_vmx_instruction(struct kvm_vcpu *vcpu)
5443 {
5444         kvm_queue_exception(vcpu, UD_VECTOR);
5445         return 1;
5446 }
5447 
5448 static int handle_encls(struct kvm_vcpu *vcpu)
5449 {
5450         /*
5451          * SGX virtualization is not yet supported.  There is no software
5452          * enable bit for SGX, so we have to trap ENCLS and inject a #UD
5453          * to prevent the guest from executing ENCLS.
5454          */
5455         kvm_queue_exception(vcpu, UD_VECTOR);
5456         return 1;
5457 }
5458 
5459 /*
5460  * The exit handlers return 1 if the exit was handled fully and guest execution
5461  * may resume.  Otherwise they set the kvm_run parameter to indicate what needs
5462  * to be done to userspace and return 0.
5463  */
5464 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
5465         [EXIT_REASON_EXCEPTION_NMI]           = handle_exception,
5466         [EXIT_REASON_EXTERNAL_INTERRUPT]      = handle_external_interrupt,
5467         [EXIT_REASON_TRIPLE_FAULT]            = handle_triple_fault,
5468         [EXIT_REASON_NMI_WINDOW]              = handle_nmi_window,
5469         [EXIT_REASON_IO_INSTRUCTION]          = handle_io,
5470         [EXIT_REASON_CR_ACCESS]               = handle_cr,
5471         [EXIT_REASON_DR_ACCESS]               = handle_dr,
5472         [EXIT_REASON_CPUID]                   = handle_cpuid,
5473         [EXIT_REASON_MSR_READ]                = handle_rdmsr,
5474         [EXIT_REASON_MSR_WRITE]               = handle_wrmsr,
5475         [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
5476         [EXIT_REASON_HLT]                     = handle_halt,
5477         [EXIT_REASON_INVD]                    = handle_invd,
5478         [EXIT_REASON_INVLPG]                  = handle_invlpg,
5479         [EXIT_REASON_RDPMC]                   = handle_rdpmc,
5480         [EXIT_REASON_VMCALL]                  = handle_vmcall,
5481         [EXIT_REASON_VMCLEAR]                 = handle_vmx_instruction,
5482         [EXIT_REASON_VMLAUNCH]                = handle_vmx_instruction,
5483         [EXIT_REASON_VMPTRLD]                 = handle_vmx_instruction,
5484         [EXIT_REASON_VMPTRST]                 = handle_vmx_instruction,
5485         [EXIT_REASON_VMREAD]                  = handle_vmx_instruction,
5486         [EXIT_REASON_VMRESUME]                = handle_vmx_instruction,
5487         [EXIT_REASON_VMWRITE]                 = handle_vmx_instruction,
5488         [EXIT_REASON_VMOFF]                   = handle_vmx_instruction,
5489         [EXIT_REASON_VMON]                    = handle_vmx_instruction,
5490         [EXIT_REASON_TPR_BELOW_THRESHOLD]     = handle_tpr_below_threshold,
5491         [EXIT_REASON_APIC_ACCESS]             = handle_apic_access,
5492         [EXIT_REASON_APIC_WRITE]              = handle_apic_write,
5493         [EXIT_REASON_EOI_INDUCED]             = handle_apic_eoi_induced,
5494         [EXIT_REASON_WBINVD]                  = handle_wbinvd,
5495         [EXIT_REASON_XSETBV]                  = handle_xsetbv,
5496         [EXIT_REASON_TASK_SWITCH]             = handle_task_switch,
5497         [EXIT_REASON_MCE_DURING_VMENTRY]      = handle_machine_check,
5498         [EXIT_REASON_GDTR_IDTR]               = handle_desc,
5499         [EXIT_REASON_LDTR_TR]                 = handle_desc,
5500         [EXIT_REASON_EPT_VIOLATION]           = handle_ept_violation,
5501         [EXIT_REASON_EPT_MISCONFIG]           = handle_ept_misconfig,
5502         [EXIT_REASON_PAUSE_INSTRUCTION]       = handle_pause,
5503         [EXIT_REASON_MWAIT_INSTRUCTION]       = handle_mwait,
5504         [EXIT_REASON_MONITOR_TRAP_FLAG]       = handle_monitor_trap,
5505         [EXIT_REASON_MONITOR_INSTRUCTION]     = handle_monitor,
5506         [EXIT_REASON_INVEPT]                  = handle_vmx_instruction,
5507         [EXIT_REASON_INVVPID]                 = handle_vmx_instruction,
5508         [EXIT_REASON_RDRAND]                  = handle_invalid_op,
5509         [EXIT_REASON_RDSEED]                  = handle_invalid_op,
5510         [EXIT_REASON_XSAVES]                  = handle_xsaves,
5511         [EXIT_REASON_XRSTORS]                 = handle_xrstors,
5512         [EXIT_REASON_PML_FULL]                = handle_pml_full,
5513         [EXIT_REASON_INVPCID]                 = handle_invpcid,
5514         [EXIT_REASON_VMFUNC]                  = handle_vmx_instruction,
5515         [EXIT_REASON_PREEMPTION_TIMER]        = handle_preemption_timer,
5516         [EXIT_REASON_ENCLS]                   = handle_encls,
5517 };
5518 
5519 static const int kvm_vmx_max_exit_handlers =
5520         ARRAY_SIZE(kvm_vmx_exit_handlers);
5521 
5522 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5523 {
5524         *info1 = vmcs_readl(EXIT_QUALIFICATION);
5525         *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
5526 }
5527 
5528 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
5529 {
5530         if (vmx->pml_pg) {
5531                 __free_page(vmx->pml_pg);
5532                 vmx->pml_pg = NULL;
5533         }
5534 }
5535 
5536 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
5537 {
5538         struct vcpu_vmx *vmx = to_vmx(vcpu);
5539         u64 *pml_buf;
5540         u16 pml_idx;
5541 
5542         pml_idx = vmcs_read16(GUEST_PML_INDEX);
5543 
5544         /* Do nothing if PML buffer is empty */
5545         if (pml_idx == (PML_ENTITY_NUM - 1))
5546                 return;
5547 
5548         /* PML index always points to next available PML buffer entity */
5549         if (pml_idx >= PML_ENTITY_NUM)
5550                 pml_idx = 0;
5551         else
5552                 pml_idx++;
5553 
5554         pml_buf = page_address(vmx->pml_pg);
5555         for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
5556                 u64 gpa;
5557 
5558                 gpa = pml_buf[pml_idx];
5559                 WARN_ON(gpa & (PAGE_SIZE - 1));
5560                 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
5561         }
5562 
5563         /* reset PML index */
5564         vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5565 }
5566 
5567 /*
5568  * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
5569  * Called before reporting dirty_bitmap to userspace.
5570  */
5571 static void kvm_flush_pml_buffers(struct kvm *kvm)
5572 {
5573         int i;
5574         struct kvm_vcpu *vcpu;
5575         /*
5576          * We only need to kick vcpu out of guest mode here, as PML buffer
5577          * is flushed at beginning of all VMEXITs, and it's obvious that only
5578          * vcpus running in guest are possible to have unflushed GPAs in PML
5579          * buffer.
5580          */
5581         kvm_for_each_vcpu(i, vcpu, kvm)
5582                 kvm_vcpu_kick(vcpu);
5583 }
5584 
5585 static void vmx_dump_sel(char *name, uint32_t sel)
5586 {
5587         pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
5588                name, vmcs_read16(sel),
5589                vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
5590                vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
5591                vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
5592 }
5593 
5594 static void vmx_dump_dtsel(char *name, uint32_t limit)
5595 {
5596         pr_err("%s                           limit=0x%08x, base=0x%016lx\n",
5597                name, vmcs_read32(limit),
5598                vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
5599 }
5600 
5601 static void dump_vmcs(void)
5602 {
5603         u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
5604         u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
5605         u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5606         u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
5607         u32 secondary_exec_control = 0;
5608         unsigned long cr4 = vmcs_readl(GUEST_CR4);
5609         u64 efer = vmcs_read64(GUEST_IA32_EFER);
5610         int i, n;
5611 
5612         if (cpu_has_secondary_exec_ctrls())
5613                 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5614 
5615         pr_err("*** Guest State ***\n");
5616         pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5617                vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
5618                vmcs_readl(CR0_GUEST_HOST_MASK));
5619         pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
5620                cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
5621         pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
5622         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
5623             (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
5624         {
5625                 pr_err("PDPTR0 = 0x%016llx  PDPTR1 = 0x%016llx\n",
5626                        vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
5627                 pr_err("PDPTR2 = 0x%016llx  PDPTR3 = 0x%016llx\n",
5628                        vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
5629         }
5630         pr_err("RSP = 0x%016lx  RIP = 0x%016lx\n",
5631                vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
5632         pr_err("RFLAGS=0x%08lx         DR7 = 0x%016lx\n",
5633                vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
5634         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5635                vmcs_readl(GUEST_SYSENTER_ESP),
5636                vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
5637         vmx_dump_sel("CS:  ", GUEST_CS_SELECTOR);
5638         vmx_dump_sel("DS:  ", GUEST_DS_SELECTOR);
5639         vmx_dump_sel("SS:  ", GUEST_SS_SELECTOR);
5640         vmx_dump_sel("ES:  ", GUEST_ES_SELECTOR);
5641         vmx_dump_sel("FS:  ", GUEST_FS_SELECTOR);
5642         vmx_dump_sel("GS:  ", GUEST_GS_SELECTOR);
5643         vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
5644         vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
5645         vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
5646         vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
5647         if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
5648             (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
5649                 pr_err("EFER =     0x%016llx  PAT = 0x%016llx\n",
5650                        efer, vmcs_read64(GUEST_IA32_PAT));
5651         pr_err("DebugCtl = 0x%016llx  DebugExceptions = 0x%016lx\n",
5652                vmcs_read64(GUEST_IA32_DEBUGCTL),
5653                vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
5654         if (cpu_has_load_perf_global_ctrl() &&
5655             vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
5656                 pr_err("PerfGlobCtl = 0x%016llx\n",
5657                        vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
5658         if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
5659                 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
5660         pr_err("Interruptibility = %08x  ActivityState = %08x\n",
5661                vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
5662                vmcs_read32(GUEST_ACTIVITY_STATE));
5663         if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
5664                 pr_err("InterruptStatus = %04x\n",
5665                        vmcs_read16(GUEST_INTR_STATUS));
5666 
5667         pr_err("*** Host State ***\n");
5668         pr_err("RIP = 0x%016lx  RSP = 0x%016lx\n",
5669                vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
5670         pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
5671                vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
5672                vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
5673                vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
5674                vmcs_read16(HOST_TR_SELECTOR));
5675         pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
5676                vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
5677                vmcs_readl(HOST_TR_BASE));
5678         pr_err("GDTBase=%016lx IDTBase=%016lx\n",
5679                vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
5680         pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
5681                vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
5682                vmcs_readl(HOST_CR4));
5683         pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
5684                vmcs_readl(HOST_IA32_SYSENTER_ESP),
5685                vmcs_read32(HOST_IA32_SYSENTER_CS),
5686                vmcs_readl(HOST_IA32_SYSENTER_EIP));
5687         if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
5688                 pr_err("EFER = 0x%016llx  PAT = 0x%016llx\n",
5689                        vmcs_read64(HOST_IA32_EFER),
5690                        vmcs_read64(HOST_IA32_PAT));
5691         if (cpu_has_load_perf_global_ctrl() &&
5692             vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
5693                 pr_err("PerfGlobCtl = 0x%016llx\n",
5694                        vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
5695 
5696         pr_err("*** Control State ***\n");
5697         pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
5698                pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
5699         pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
5700         pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
5701                vmcs_read32(EXCEPTION_BITMAP),
5702                vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
5703                vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
5704         pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
5705                vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
5706                vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
5707                vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
5708         pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
5709                vmcs_read32(VM_EXIT_INTR_INFO),
5710                vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
5711                vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
5712         pr_err("        reason=%08x qualification=%016lx\n",
5713                vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
5714         pr_err("IDTVectoring: info=%08x errcode=%08x\n",
5715                vmcs_read32(IDT_VECTORING_INFO_FIELD),
5716                vmcs_read32(IDT_VECTORING_ERROR_CODE));
5717         pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
5718         if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
5719                 pr_err("TSC Multiplier = 0x%016llx\n",
5720                        vmcs_read64(TSC_MULTIPLIER));
5721         if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
5722                 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
5723         if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
5724                 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
5725         if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
5726                 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
5727         n = vmcs_read32(CR3_TARGET_COUNT);
5728         for (i = 0; i + 1 < n; i += 4)
5729                 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
5730                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
5731                        i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
5732         if (i < n)
5733                 pr_err("CR3 target%u=%016lx\n",
5734                        i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
5735         if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
5736                 pr_err("PLE Gap=%08x Window=%08x\n",
5737                        vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
5738         if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
5739                 pr_err("Virtual processor ID = 0x%04x\n",
5740                        vmcs_read16(VIRTUAL_PROCESSOR_ID));
5741 }
5742 
5743 /*
5744  * The guest has exited.  See if we can fix it or if we need userspace
5745  * assistance.
5746  */
5747 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
5748 {
5749         struct vcpu_vmx *vmx = to_vmx(vcpu);
5750         u32 exit_reason = vmx->exit_reason;
5751         u32 vectoring_info = vmx->idt_vectoring_info;
5752 
5753         trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
5754 
5755         /*
5756          * Flush logged GPAs PML buffer, this will make dirty_bitmap more
5757          * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
5758          * querying dirty_bitmap, we only need to kick all vcpus out of guest
5759          * mode as if vcpus is in root mode, the PML buffer must has been
5760          * flushed already.
5761          */
5762         if (enable_pml)
5763                 vmx_flush_pml_buffer(vcpu);
5764 
5765         /* If guest state is invalid, start emulating */
5766         if (vmx->emulation_required)
5767                 return handle_invalid_guest_state(vcpu);
5768 
5769         if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
5770                 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
5771 
5772         if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
5773                 dump_vmcs();
5774                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5775                 vcpu->run->fail_entry.hardware_entry_failure_reason
5776                         = exit_reason;
5777                 return 0;
5778         }
5779 
5780         if (unlikely(vmx->fail)) {
5781                 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5782                 vcpu->run->fail_entry.hardware_entry_failure_reason
5783                         = vmcs_read32(VM_INSTRUCTION_ERROR);
5784                 return 0;
5785         }
5786 
5787         /*
5788          * Note:
5789          * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
5790          * delivery event since it indicates guest is accessing MMIO.
5791          * The vm-exit can be triggered again after return to guest that
5792          * will cause infinite loop.
5793          */
5794         if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
5795                         (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
5796                         exit_reason != EXIT_REASON_EPT_VIOLATION &&
5797                         exit_reason != EXIT_REASON_PML_FULL &&
5798                         exit_reason != EXIT_REASON_TASK_SWITCH)) {
5799                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5800                 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
5801                 vcpu->run->internal.ndata = 3;
5802                 vcpu->run->internal.data[0] = vectoring_info;
5803                 vcpu->run->internal.data[1] = exit_reason;
5804                 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
5805                 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
5806                         vcpu->run->internal.ndata++;
5807                         vcpu->run->internal.data[3] =
5808                                 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
5809                 }
5810                 return 0;
5811         }
5812 
5813         if (unlikely(!enable_vnmi &&
5814                      vmx->loaded_vmcs->soft_vnmi_blocked)) {
5815                 if (vmx_interrupt_allowed(vcpu)) {
5816                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5817                 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
5818                            vcpu->arch.nmi_pending) {
5819                         /*
5820                          * This CPU don't support us in finding the end of an
5821                          * NMI-blocked window if the guest runs with IRQs
5822                          * disabled. So we pull the trigger after 1 s of
5823                          * futile waiting, but inform the user about this.
5824                          */
5825                         printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
5826                                "state on VCPU %d after 1 s timeout\n",
5827                                __func__, vcpu->vcpu_id);
5828                         vmx->loaded_vmcs->soft_vnmi_blocked = 0;
5829                 }
5830         }
5831 
5832         if (exit_reason < kvm_vmx_max_exit_handlers
5833             && kvm_vmx_exit_handlers[exit_reason])
5834                 return kvm_vmx_exit_handlers[exit_reason](vcpu);
5835         else {
5836                 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
5837                                 exit_reason);
5838                 kvm_queue_exception(vcpu, UD_VECTOR);
5839                 return 1;
5840         }
5841 }
5842 
5843 /*
5844  * Software based L1D cache flush which is used when microcode providing
5845  * the cache control MSR is not loaded.
5846  *
5847  * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
5848  * flush it is required to read in 64 KiB because the replacement algorithm
5849  * is not exactly LRU. This could be sized at runtime via topology
5850  * information but as all relevant affected CPUs have 32KiB L1D cache size
5851  * there is no point in doing so.
5852  */
5853 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
5854 {
5855         int size = PAGE_SIZE << L1D_CACHE_ORDER;
5856 
5857         /*
5858          * This code is only executed when the the flush mode is 'cond' or
5859          * 'always'
5860          */
5861         if (static_branch_likely(&vmx_l1d_flush_cond)) {
5862                 bool flush_l1d;
5863 
5864                 /*
5865                  * Clear the per-vcpu flush bit, it gets set again
5866                  * either from vcpu_run() or from one of the unsafe
5867                  * VMEXIT handlers.
5868                  */
5869                 flush_l1d = vcpu->arch.l1tf_flush_l1d;
5870                 vcpu->arch.l1tf_flush_l1d = false;
5871 
5872                 /*
5873                  * Clear the per-cpu flush bit, it gets set again from
5874                  * the interrupt handlers.
5875                  */
5876                 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
5877                 kvm_clear_cpu_l1tf_flush_l1d();
5878 
5879                 if (!flush_l1d)
5880                         return;
5881         }
5882 
5883         vcpu->stat.l1d_flush++;
5884 
5885         if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
5886                 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
5887                 return;
5888         }
5889 
5890         asm volatile(
5891                 /* First ensure the pages are in the TLB */
5892                 "xorl   %%eax, %%eax\n"
5893                 ".Lpopulate_tlb:\n\t"
5894                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5895                 "addl   $4096, %%eax\n\t"
5896                 "cmpl   %%eax, %[size]\n\t"
5897                 "jne    .Lpopulate_tlb\n\t"
5898                 "xorl   %%eax, %%eax\n\t"
5899                 "cpuid\n\t"
5900                 /* Now fill the cache */
5901                 "xorl   %%eax, %%eax\n"
5902                 ".Lfill_cache:\n"
5903                 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
5904                 "addl   $64, %%eax\n\t"
5905                 "cmpl   %%eax, %[size]\n\t"
5906                 "jne    .Lfill_cache\n\t"
5907                 "lfence\n"
5908                 :: [flush_pages] "r" (vmx_l1d_flush_pages),
5909                     [size] "r" (size)
5910                 : "eax", "ebx", "ecx", "edx");
5911 }
5912 
5913 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5914 {
5915         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5916 
5917         if (is_guest_mode(vcpu) &&
5918                 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
5919                 return;
5920 
5921         if (irr == -1 || tpr < irr) {
5922                 vmcs_write32(TPR_THRESHOLD, 0);
5923                 return;
5924         }
5925 
5926         vmcs_write32(TPR_THRESHOLD, irr);
5927 }
5928 
5929 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5930 {
5931         u32 sec_exec_control;
5932 
5933         if (!lapic_in_kernel(vcpu))
5934                 return;
5935 
5936         if (!flexpriority_enabled &&
5937             !cpu_has_vmx_virtualize_x2apic_mode())
5938                 return;
5939 
5940         /* Postpone execution until vmcs01 is the current VMCS. */
5941         if (is_guest_mode(vcpu)) {
5942                 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
5943                 return;
5944         }
5945 
5946         sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
5947         sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
5948                               SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
5949 
5950         switch (kvm_get_apic_mode(vcpu)) {
5951         case LAPIC_MODE_INVALID:
5952                 WARN_ONCE(true, "Invalid local APIC state");
5953         case LAPIC_MODE_DISABLED:
5954                 break;
5955         case LAPIC_MODE_XAPIC:
5956                 if (flexpriority_enabled) {
5957                         sec_exec_control |=
5958                                 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5959                         vmx_flush_tlb(vcpu, true);
5960                 }
5961                 break;
5962         case LAPIC_MODE_X2APIC:
5963                 if (cpu_has_vmx_virtualize_x2apic_mode())
5964                         sec_exec_control |=
5965                                 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5966                 break;
5967         }
5968         vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
5969 
5970         vmx_update_msr_bitmap(vcpu);
5971 }
5972 
5973 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
5974 {
5975         if (!is_guest_mode(vcpu)) {
5976                 vmcs_write64(APIC_ACCESS_ADDR, hpa);
5977                 vmx_flush_tlb(vcpu, true);
5978         }
5979 }
5980 
5981 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5982 {
5983         u16 status;
5984         u8 old;
5985 
5986         if (max_isr == -1)
5987                 max_isr = 0;
5988 
5989         status = vmcs_read16(GUEST_INTR_STATUS);
5990         old = status >> 8;
5991         if (max_isr != old) {
5992                 status &= 0xff;
5993                 status |= max_isr << 8;
5994                 vmcs_write16(GUEST_INTR_STATUS, status);
5995         }
5996 }
5997 
5998 static void vmx_set_rvi(int vector)
5999 {
6000         u16 status;
6001         u8 old;
6002 
6003         if (vector == -1)
6004                 vector = 0;
6005 
6006         status = vmcs_read16(GUEST_INTR_STATUS);
6007         old = (u8)status & 0xff;
6008         if ((u8)vector != old) {
6009                 status &= ~0xff;
6010                 status |= (u8)vector;
6011                 vmcs_write16(GUEST_INTR_STATUS, status);
6012         }
6013 }
6014 
6015 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
6016 {
6017         /*
6018          * When running L2, updating RVI is only relevant when
6019          * vmcs12 virtual-interrupt-delivery enabled.
6020          * However, it can be enabled only when L1 also
6021          * intercepts external-interrupts and in that case
6022          * we should not update vmcs02 RVI but instead intercept
6023          * interrupt. Therefore, do nothing when running L2.
6024          */
6025         if (!is_guest_mode(vcpu))
6026                 vmx_set_rvi(max_irr);
6027 }
6028 
6029 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
6030 {
6031         struct vcpu_vmx *vmx = to_vmx(vcpu);
6032         int max_irr;
6033         bool max_irr_updated;
6034 
6035         WARN_ON(!vcpu->arch.apicv_active);
6036         if (pi_test_on(&vmx->pi_desc)) {
6037                 pi_clear_on(&vmx->pi_desc);
6038                 /*
6039                  * IOMMU can write to PIR.ON, so the barrier matters even on UP.
6040                  * But on x86 this is just a compiler barrier anyway.
6041                  */
6042                 smp_mb__after_atomic();
6043                 max_irr_updated =
6044                         kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
6045 
6046                 /*
6047                  * If we are running L2 and L1 has a new pending interrupt
6048                  * which can be injected, we should re-evaluate
6049                  * what should be done with this new L1 interrupt.
6050                  * If L1 intercepts external-interrupts, we should
6051                  * exit from L2 to L1. Otherwise, interrupt should be
6052                  * delivered directly to L2.
6053                  */
6054                 if (is_guest_mode(vcpu) && max_irr_updated) {
6055                         if (nested_exit_on_intr(vcpu))
6056                                 kvm_vcpu_exiting_guest_mode(vcpu);
6057                         else
6058                                 kvm_make_request(KVM_REQ_EVENT, vcpu);
6059                 }
6060         } else {
6061                 max_irr = kvm_lapic_find_highest_irr(vcpu);
6062         }
6063         vmx_hwapic_irr_update(vcpu, max_irr);
6064         return max_irr;
6065 }
6066 
6067 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
6068 {
6069         if (!kvm_vcpu_apicv_active(vcpu))
6070                 return;
6071 
6072         vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
6073         vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
6074         vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
6075         vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
6076 }
6077 
6078 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
6079 {
6080         struct vcpu_vmx *vmx = to_vmx(vcpu);
6081 
6082         pi_clear_on(&vmx->pi_desc);
6083         memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
6084 }
6085 
6086 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
6087 {
6088         u32 exit_intr_info = 0;
6089         u16 basic_exit_reason = (u16)vmx->exit_reason;
6090 
6091         if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
6092               || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
6093                 return;
6094 
6095         if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
6096                 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6097         vmx->exit_intr_info = exit_intr_info;
6098 
6099         /* if exit due to PF check for async PF */
6100         if (is_page_fault(exit_intr_info))
6101                 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
6102 
6103         /* Handle machine checks before interrupts are enabled */
6104         if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
6105             is_machine_check(exit_intr_info))
6106                 kvm_machine_check();
6107 
6108         /* We need to handle NMIs before interrupts are enabled */
6109         if (is_nmi(exit_intr_info)) {
6110                 kvm_before_interrupt(&vmx->vcpu);
6111                 asm("int $2");
6112                 kvm_after_interrupt(&vmx->vcpu);
6113         }
6114 }
6115 
6116 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
6117 {
6118         u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
6119 
6120         if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
6121                         == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
6122                 unsigned int vector;
6123                 unsigned long entry;
6124                 gate_desc *desc;
6125                 struct vcpu_vmx *vmx = to_vmx(vcpu);
6126 #ifdef CONFIG_X86_64
6127                 unsigned long tmp;
6128 #endif
6129 
6130                 vector =  exit_intr_info & INTR_INFO_VECTOR_MASK;
6131                 desc = (gate_desc *)vmx->host_idt_base + vector;
6132                 entry = gate_offset(desc);
6133                 asm volatile(
6134 #ifdef CONFIG_X86_64
6135                         "mov %%" _ASM_SP ", %[sp]\n\t"
6136                         "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
6137                         "push $%c[ss]\n\t"
6138                         "push %[sp]\n\t"
6139 #endif
6140                         "pushf\n\t"
6141                         __ASM_SIZE(push) " $%c[cs]\n\t"
6142                         CALL_NOSPEC
6143                         :
6144 #ifdef CONFIG_X86_64
6145                         [sp]"=&r"(tmp),
6146 #endif
6147                         ASM_CALL_CONSTRAINT
6148                         :
6149