KVM: VMX: Separate saving pre-realmode state from setting segments
[linux-3.10.git] / arch / x86 / kvm / vmx.c
index 84d9c93..4e49caf 100644 (file)
@@ -18,6 +18,7 @@
 
 #include "irq.h"
 #include "mmu.h"
+#include "cpuid.h"
 
 #include <linux/kvm_host.h>
 #include <linux/module.h>
@@ -26,6 +27,7 @@
 #include <linux/highmem.h>
 #include <linux/sched.h>
 #include <linux/moduleparam.h>
+#include <linux/mod_devicetable.h>
 #include <linux/ftrace_event.h>
 #include <linux/slab.h>
 #include <linux/tboot.h>
@@ -39,6 +41,7 @@
 #include <asm/mce.h>
 #include <asm/i387.h>
 #include <asm/xcr.h>
+#include <asm/perf_event.h>
 
 #include "trace.h"
 
 MODULE_AUTHOR("Qumranet");
 MODULE_LICENSE("GPL");
 
-static int __read_mostly bypass_guest_pf = 1;
-module_param(bypass_guest_pf, bool, S_IRUGO);
+static const struct x86_cpu_id vmx_cpu_id[] = {
+       X86_FEATURE_MATCH(X86_FEATURE_VMX),
+       {}
+};
+MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
 
-static int __read_mostly enable_vpid = 1;
+static bool __read_mostly enable_vpid = 1;
 module_param_named(vpid, enable_vpid, bool, 0444);
 
-static int __read_mostly flexpriority_enabled = 1;
+static bool __read_mostly flexpriority_enabled = 1;
 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
 
-static int __read_mostly enable_ept = 1;
+static bool __read_mostly enable_ept = 1;
 module_param_named(ept, enable_ept, bool, S_IRUGO);
 
-static int __read_mostly enable_unrestricted_guest = 1;
+static bool __read_mostly enable_unrestricted_guest = 1;
 module_param_named(unrestricted_guest,
                        enable_unrestricted_guest, bool, S_IRUGO);
 
-static int __read_mostly emulate_invalid_guest_state = 0;
+static bool __read_mostly enable_ept_ad_bits = 1;
+module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
+
+static bool __read_mostly emulate_invalid_guest_state = true;
 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
 
-static int __read_mostly vmm_exclusive = 1;
+static bool __read_mostly vmm_exclusive = 1;
 module_param(vmm_exclusive, bool, S_IRUGO);
 
-static int __read_mostly yield_on_hlt = 1;
-module_param(yield_on_hlt, bool, S_IRUGO);
+static bool __read_mostly fasteoi = 1;
+module_param(fasteoi, bool, S_IRUGO);
 
 /*
  * If nested=1, nested virtualization is supported, i.e., guests may use
  * VMX and be a hypervisor for its own guests. If nested=0, guests may not
  * use VMX instructions.
  */
-static int __read_mostly nested = 0;
+static bool __read_mostly nested = 0;
 module_param(nested, bool, S_IRUGO);
 
 #define KVM_GUEST_CR0_MASK_UNRESTRICTED_GUEST                          \
@@ -118,7 +127,7 @@ module_param(ple_gap, int, S_IRUGO);
 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
 module_param(ple_window, int, S_IRUGO);
 
-#define NR_AUTOLOAD_MSRS 1
+#define NR_AUTOLOAD_MSRS 8
 #define VMCS02_POOL_SIZE 1
 
 struct vmcs {
@@ -345,6 +354,14 @@ struct nested_vmx {
        /* vmcs02_list cache of VMCSs recently used to run L2 guests */
        struct list_head vmcs02_pool;
        int vmcs02_num;
+       u64 vmcs01_tsc_offset;
+       /* L2 must run next, and mustn't decide to exit to L1. */
+       bool nested_run_pending;
+       /*
+        * Guest pages referred to in vmcs02 with host-physical pointers, so
+        * we must keep them pinned while L2 runs.
+        */
+       struct page *apic_access_page;
 };
 
 struct vcpu_vmx {
@@ -379,6 +396,9 @@ struct vcpu_vmx {
        struct {
                int           loaded;
                u16           fs_sel, gs_sel, ldt_sel;
+#ifdef CONFIG_X86_64
+               u16           ds_sel, es_sel;
+#endif
                int           gs_ldt_reload_needed;
                int           fs_reload_needed;
        } host_state;
@@ -576,10 +596,9 @@ static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
 {
        struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT);
-       if (is_error_page(page)) {
-               kvm_release_page_clean(page);
+       if (is_error_page(page))
                return NULL;
-       }
+
        return page;
 }
 
@@ -598,6 +617,10 @@ static void kvm_cpu_vmxon(u64 addr);
 static void kvm_cpu_vmxoff(void);
 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
+static void vmx_set_segment(struct kvm_vcpu *vcpu,
+                           struct kvm_segment *var, int seg);
+static void vmx_get_segment(struct kvm_vcpu *vcpu,
+                           struct kvm_segment *var, int seg);
 
 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
@@ -614,6 +637,7 @@ static unsigned long *vmx_msr_bitmap_legacy;
 static unsigned long *vmx_msr_bitmap_longmode;
 
 static bool cpu_has_load_ia32_efer;
+static bool cpu_has_load_perf_global_ctrl;
 
 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
 static DEFINE_SPINLOCK(vmx_vpid_lock);
@@ -771,6 +795,11 @@ static inline bool cpu_has_vmx_ept_4levels(void)
        return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
 }
 
+static inline bool cpu_has_vmx_ept_ad_bits(void)
+{
+       return vmx_capability.ept & VMX_EPT_AD_BIT;
+}
+
 static inline bool cpu_has_vmx_invept_individual_addr(void)
 {
        return vmx_capability.ept & VMX_EPT_EXTENT_INDIVIDUAL_BIT;
@@ -831,6 +860,12 @@ static inline bool cpu_has_vmx_rdtscp(void)
                SECONDARY_EXEC_RDTSCP;
 }
 
+static inline bool cpu_has_vmx_invpcid(void)
+{
+       return vmcs_config.cpu_based_2nd_exec_ctrl &
+               SECONDARY_EXEC_ENABLE_INVPCID;
+}
+
 static inline bool cpu_has_virtual_nmis(void)
 {
        return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
@@ -847,6 +882,35 @@ static inline bool report_flexpriority(void)
        return flexpriority_enabled;
 }
 
+static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
+{
+       return vmcs12->cpu_based_vm_exec_control & bit;
+}
+
+static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
+{
+       return (vmcs12->cpu_based_vm_exec_control &
+                       CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
+               (vmcs12->secondary_vm_exec_control & bit);
+}
+
+static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12,
+       struct kvm_vcpu *vcpu)
+{
+       return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
+}
+
+static inline bool is_exception(u32 intr_info)
+{
+       return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
+               == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK);
+}
+
+static void nested_vmx_vmexit(struct kvm_vcpu *vcpu);
+static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
+                       struct vmcs12 *vmcs12,
+                       u32 reason, unsigned long qualification);
+
 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
 {
        int i;
@@ -922,7 +986,7 @@ static void vmcs_load(struct vmcs *vmcs)
                        : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
                        : "cc", "memory");
        if (error)
-               printk(KERN_ERR "kvm: vmptrld %p/%llx fail\n",
+               printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
                       vmcs, phys_addr);
 }
 
@@ -1142,18 +1206,46 @@ static void update_exception_bitmap(struct kvm_vcpu *vcpu)
                eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
        if (vcpu->fpu_active)
                eb &= ~(1u << NM_VECTOR);
+
+       /* When we are running a nested L2 guest and L1 specified for it a
+        * certain exception bitmap, we must trap the same exceptions and pass
+        * them to L1. When running L2, we will only handle the exceptions
+        * specified above if L1 did not want them.
+        */
+       if (is_guest_mode(vcpu))
+               eb |= get_vmcs12(vcpu)->exception_bitmap;
+
        vmcs_write32(EXCEPTION_BITMAP, eb);
 }
 
+static void clear_atomic_switch_msr_special(unsigned long entry,
+               unsigned long exit)
+{
+       vmcs_clear_bits(VM_ENTRY_CONTROLS, entry);
+       vmcs_clear_bits(VM_EXIT_CONTROLS, exit);
+}
+
 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
 {
        unsigned i;
        struct msr_autoload *m = &vmx->msr_autoload;
 
-       if (msr == MSR_EFER && cpu_has_load_ia32_efer) {
-               vmcs_clear_bits(VM_ENTRY_CONTROLS, VM_ENTRY_LOAD_IA32_EFER);
-               vmcs_clear_bits(VM_EXIT_CONTROLS, VM_EXIT_LOAD_IA32_EFER);
-               return;
+       switch (msr) {
+       case MSR_EFER:
+               if (cpu_has_load_ia32_efer) {
+                       clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
+                                       VM_EXIT_LOAD_IA32_EFER);
+                       return;
+               }
+               break;
+       case MSR_CORE_PERF_GLOBAL_CTRL:
+               if (cpu_has_load_perf_global_ctrl) {
+                       clear_atomic_switch_msr_special(
+                                       VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
+                                       VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
+                       return;
+               }
+               break;
        }
 
        for (i = 0; i < m->nr; ++i)
@@ -1169,25 +1261,55 @@ static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
        vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
 }
 
+static void add_atomic_switch_msr_special(unsigned long entry,
+               unsigned long exit, unsigned long guest_val_vmcs,
+               unsigned long host_val_vmcs, u64 guest_val, u64 host_val)
+{
+       vmcs_write64(guest_val_vmcs, guest_val);
+       vmcs_write64(host_val_vmcs, host_val);
+       vmcs_set_bits(VM_ENTRY_CONTROLS, entry);
+       vmcs_set_bits(VM_EXIT_CONTROLS, exit);
+}
+
 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
                                  u64 guest_val, u64 host_val)
 {
        unsigned i;
        struct msr_autoload *m = &vmx->msr_autoload;
 
-       if (msr == MSR_EFER && cpu_has_load_ia32_efer) {
-               vmcs_write64(GUEST_IA32_EFER, guest_val);
-               vmcs_write64(HOST_IA32_EFER, host_val);
-               vmcs_set_bits(VM_ENTRY_CONTROLS, VM_ENTRY_LOAD_IA32_EFER);
-               vmcs_set_bits(VM_EXIT_CONTROLS, VM_EXIT_LOAD_IA32_EFER);
-               return;
+       switch (msr) {
+       case MSR_EFER:
+               if (cpu_has_load_ia32_efer) {
+                       add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER,
+                                       VM_EXIT_LOAD_IA32_EFER,
+                                       GUEST_IA32_EFER,
+                                       HOST_IA32_EFER,
+                                       guest_val, host_val);
+                       return;
+               }
+               break;
+       case MSR_CORE_PERF_GLOBAL_CTRL:
+               if (cpu_has_load_perf_global_ctrl) {
+                       add_atomic_switch_msr_special(
+                                       VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
+                                       VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
+                                       GUEST_IA32_PERF_GLOBAL_CTRL,
+                                       HOST_IA32_PERF_GLOBAL_CTRL,
+                                       guest_val, host_val);
+                       return;
+               }
+               break;
        }
 
        for (i = 0; i < m->nr; ++i)
                if (m->guest[i].index == msr)
                        break;
 
-       if (i == m->nr) {
+       if (i == NR_AUTOLOAD_MSRS) {
+               printk_once(KERN_WARNING"Not enough mst switch entries. "
+                               "Can't add msr %x\n", msr);
+               return;
+       } else if (i == m->nr) {
                ++m->nr;
                vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr);
                vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr);
@@ -1220,7 +1342,7 @@ static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
        guest_efer = vmx->vcpu.arch.efer;
 
        /*
-        * NX is emulated; LMA and LME handled by hardware; SCE meaninless
+        * NX is emulated; LMA and LME handled by hardware; SCE meaningless
         * outside long mode
         */
        ignore_bits = EFER_NX | EFER_SCE;
@@ -1316,6 +1438,11 @@ static void vmx_save_host_state(struct kvm_vcpu *vcpu)
        }
 
 #ifdef CONFIG_X86_64
+       savesegment(ds, vmx->host_state.ds_sel);
+       savesegment(es, vmx->host_state.es_sel);
+#endif
+
+#ifdef CONFIG_X86_64
        vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
        vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
 #else
@@ -1355,11 +1482,17 @@ static void __vmx_load_host_state(struct vcpu_vmx *vmx)
        }
        if (vmx->host_state.fs_reload_needed)
                loadsegment(fs, vmx->host_state.fs_sel);
+#ifdef CONFIG_X86_64
+       if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
+               loadsegment(ds, vmx->host_state.ds_sel);
+               loadsegment(es, vmx->host_state.es_sel);
+       }
+#endif
        reload_tss();
 #ifdef CONFIG_X86_64
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
 #endif
-       if (current_thread_info()->status & TS_USEDFPU)
+       if (user_has_fpu())
                clts();
        load_gdt(&__get_cpu_var(host_gdt));
 }
@@ -1436,19 +1569,55 @@ static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
        vmcs_writel(GUEST_CR0, cr0);
        update_exception_bitmap(vcpu);
        vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
+       if (is_guest_mode(vcpu))
+               vcpu->arch.cr0_guest_owned_bits &=
+                       ~get_vmcs12(vcpu)->cr0_guest_host_mask;
        vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
 }
 
 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
 
+/*
+ * Return the cr0 value that a nested guest would read. This is a combination
+ * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
+ * its hypervisor (cr0_read_shadow).
+ */
+static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
+{
+       return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
+               (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
+}
+static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
+{
+       return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
+               (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
+}
+
 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
 {
+       /* Note that there is no vcpu->fpu_active = 0 here. The caller must
+        * set this *before* calling this function.
+        */
        vmx_decache_cr0_guest_bits(vcpu);
        vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
        update_exception_bitmap(vcpu);
        vcpu->arch.cr0_guest_owned_bits = 0;
        vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
-       vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
+       if (is_guest_mode(vcpu)) {
+               /*
+                * L1's specified read shadow might not contain the TS bit,
+                * so now that we turned on shadowing of this bit, we need to
+                * set this bit of the shadow. Like in nested_vmx_run we need
+                * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
+                * up-to-date here because we just decached cr0.TS (and we'll
+                * only update vmcs12->guest_cr0 on nested exit).
+                */
+               struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+               vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
+                       (vcpu->arch.cr0 & X86_CR0_TS);
+               vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
+       } else
+               vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
 }
 
 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
@@ -1521,15 +1690,23 @@ static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
        vmx_set_interrupt_shadow(vcpu, 0);
 }
 
-static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
+/*
+ * KVM wants to inject page-faults which it got to the guest. This function
+ * checks whether in a nested guest, we need to inject them to L1 or L2.
+ * This function assumes it is called with the exit reason in vmcs02 being
+ * a #PF exception (this is the only case in which KVM injects a #PF when L2
+ * is running).
+ */
+static int nested_pf_handled(struct kvm_vcpu *vcpu)
 {
-       /* Ensure that we clear the HLT state in the VMCS.  We don't need to
-        * explicitly skip the instruction because if the HLT state is set, then
-        * the instruction is already executing and RIP has already been
-        * advanced. */
-       if (!yield_on_hlt &&
-           vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
-               vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
+       struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+
+       /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
+       if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR)))
+               return 0;
+
+       nested_vmx_vmexit(vcpu);
+       return 1;
 }
 
 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
@@ -1539,6 +1716,10 @@ static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
        struct vcpu_vmx *vmx = to_vmx(vcpu);
        u32 intr_info = nr | INTR_INFO_VALID_MASK;
 
+       if (nr == PF_VECTOR && is_guest_mode(vcpu) &&
+               nested_pf_handled(vcpu))
+               return;
+
        if (has_error_code) {
                vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
                intr_info |= INTR_INFO_DELIVER_CODE_MASK;
@@ -1561,7 +1742,6 @@ static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
                intr_info |= INTR_TYPE_HARD_EXCEPTION;
 
        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
-       vmx_clear_hlt(vcpu);
 }
 
 static bool vmx_rdtscp_supported(void)
@@ -1569,6 +1749,11 @@ static bool vmx_rdtscp_supported(void)
        return cpu_has_vmx_rdtscp();
 }
 
+static bool vmx_invpcid_supported(void)
+{
+       return cpu_has_vmx_invpcid() && enable_ept;
+}
+
 /*
  * Swap MSR entry in host/guest MSR entry array.
  */
@@ -1591,7 +1776,6 @@ static void setup_msrs(struct vcpu_vmx *vmx)
        int save_nmsrs, index;
        unsigned long *msr_bitmap;
 
-       vmx_load_host_state(vmx);
        save_nmsrs = 0;
 #ifdef CONFIG_X86_64
        if (is_long_mode(&vmx->vcpu)) {
@@ -1646,13 +1830,34 @@ static u64 guest_read_tsc(void)
 }
 
 /*
- * Empty call-back. Needs to be implemented when VMX enables the SET_TSC_KHZ
- * ioctl. In this case the call-back should update internal vmx state to make
- * the changes effective.
+ * Like guest_read_tsc, but always returns L1's notion of the timestamp
+ * counter, even if a nested guest (L2) is currently running.
+ */
+u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu)
+{
+       u64 host_tsc, tsc_offset;
+
+       rdtscll(host_tsc);
+       tsc_offset = is_guest_mode(vcpu) ?
+               to_vmx(vcpu)->nested.vmcs01_tsc_offset :
+               vmcs_read64(TSC_OFFSET);
+       return host_tsc + tsc_offset;
+}
+
+/*
+ * Engage any workarounds for mis-matched TSC rates.  Currently limited to
+ * software catchup for faster rates on slower CPUs.
  */
-static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
+static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale)
 {
-       /* Nothing to do here */
+       if (!scale)
+               return;
+
+       if (user_tsc_khz > tsc_khz) {
+               vcpu->arch.tsc_catchup = 1;
+               vcpu->arch.tsc_always_catchup = 1;
+       } else
+               WARN(1, "user requested TSC rate below hardware speed\n");
 }
 
 /*
@@ -1660,13 +1865,33 @@ static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz)
  */
 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
 {
-       vmcs_write64(TSC_OFFSET, offset);
+       if (is_guest_mode(vcpu)) {
+               /*
+                * We're here if L1 chose not to trap WRMSR to TSC. According
+                * to the spec, this should set L1's TSC; The offset that L1
+                * set for L2 remains unchanged, and still needs to be added
+                * to the newly set TSC to get L2's TSC.
+                */
+               struct vmcs12 *vmcs12;
+               to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset;
+               /* recalculate vmcs02.TSC_OFFSET: */
+               vmcs12 = get_vmcs12(vcpu);
+               vmcs_write64(TSC_OFFSET, offset +
+                       (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
+                        vmcs12->tsc_offset : 0));
+       } else {
+               vmcs_write64(TSC_OFFSET, offset);
+       }
 }
 
-static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment)
+static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host)
 {
        u64 offset = vmcs_read64(TSC_OFFSET);
        vmcs_write64(TSC_OFFSET, offset + adjustment);
+       if (is_guest_mode(vcpu)) {
+               /* Even when running L2, the adjustment needs to apply to L1 */
+               to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment;
+       }
 }
 
 static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
@@ -1737,6 +1962,7 @@ static __init void nested_vmx_setup_ctls_msrs(void)
 
        /* exit controls */
        nested_vmx_exit_ctls_low = 0;
+       /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */
 #ifdef CONFIG_X86_64
        nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE;
 #else
@@ -1764,6 +1990,7 @@ static __init void nested_vmx_setup_ctls_msrs(void)
 #endif
                CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
                CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING |
+               CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING |
                CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
        /*
         * We can allow some features even when not supported by the
@@ -1950,12 +2177,10 @@ static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
                        return 1;
                /* Otherwise falls through */
        default:
-               vmx_load_host_state(to_vmx(vcpu));
                if (vmx_get_vmx_msr(vcpu, msr_index, pdata))
                        return 0;
                msr = find_msr_entry(to_vmx(vcpu), msr_index);
                if (msr) {
-                       vmx_load_host_state(to_vmx(vcpu));
                        data = msr->data;
                        break;
                }
@@ -1979,7 +2204,6 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
 
        switch (msr_index) {
        case MSR_EFER:
-               vmx_load_host_state(vmx);
                ret = kvm_set_msr_common(vcpu, msr_index, data);
                break;
 #ifdef CONFIG_X86_64
@@ -2028,8 +2252,13 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
                        break;
                msr = find_msr_entry(vmx, msr_index);
                if (msr) {
-                       vmx_load_host_state(vmx);
                        msr->data = data;
+                       if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
+                               preempt_disable();
+                               kvm_set_shared_msr(msr->index, msr->data,
+                                                  msr->mask);
+                               preempt_enable();
+                       }
                        break;
                }
                ret = kvm_set_msr_common(vcpu, msr_index, data);
@@ -2210,7 +2439,7 @@ static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
                                &_pin_based_exec_control) < 0)
                return -EIO;
 
-       min =
+       min = CPU_BASED_HLT_EXITING |
 #ifdef CONFIG_X86_64
              CPU_BASED_CR8_LOAD_EXITING |
              CPU_BASED_CR8_STORE_EXITING |
@@ -2222,10 +2451,8 @@ static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
              CPU_BASED_USE_TSC_OFFSETING |
              CPU_BASED_MWAIT_EXITING |
              CPU_BASED_MONITOR_EXITING |
-             CPU_BASED_INVLPG_EXITING;
-
-       if (yield_on_hlt)
-               min |= CPU_BASED_HLT_EXITING;
+             CPU_BASED_INVLPG_EXITING |
+             CPU_BASED_RDPMC_EXITING;
 
        opt = CPU_BASED_TPR_SHADOW |
              CPU_BASED_USE_MSR_BITMAPS |
@@ -2246,7 +2473,8 @@ static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
                        SECONDARY_EXEC_ENABLE_EPT |
                        SECONDARY_EXEC_UNRESTRICTED_GUEST |
                        SECONDARY_EXEC_PAUSE_LOOP_EXITING |
-                       SECONDARY_EXEC_RDTSCP;
+                       SECONDARY_EXEC_RDTSCP |
+                       SECONDARY_EXEC_ENABLE_INVPCID;
                if (adjust_vmx_controls(min2, opt2,
                                        MSR_IA32_VMX_PROCBASED_CTLS2,
                                        &_cpu_based_2nd_exec_control) < 0)
@@ -2314,6 +2542,42 @@ static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
                && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
                                   VM_EXIT_LOAD_IA32_EFER);
 
+       cpu_has_load_perf_global_ctrl =
+               allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
+                               VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
+               && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
+                                  VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
+
+       /*
+        * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
+        * but due to arrata below it can't be used. Workaround is to use
+        * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
+        *
+        * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
+        *
+        * AAK155             (model 26)
+        * AAP115             (model 30)
+        * AAT100             (model 37)
+        * BC86,AAY89,BD102   (model 44)
+        * BA97               (model 46)
+        *
+        */
+       if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
+               switch (boot_cpu_data.x86_model) {
+               case 26:
+               case 30:
+               case 37:
+               case 44:
+               case 46:
+                       cpu_has_load_perf_global_ctrl = false;
+                       printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
+                                       "does not work properly. Using workaround\n");
+                       break;
+               default:
+                       break;
+               }
+       }
+
        return 0;
 }
 
@@ -2397,8 +2661,12 @@ static __init int hardware_setup(void)
            !cpu_has_vmx_ept_4levels()) {
                enable_ept = 0;
                enable_unrestricted_guest = 0;
+               enable_ept_ad_bits = 0;
        }
 
+       if (!cpu_has_vmx_ept_ad_bits())
+               enable_ept_ad_bits = 0;
+
        if (!cpu_has_vmx_unrestricted_guest())
                enable_unrestricted_guest = 0;
 
@@ -2488,17 +2756,19 @@ static gva_t rmode_tss_base(struct kvm *kvm)
 {
        if (!kvm->arch.tss_addr) {
                struct kvm_memslots *slots;
+               struct kvm_memory_slot *slot;
                gfn_t base_gfn;
 
                slots = kvm_memslots(kvm);
-               base_gfn = slots->memslots[0].base_gfn +
-                                kvm->memslots->memslots[0].npages - 3;
+               slot = id_to_memslot(slots, 0);
+               base_gfn = slot->base_gfn + slot->npages - 3;
+
                return base_gfn << PAGE_SHIFT;
        }
        return kvm->arch.tss_addr;
 }
 
-static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
+static void save_rmode_seg(int seg, struct kvm_save_segment *save)
 {
        struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
 
@@ -2506,6 +2776,12 @@ static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
        save->base = vmcs_readl(sf->base);
        save->limit = vmcs_read32(sf->limit);
        save->ar = vmcs_read32(sf->ar_bytes);
+}
+
+static void fix_rmode_seg(int seg, struct kvm_save_segment *save)
+{
+       struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
+
        vmcs_write16(sf->selector, save->base >> 4);
        vmcs_write32(sf->base, save->base & 0xffff0);
        vmcs_write32(sf->limit, 0xffff);
@@ -2520,6 +2796,7 @@ static void enter_rmode(struct kvm_vcpu *vcpu)
 {
        unsigned long flags;
        struct vcpu_vmx *vmx = to_vmx(vcpu);
+       struct kvm_segment var;
 
        if (enable_unrestricted_guest)
                return;
@@ -2527,6 +2804,12 @@ static void enter_rmode(struct kvm_vcpu *vcpu)
        vmx->emulation_required = 1;
        vmx->rmode.vm86_active = 1;
 
+       save_rmode_seg(VCPU_SREG_TR, &vmx->rmode.tr);
+       save_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
+       save_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
+       save_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
+       save_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
+
        /*
         * Very old userspace does not call KVM_SET_TSS_ADDR before entering
         * vcpu. Call it here with phys address pointing 16M below 4G.
@@ -2541,14 +2824,8 @@ static void enter_rmode(struct kvm_vcpu *vcpu)
 
        vmx_segment_cache_clear(vmx);
 
-       vmx->rmode.tr.selector = vmcs_read16(GUEST_TR_SELECTOR);
-       vmx->rmode.tr.base = vmcs_readl(GUEST_TR_BASE);
        vmcs_writel(GUEST_TR_BASE, rmode_tss_base(vcpu->kvm));
-
-       vmx->rmode.tr.limit = vmcs_read32(GUEST_TR_LIMIT);
        vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
-
-       vmx->rmode.tr.ar = vmcs_read32(GUEST_TR_AR_BYTES);
        vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
 
        flags = vmcs_readl(GUEST_RFLAGS);
@@ -2563,20 +2840,23 @@ static void enter_rmode(struct kvm_vcpu *vcpu)
        if (emulate_invalid_guest_state)
                goto continue_rmode;
 
-       vmcs_write16(GUEST_SS_SELECTOR, vmcs_readl(GUEST_SS_BASE) >> 4);
-       vmcs_write32(GUEST_SS_LIMIT, 0xffff);
-       vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
+       vmx_get_segment(vcpu, &var, VCPU_SREG_SS);
+       vmx_set_segment(vcpu, &var, VCPU_SREG_SS);
+
+       vmx_get_segment(vcpu, &var, VCPU_SREG_CS);
+       vmx_set_segment(vcpu, &var, VCPU_SREG_CS);
 
-       vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
-       vmcs_write32(GUEST_CS_LIMIT, 0xffff);
-       if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
-               vmcs_writel(GUEST_CS_BASE, 0xf0000);
-       vmcs_write16(GUEST_CS_SELECTOR, vmcs_readl(GUEST_CS_BASE) >> 4);
+       vmx_get_segment(vcpu, &var, VCPU_SREG_ES);
+       vmx_set_segment(vcpu, &var, VCPU_SREG_ES);
 
-       fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
-       fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
-       fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
-       fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
+       vmx_get_segment(vcpu, &var, VCPU_SREG_DS);
+       vmx_set_segment(vcpu, &var, VCPU_SREG_DS);
+
+       vmx_get_segment(vcpu, &var, VCPU_SREG_GS);
+       vmx_set_segment(vcpu, &var, VCPU_SREG_GS);
+
+       vmx_get_segment(vcpu, &var, VCPU_SREG_FS);
+       vmx_set_segment(vcpu, &var, VCPU_SREG_FS);
 
 continue_rmode:
        kvm_mmu_reset_context(vcpu);
@@ -2621,8 +2901,8 @@ static void enter_lmode(struct kvm_vcpu *vcpu)
 
        guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
        if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) {
-               printk(KERN_DEBUG "%s: tss fixup for long mode. \n",
-                      __func__);
+               pr_debug_ratelimited("%s: tss fixup for long mode. \n",
+                                    __func__);
                vmcs_write32(GUEST_TR_AR_BYTES,
                             (guest_tr_ar & ~AR_TYPE_MASK)
                             | AR_TYPE_BUSY_64_TSS);
@@ -2777,6 +3057,8 @@ static u64 construct_eptp(unsigned long root_hpa)
        /* TODO write the value reading from MSR */
        eptp = VMX_EPT_DEFAULT_MT |
                VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
+       if (enable_ept_ad_bits)
+               eptp |= VMX_EPT_AD_ENABLE_BIT;
        eptp |= (root_hpa & PAGE_MASK);
 
        return eptp;
@@ -2903,11 +3185,22 @@ static int __vmx_get_cpl(struct kvm_vcpu *vcpu)
 
 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
 {
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
+
+       /*
+        * If we enter real mode with cs.sel & 3 != 0, the normal CPL calculations
+        * fail; use the cache instead.
+        */
+       if (unlikely(vmx->emulation_required && emulate_invalid_guest_state)) {
+               return vmx->cpl;
+       }
+
        if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) {
                __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
-               to_vmx(vcpu)->cpl = __vmx_get_cpl(vcpu);
+               vmx->cpl = __vmx_get_cpl(vcpu);
        }
-       return to_vmx(vcpu)->cpl;
+
+       return vmx->cpl;
 }
 
 
@@ -2915,7 +3208,7 @@ static u32 vmx_segment_access_rights(struct kvm_segment *var)
 {
        u32 ar;
 
-       if (var->unusable)
+       if (var->unusable || !var->present)
                ar = 1 << 16;
        else {
                ar = var->type & 15;
@@ -2927,8 +3220,6 @@ static u32 vmx_segment_access_rights(struct kvm_segment *var)
                ar |= (var->db & 1) << 14;
                ar |= (var->g & 1) << 15;
        }
-       if (ar == 0) /* a 0 value means unusable */
-               ar = AR_UNUSABLE_MASK;
 
        return ar;
 }
@@ -2968,7 +3259,7 @@ static void vmx_set_segment(struct kvm_vcpu *vcpu,
         * qemu binaries.
         *   IA32 arch specifies that at the time of processor reset the
         * "Accessed" bit in the AR field of segment registers is 1. And qemu
-        * is setting it to 0 in the usedland code. This causes invalid guest
+        * is setting it to 0 in the userland code. This causes invalid guest
         * state vmexit when "unrestricted guest" mode is turned on.
         *    Fix for this setup issue in cpu_reset is being pushed in the qemu
         * tree. Newer qemu binaries with that qemu fix would not need this
@@ -2979,6 +3270,44 @@ static void vmx_set_segment(struct kvm_vcpu *vcpu,
 
        vmcs_write32(sf->ar_bytes, ar);
        __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail);
+
+       /*
+        * Fix segments for real mode guest in hosts that don't have
+        * "unrestricted_mode" or it was disabled.
+        * This is done to allow migration of the guests from hosts with
+        * unrestricted guest like Westmere to older host that don't have
+        * unrestricted guest like Nehelem.
+        */
+       if (!enable_unrestricted_guest && vmx->rmode.vm86_active) {
+               switch (seg) {
+               case VCPU_SREG_CS:
+                       vmcs_write32(GUEST_CS_AR_BYTES, 0xf3);
+                       vmcs_write32(GUEST_CS_LIMIT, 0xffff);
+                       if (vmcs_readl(GUEST_CS_BASE) == 0xffff0000)
+                               vmcs_writel(GUEST_CS_BASE, 0xf0000);
+                       vmcs_write16(GUEST_CS_SELECTOR,
+                                    vmcs_readl(GUEST_CS_BASE) >> 4);
+                       break;
+               case VCPU_SREG_ES:
+                       fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.es);
+                       break;
+               case VCPU_SREG_DS:
+                       fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.ds);
+                       break;
+               case VCPU_SREG_GS:
+                       fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.gs);
+                       break;
+               case VCPU_SREG_FS:
+                       fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.fs);
+                       break;
+               case VCPU_SREG_SS:
+                       vmcs_write16(GUEST_SS_SELECTOR,
+                                    vmcs_readl(GUEST_SS_BASE) >> 4);
+                       vmcs_write32(GUEST_SS_LIMIT, 0xffff);
+                       vmcs_write32(GUEST_SS_AR_BYTES, 0xf3);
+                       break;
+               }
+       }
 }
 
 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
@@ -3395,18 +3724,122 @@ static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only)
 }
 
 /*
+ * Set up the vmcs's constant host-state fields, i.e., host-state fields that
+ * will not change in the lifetime of the guest.
+ * Note that host-state that does change is set elsewhere. E.g., host-state
+ * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
+ */
+static void vmx_set_constant_host_state(void)
+{
+       u32 low32, high32;
+       unsigned long tmpl;
+       struct desc_ptr dt;
+
+       vmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS);  /* 22.2.3 */
+       vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
+       vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
+
+       vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
+#ifdef CONFIG_X86_64
+       /*
+        * Load null selectors, so we can avoid reloading them in
+        * __vmx_load_host_state(), in case userspace uses the null selectors
+        * too (the expected case).
+        */
+       vmcs_write16(HOST_DS_SELECTOR, 0);
+       vmcs_write16(HOST_ES_SELECTOR, 0);
+#else
+       vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
+       vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
+#endif
+       vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
+       vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
+
+       native_store_idt(&dt);
+       vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
+
+       asm("mov $.Lkvm_vmx_return, %0" : "=r"(tmpl));
+       vmcs_writel(HOST_RIP, tmpl); /* 22.2.5 */
+
+       rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
+       vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
+       rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
+       vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
+
+       if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
+               rdmsr(MSR_IA32_CR_PAT, low32, high32);
+               vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
+       }
+}
+
+static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
+{
+       vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
+       if (enable_ept)
+               vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
+       if (is_guest_mode(&vmx->vcpu))
+               vmx->vcpu.arch.cr4_guest_owned_bits &=
+                       ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
+       vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
+}
+
+static u32 vmx_exec_control(struct vcpu_vmx *vmx)
+{
+       u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
+       if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
+               exec_control &= ~CPU_BASED_TPR_SHADOW;
+#ifdef CONFIG_X86_64
+               exec_control |= CPU_BASED_CR8_STORE_EXITING |
+                               CPU_BASED_CR8_LOAD_EXITING;
+#endif
+       }
+       if (!enable_ept)
+               exec_control |= CPU_BASED_CR3_STORE_EXITING |
+                               CPU_BASED_CR3_LOAD_EXITING  |
+                               CPU_BASED_INVLPG_EXITING;
+       return exec_control;
+}
+
+static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
+{
+       u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
+       if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
+               exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
+       if (vmx->vpid == 0)
+               exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
+       if (!enable_ept) {
+               exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
+               enable_unrestricted_guest = 0;
+               /* Enable INVPCID for non-ept guests may cause performance regression. */
+               exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
+       }
+       if (!enable_unrestricted_guest)
+               exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
+       if (!ple_gap)
+               exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
+       return exec_control;
+}
+
+static void ept_set_mmio_spte_mask(void)
+{
+       /*
+        * EPT Misconfigurations can be generated if the value of bits 2:0
+        * of an EPT paging-structure entry is 110b (write/execute).
+        * Also, magic bits (0xffull << 49) is set to quickly identify mmio
+        * spte.
+        */
+       kvm_mmu_set_mmio_spte_mask(0xffull << 49 | 0x6ull);
+}
+
+/*
  * Sets up the vmcs for emulated real mode.
  */
 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
 {
-       u32 host_sysenter_cs, msr_low, msr_high;
-       u32 junk;
-       u64 host_pat;
+#ifdef CONFIG_X86_64
        unsigned long a;
-       struct desc_ptr dt;
+#endif
        int i;
-       unsigned long kvm_vmx_return;
-       u32 exec_control;
 
        /* I/O */
        vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
@@ -3421,36 +3854,11 @@ static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
        vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
                vmcs_config.pin_based_exec_ctrl);
 
-       exec_control = vmcs_config.cpu_based_exec_ctrl;
-       if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) {
-               exec_control &= ~CPU_BASED_TPR_SHADOW;
-#ifdef CONFIG_X86_64
-               exec_control |= CPU_BASED_CR8_STORE_EXITING |
-                               CPU_BASED_CR8_LOAD_EXITING;
-#endif
-       }
-       if (!enable_ept)
-               exec_control |= CPU_BASED_CR3_STORE_EXITING |
-                               CPU_BASED_CR3_LOAD_EXITING  |
-                               CPU_BASED_INVLPG_EXITING;
-       vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
+       vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
 
        if (cpu_has_secondary_exec_ctrls()) {
-               exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
-               if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm))
-                       exec_control &=
-                               ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
-               if (vmx->vpid == 0)
-                       exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
-               if (!enable_ept) {
-                       exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
-                       enable_unrestricted_guest = 0;
-               }
-               if (!enable_unrestricted_guest)
-                       exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
-               if (!ple_gap)
-                       exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
-               vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
+               vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
+                               vmx_secondary_exec_control(vmx));
        }
 
        if (ple_gap) {
@@ -3458,20 +3866,13 @@ static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
                vmcs_write32(PLE_WINDOW, ple_window);
        }
 
-       vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, !!bypass_guest_pf);
-       vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, !!bypass_guest_pf);
+       vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
+       vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
        vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
 
-       vmcs_writel(HOST_CR0, read_cr0() | X86_CR0_TS);  /* 22.2.3 */
-       vmcs_writel(HOST_CR4, read_cr4());  /* 22.2.3, 22.2.5 */
-       vmcs_writel(HOST_CR3, read_cr3());  /* 22.2.3  FIXME: shadow tables */
-
-       vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
-       vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
-       vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
        vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
        vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
-       vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
+       vmx_set_constant_host_state();
 #ifdef CONFIG_X86_64
        rdmsrl(MSR_FS_BASE, a);
        vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
@@ -3482,32 +3883,15 @@ static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
        vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
 #endif
 
-       vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
-
-       native_store_idt(&dt);
-       vmcs_writel(HOST_IDTR_BASE, dt.address);   /* 22.2.4 */
-
-       asm("mov $.Lkvm_vmx_return, %0" : "=r"(kvm_vmx_return));
-       vmcs_writel(HOST_RIP, kvm_vmx_return); /* 22.2.5 */
        vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
        vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
        vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host));
        vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
        vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest));
 
-       rdmsr(MSR_IA32_SYSENTER_CS, host_sysenter_cs, junk);
-       vmcs_write32(HOST_IA32_SYSENTER_CS, host_sysenter_cs);
-       rdmsrl(MSR_IA32_SYSENTER_ESP, a);
-       vmcs_writel(HOST_IA32_SYSENTER_ESP, a);   /* 22.2.3 */
-       rdmsrl(MSR_IA32_SYSENTER_EIP, a);
-       vmcs_writel(HOST_IA32_SYSENTER_EIP, a);   /* 22.2.3 */
-
-       if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
-               rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
-               host_pat = msr_low | ((u64) msr_high << 32);
-               vmcs_write64(HOST_IA32_PAT, host_pat);
-       }
        if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
+               u32 msr_low, msr_high;
+               u64 host_pat;
                rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high);
                host_pat = msr_low | ((u64) msr_high << 32);
                /* Write the default value follow host pat */
@@ -3537,10 +3921,7 @@ static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
        vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl);
 
        vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
-       vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
-       if (enable_ept)
-               vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
-       vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
+       set_cr4_guest_host_mask(vmx);
 
        kvm_write_tsc(&vmx->vcpu, 0);
 
@@ -3647,7 +4028,9 @@ static int vmx_vcpu_reset(struct kvm_vcpu *vcpu)
                vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
 
        vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
+       vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
        vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */
+       srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
        vmx_set_cr4(&vmx->vcpu, 0);
        vmx_set_efer(&vmx->vcpu, 0);
        vmx_fpu_activate(&vmx->vcpu);
@@ -3664,9 +4047,28 @@ out:
        return ret;
 }
 
+/*
+ * In nested virtualization, check if L1 asked to exit on external interrupts.
+ * For most existing hypervisors, this will always return true.
+ */
+static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
+{
+       return get_vmcs12(vcpu)->pin_based_vm_exec_control &
+               PIN_BASED_EXT_INTR_MASK;
+}
+
 static void enable_irq_window(struct kvm_vcpu *vcpu)
 {
        u32 cpu_based_vm_exec_control;
+       if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) {
+               /*
+                * We get here if vmx_interrupt_allowed() said we can't
+                * inject to L1 now because L2 must run. Ask L2 to exit
+                * right after entry, so we can inject to L1 more promptly.
+                */
+               kvm_make_request(KVM_REQ_IMMEDIATE_EXIT, vcpu);
+               return;
+       }
 
        cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
        cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
@@ -3716,13 +4118,15 @@ static void vmx_inject_irq(struct kvm_vcpu *vcpu)
        } else
                intr |= INTR_TYPE_EXT_INTR;
        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
-       vmx_clear_hlt(vcpu);
 }
 
 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
 {
        struct vcpu_vmx *vmx = to_vmx(vcpu);
 
+       if (is_guest_mode(vcpu))
+               return;
+
        if (!cpu_has_virtual_nmis()) {
                /*
                 * Tracking the NMI-blocked state in software is built upon
@@ -3745,7 +4149,6 @@ static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
        }
        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
                        INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
-       vmx_clear_hlt(vcpu);
 }
 
 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
@@ -3789,6 +4192,18 @@ static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
 
 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
 {
+       if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) {
+               struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+               if (to_vmx(vcpu)->nested.nested_run_pending ||
+                   (vmcs12->idt_vectoring_info_field &
+                    VECTORING_INFO_VALID_MASK))
+                       return 0;
+               nested_vmx_vmexit(vcpu);
+               vmcs12->vm_exit_reason = EXIT_REASON_EXTERNAL_INTERRUPT;
+               vmcs12->vm_exit_intr_info = 0;
+               /* fall through to normal code, but now in L1, not L2 */
+       }
+
        return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
                !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
                        (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
@@ -3930,8 +4345,7 @@ static int handle_exception(struct kvm_vcpu *vcpu)
                error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
        if (is_page_fault(intr_info)) {
                /* EPT won't cause page fault directly */
-               if (enable_ept)
-                       BUG();
+               BUG_ON(enable_ept);
                cr2 = vmcs_readl(EXIT_QUALIFICATION);
                trace_kvm_page_fault(cr2, error_code);
 
@@ -4030,6 +4444,58 @@ vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
        hypercall[2] = 0xc1;
 }
 
+/* called to set cr0 as appropriate for a mov-to-cr0 exit. */
+static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
+{
+       if (to_vmx(vcpu)->nested.vmxon &&
+           ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
+               return 1;
+
+       if (is_guest_mode(vcpu)) {
+               /*
+                * We get here when L2 changed cr0 in a way that did not change
+                * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
+                * but did change L0 shadowed bits. This can currently happen
+                * with the TS bit: L0 may want to leave TS on (for lazy fpu
+                * loading) while pretending to allow the guest to change it.
+                */
+               if (kvm_set_cr0(vcpu, (val & vcpu->arch.cr0_guest_owned_bits) |
+                        (vcpu->arch.cr0 & ~vcpu->arch.cr0_guest_owned_bits)))
+                       return 1;
+               vmcs_writel(CR0_READ_SHADOW, val);
+               return 0;
+       } else
+               return kvm_set_cr0(vcpu, val);
+}
+
+static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
+{
+       if (is_guest_mode(vcpu)) {
+               if (kvm_set_cr4(vcpu, (val & vcpu->arch.cr4_guest_owned_bits) |
+                        (vcpu->arch.cr4 & ~vcpu->arch.cr4_guest_owned_bits)))
+                       return 1;
+               vmcs_writel(CR4_READ_SHADOW, val);
+               return 0;
+       } else
+               return kvm_set_cr4(vcpu, val);
+}
+
+/* called to set cr0 as approriate for clts instruction exit. */
+static void handle_clts(struct kvm_vcpu *vcpu)
+{
+       if (is_guest_mode(vcpu)) {
+               /*
+                * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
+                * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
+                * just pretend it's off (also in arch.cr0 for fpu_activate).
+                */
+               vmcs_writel(CR0_READ_SHADOW,
+                       vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
+               vcpu->arch.cr0 &= ~X86_CR0_TS;
+       } else
+               vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
+}
+
 static int handle_cr(struct kvm_vcpu *vcpu)
 {
        unsigned long exit_qualification, val;
@@ -4046,7 +4512,7 @@ static int handle_cr(struct kvm_vcpu *vcpu)
                trace_kvm_cr_write(cr, val);
                switch (cr) {
                case 0:
-                       err = kvm_set_cr0(vcpu, val);
+                       err = handle_set_cr0(vcpu, val);
                        kvm_complete_insn_gp(vcpu, err);
                        return 1;
                case 3:
@@ -4054,7 +4520,7 @@ static int handle_cr(struct kvm_vcpu *vcpu)
                        kvm_complete_insn_gp(vcpu, err);
                        return 1;
                case 4:
-                       err = kvm_set_cr4(vcpu, val);
+                       err = handle_set_cr4(vcpu, val);
                        kvm_complete_insn_gp(vcpu, err);
                        return 1;
                case 8: {
@@ -4072,7 +4538,7 @@ static int handle_cr(struct kvm_vcpu *vcpu)
                };
                break;
        case 2: /* clts */
-               vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
+               handle_clts(vcpu);
                trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
                skip_emulated_instruction(vcpu);
                vmx_fpu_activate(vcpu);
@@ -4104,7 +4570,7 @@ static int handle_cr(struct kvm_vcpu *vcpu)
                break;
        }
        vcpu->run->exit_reason = 0;
-       pr_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
+       vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
               (int)(exit_qualification >> 4) & 3, cr);
        return 0;
 }
@@ -4248,12 +4714,6 @@ static int handle_vmcall(struct kvm_vcpu *vcpu)
        return 1;
 }
 
-static int handle_vmx_insn(struct kvm_vcpu *vcpu)
-{
-       kvm_queue_exception(vcpu, UD_VECTOR);
-       return 1;
-}
-
 static int handle_invd(struct kvm_vcpu *vcpu)
 {
        return emulate_instruction(vcpu, 0) == EMULATE_DONE;
@@ -4268,6 +4728,16 @@ static int handle_invlpg(struct kvm_vcpu *vcpu)
        return 1;
 }
 
+static int handle_rdpmc(struct kvm_vcpu *vcpu)
+{
+       int err;
+
+       err = kvm_rdpmc(vcpu);
+       kvm_complete_insn_gp(vcpu, err);
+
+       return 1;
+}
+
 static int handle_wbinvd(struct kvm_vcpu *vcpu)
 {
        skip_emulated_instruction(vcpu);
@@ -4287,6 +4757,24 @@ static int handle_xsetbv(struct kvm_vcpu *vcpu)
 
 static int handle_apic_access(struct kvm_vcpu *vcpu)
 {
+       if (likely(fasteoi)) {
+               unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
+               int access_type, offset;
+
+               access_type = exit_qualification & APIC_ACCESS_TYPE;
+               offset = exit_qualification & APIC_ACCESS_OFFSET;
+               /*
+                * Sane guest uses MOV to write EOI, with written value
+                * not cared. So make a short-circuit here by avoiding
+                * heavy instruction emulation.
+                */
+               if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
+                   (offset == APIC_EOI)) {
+                       kvm_lapic_set_eoi(vcpu);
+                       skip_emulated_instruction(vcpu);
+                       return 1;
+               }
+       }
        return emulate_instruction(vcpu, 0) == EMULATE_DONE;
 }
 
@@ -4297,9 +4785,10 @@ static int handle_task_switch(struct kvm_vcpu *vcpu)
        bool has_error_code = false;
        u32 error_code = 0;
        u16 tss_selector;
-       int reason, type, idt_v;
+       int reason, type, idt_v, idt_index;
 
        idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
+       idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
        type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
 
        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
@@ -4337,8 +4826,9 @@ static int handle_task_switch(struct kvm_vcpu *vcpu)
                       type != INTR_TYPE_NMI_INTR))
                skip_emulated_instruction(vcpu);
 
-       if (kvm_task_switch(vcpu, tss_selector, reason,
-                               has_error_code, error_code) == EMULATE_FAIL) {
+       if (kvm_task_switch(vcpu, tss_selector,
+                           type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
+                           has_error_code, error_code) == EMULATE_FAIL) {
                vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
                vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
                vcpu->run->internal.ndata = 0;
@@ -4360,6 +4850,7 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)
 {
        unsigned long exit_qualification;
        gpa_t gpa;
+       u32 error_code;
        int gla_validity;
 
        exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
@@ -4384,7 +4875,13 @@ static int handle_ept_violation(struct kvm_vcpu *vcpu)
 
        gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
        trace_kvm_page_fault(gpa, exit_qualification);
-       return kvm_mmu_page_fault(vcpu, gpa, exit_qualification & 0x3, NULL, 0);
+
+       /* It is a write fault? */
+       error_code = exit_qualification & (1U << 1);
+       /* ept page table is present? */
+       error_code |= (exit_qualification >> 3) & 0x1;
+
+       return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
 }
 
 static u64 ept_rsvd_mask(u64 spte, int level)
@@ -4451,11 +4948,19 @@ static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte,
 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
 {
        u64 sptes[4];
-       int nr_sptes, i;
+       int nr_sptes, i, ret;
        gpa_t gpa;
 
        gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
 
+       ret = handle_mmio_page_fault_common(vcpu, gpa, true);
+       if (likely(ret == 1))
+               return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
+                                             EMULATE_DONE;
+       if (unlikely(!ret))
+               return 1;
+
+       /* It is the real ept misconfig */
        printk(KERN_ERR "EPT: Misconfiguration.\n");
        printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa);
 
@@ -4491,15 +4996,18 @@ static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
        int ret = 1;
        u32 cpu_exec_ctrl;
        bool intr_window_requested;
+       unsigned count = 130;
 
        cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
        intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
 
-       while (!guest_state_valid(vcpu)) {
-               if (intr_window_requested
-                   && (kvm_get_rflags(&vmx->vcpu) & X86_EFLAGS_IF))
+       while (!guest_state_valid(vcpu) && count-- != 0) {
+               if (intr_window_requested && vmx_interrupt_allowed(vcpu))
                        return handle_interrupt_window(&vmx->vcpu);
 
+               if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
+                       return 1;
+
                err = emulate_instruction(vcpu, 0);
 
                if (err == EMULATE_DO_MMIO) {
@@ -4507,8 +5015,12 @@ static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
                        goto out;
                }
 
-               if (err != EMULATE_DONE)
+               if (err != EMULATE_DONE) {
+                       vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
+                       vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
+                       vcpu->run->internal.ndata = 0;
                        return 0;
+               }
 
                if (signal_pending(current))
                        goto out;
@@ -4516,7 +5028,7 @@ static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
                        schedule();
        }
 
-       vmx->emulation_required = 0;
+       vmx->emulation_required = !guest_state_valid(vcpu);
 out:
        return ret;
 }
@@ -4712,6 +5224,11 @@ static void free_nested(struct vcpu_vmx *vmx)
                vmx->nested.current_vmptr = -1ull;
                vmx->nested.current_vmcs12 = NULL;
        }
+       /* Unpin physical memory we referred to in current vmcs02 */
+       if (vmx->nested.apic_access_page) {
+               nested_release_page(vmx->nested.apic_access_page);
+               vmx->nested.apic_access_page = 0;
+       }
 
        nested_free_all_saved_vmcss(vmx);
 }
@@ -4877,6 +5394,21 @@ static int handle_vmclear(struct kvm_vcpu *vcpu)
        return 1;
 }
 
+static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
+
+/* Emulate the VMLAUNCH instruction */
+static int handle_vmlaunch(struct kvm_vcpu *vcpu)
+{
+       return nested_vmx_run(vcpu, true);
+}
+
+/* Emulate the VMRESUME instruction */
+static int handle_vmresume(struct kvm_vcpu *vcpu)
+{
+
+       return nested_vmx_run(vcpu, false);
+}
+
 enum vmcs_field_type {
        VMCS_FIELD_TYPE_U16 = 0,
        VMCS_FIELD_TYPE_U64 = 1,
@@ -5172,13 +5704,14 @@ static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
        [EXIT_REASON_HLT]                     = handle_halt,
        [EXIT_REASON_INVD]                    = handle_invd,
        [EXIT_REASON_INVLPG]                  = handle_invlpg,
+       [EXIT_REASON_RDPMC]                   = handle_rdpmc,
        [EXIT_REASON_VMCALL]                  = handle_vmcall,
        [EXIT_REASON_VMCLEAR]                 = handle_vmclear,
-       [EXIT_REASON_VMLAUNCH]                = handle_vmx_insn,
+       [EXIT_REASON_VMLAUNCH]                = handle_vmlaunch,
        [EXIT_REASON_VMPTRLD]                 = handle_vmptrld,
        [EXIT_REASON_VMPTRST]                 = handle_vmptrst,
        [EXIT_REASON_VMREAD]                  = handle_vmread,
-       [EXIT_REASON_VMRESUME]                = handle_vmx_insn,
+       [EXIT_REASON_VMRESUME]                = handle_vmresume,
        [EXIT_REASON_VMWRITE]                 = handle_vmwrite,
        [EXIT_REASON_VMOFF]                   = handle_vmoff,
        [EXIT_REASON_VMON]                    = handle_vmon,
@@ -5198,6 +5731,229 @@ static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
 static const int kvm_vmx_max_exit_handlers =
        ARRAY_SIZE(kvm_vmx_exit_handlers);
 
+/*
+ * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
+ * rather than handle it ourselves in L0. I.e., check whether L1 expressed
+ * disinterest in the current event (read or write a specific MSR) by using an
+ * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
+ */
+static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
+       struct vmcs12 *vmcs12, u32 exit_reason)
+{
+       u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
+       gpa_t bitmap;
+
+       if (!nested_cpu_has(get_vmcs12(vcpu), CPU_BASED_USE_MSR_BITMAPS))
+               return 1;
+
+       /*
+        * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
+        * for the four combinations of read/write and low/high MSR numbers.
+        * First we need to figure out which of the four to use:
+        */
+       bitmap = vmcs12->msr_bitmap;
+       if (exit_reason == EXIT_REASON_MSR_WRITE)
+               bitmap += 2048;
+       if (msr_index >= 0xc0000000) {
+               msr_index -= 0xc0000000;
+               bitmap += 1024;
+       }
+
+       /* Then read the msr_index'th bit from this bitmap: */
+       if (msr_index < 1024*8) {
+               unsigned char b;
+               kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1);
+               return 1 & (b >> (msr_index & 7));
+       } else
+               return 1; /* let L1 handle the wrong parameter */
+}
+
+/*
+ * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
+ * rather than handle it ourselves in L0. I.e., check if L1 wanted to
+ * intercept (via guest_host_mask etc.) the current event.
+ */
+static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
+       struct vmcs12 *vmcs12)
+{
+       unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
+       int cr = exit_qualification & 15;
+       int reg = (exit_qualification >> 8) & 15;
+       unsigned long val = kvm_register_read(vcpu, reg);
+
+       switch ((exit_qualification >> 4) & 3) {
+       case 0: /* mov to cr */
+               switch (cr) {
+               case 0:
+                       if (vmcs12->cr0_guest_host_mask &
+                           (val ^ vmcs12->cr0_read_shadow))
+                               return 1;
+                       break;
+               case 3:
+                       if ((vmcs12->cr3_target_count >= 1 &&
+                                       vmcs12->cr3_target_value0 == val) ||
+                               (vmcs12->cr3_target_count >= 2 &&
+                                       vmcs12->cr3_target_value1 == val) ||
+                               (vmcs12->cr3_target_count >= 3 &&
+                                       vmcs12->cr3_target_value2 == val) ||
+                               (vmcs12->cr3_target_count >= 4 &&
+                                       vmcs12->cr3_target_value3 == val))
+                               return 0;
+                       if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
+                               return 1;
+                       break;
+               case 4:
+                       if (vmcs12->cr4_guest_host_mask &
+                           (vmcs12->cr4_read_shadow ^ val))
+                               return 1;
+                       break;
+               case 8:
+                       if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
+                               return 1;
+                       break;
+               }
+               break;
+       case 2: /* clts */
+               if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
+                   (vmcs12->cr0_read_shadow & X86_CR0_TS))
+                       return 1;
+               break;
+       case 1: /* mov from cr */
+               switch (cr) {
+               case 3:
+                       if (vmcs12->cpu_based_vm_exec_control &
+                           CPU_BASED_CR3_STORE_EXITING)
+                               return 1;
+                       break;
+               case 8:
+                       if (vmcs12->cpu_based_vm_exec_control &
+                           CPU_BASED_CR8_STORE_EXITING)
+                               return 1;
+                       break;
+               }
+               break;
+       case 3: /* lmsw */
+               /*
+                * lmsw can change bits 1..3 of cr0, and only set bit 0 of
+                * cr0. Other attempted changes are ignored, with no exit.
+                */
+               if (vmcs12->cr0_guest_host_mask & 0xe &
+                   (val ^ vmcs12->cr0_read_shadow))
+                       return 1;
+               if ((vmcs12->cr0_guest_host_mask & 0x1) &&
+                   !(vmcs12->cr0_read_shadow & 0x1) &&
+                   (val & 0x1))
+                       return 1;
+               break;
+       }
+       return 0;
+}
+
+/*
+ * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
+ * should handle it ourselves in L0 (and then continue L2). Only call this
+ * when in is_guest_mode (L2).
+ */
+static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
+{
+       u32 exit_reason = vmcs_read32(VM_EXIT_REASON);
+       u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
+       struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+
+       if (vmx->nested.nested_run_pending)
+               return 0;
+
+       if (unlikely(vmx->fail)) {
+               pr_info_ratelimited("%s failed vm entry %x\n", __func__,
+                                   vmcs_read32(VM_INSTRUCTION_ERROR));
+               return 1;
+       }
+
+       switch (exit_reason) {
+       case EXIT_REASON_EXCEPTION_NMI:
+               if (!is_exception(intr_info))
+                       return 0;
+               else if (is_page_fault(intr_info))
+                       return enable_ept;
+               return vmcs12->exception_bitmap &
+                               (1u << (intr_info & INTR_INFO_VECTOR_MASK));
+       case EXIT_REASON_EXTERNAL_INTERRUPT:
+               return 0;
+       case EXIT_REASON_TRIPLE_FAULT:
+               return 1;
+       case EXIT_REASON_PENDING_INTERRUPT:
+       case EXIT_REASON_NMI_WINDOW:
+               /*
+                * prepare_vmcs02() set the CPU_BASED_VIRTUAL_INTR_PENDING bit
+                * (aka Interrupt Window Exiting) only when L1 turned it on,
+                * so if we got a PENDING_INTERRUPT exit, this must be for L1.
+                * Same for NMI Window Exiting.
+                */
+               return 1;
+       case EXIT_REASON_TASK_SWITCH:
+               return 1;
+       case EXIT_REASON_CPUID:
+               return 1;
+       case EXIT_REASON_HLT:
+               return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
+       case EXIT_REASON_INVD:
+               return 1;
+       case EXIT_REASON_INVLPG:
+               return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
+       case EXIT_REASON_RDPMC:
+               return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
+       case EXIT_REASON_RDTSC:
+               return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
+       case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
+       case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
+       case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
+       case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
+       case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
+               /*
+                * VMX instructions trap unconditionally. This allows L1 to
+                * emulate them for its L2 guest, i.e., allows 3-level nesting!
+                */
+               return 1;
+       case EXIT_REASON_CR_ACCESS:
+               return nested_vmx_exit_handled_cr(vcpu, vmcs12);
+       case EXIT_REASON_DR_ACCESS:
+               return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
+       case EXIT_REASON_IO_INSTRUCTION:
+               /* TODO: support IO bitmaps */
+               return 1;
+       case EXIT_REASON_MSR_READ:
+       case EXIT_REASON_MSR_WRITE:
+               return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
+       case EXIT_REASON_INVALID_STATE:
+               return 1;
+       case EXIT_REASON_MWAIT_INSTRUCTION:
+               return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
+       case EXIT_REASON_MONITOR_INSTRUCTION:
+               return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
+       case EXIT_REASON_PAUSE_INSTRUCTION:
+               return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
+                       nested_cpu_has2(vmcs12,
+                               SECONDARY_EXEC_PAUSE_LOOP_EXITING);
+       case EXIT_REASON_MCE_DURING_VMENTRY:
+               return 0;
+       case EXIT_REASON_TPR_BELOW_THRESHOLD:
+               return 1;
+       case EXIT_REASON_APIC_ACCESS:
+               return nested_cpu_has2(vmcs12,
+                       SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
+       case EXIT_REASON_EPT_VIOLATION:
+       case EXIT_REASON_EPT_MISCONFIG:
+               return 0;
+       case EXIT_REASON_WBINVD:
+               return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
+       case EXIT_REASON_XSETBV:
+               return 1;
+       default:
+               return 1;
+       }
+}
+
 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
 {
        *info1 = vmcs_readl(EXIT_QUALIFICATION);
@@ -5214,12 +5970,29 @@ static int vmx_handle_exit(struct kvm_vcpu *vcpu)
        u32 exit_reason = vmx->exit_reason;
        u32 vectoring_info = vmx->idt_vectoring_info;
 
-       trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
-
        /* If guest state is invalid, start emulating */
        if (vmx->emulation_required && emulate_invalid_guest_state)
                return handle_invalid_guest_state(vcpu);
 
+       /*
+        * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
+        * we did not inject a still-pending event to L1 now because of
+        * nested_run_pending, we need to re-enable this bit.
+        */
+       if (vmx->nested.nested_run_pending)
+               kvm_make_request(KVM_REQ_EVENT, vcpu);
+
+       if (!is_guest_mode(vcpu) && (exit_reason == EXIT_REASON_VMLAUNCH ||
+           exit_reason == EXIT_REASON_VMRESUME))
+               vmx->nested.nested_run_pending = 1;
+       else
+               vmx->nested.nested_run_pending = 0;
+
+       if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
+               nested_vmx_vmexit(vcpu);
+               return 1;
+       }
+
        if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
                vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
                vcpu->run->fail_entry.hardware_entry_failure_reason
@@ -5242,7 +6015,9 @@ static int vmx_handle_exit(struct kvm_vcpu *vcpu)
                       "(0x%x) and exit reason is 0x%x\n",
                       __func__, vectoring_info, exit_reason);
 
-       if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked)) {
+       if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
+           !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
+                                       get_vmcs12(vcpu), vcpu)))) {
                if (vmx_interrupt_allowed(vcpu)) {
                        vmx->soft_vnmi_blocked = 0;
                } else if (vmx->vnmi_blocked_time > 1000000000LL &&
@@ -5405,6 +6180,8 @@ static void __vmx_complete_interrupts(struct vcpu_vmx *vmx,
 
 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
 {
+       if (is_guest_mode(&vmx->vcpu))
+               return;
        __vmx_complete_interrupts(vmx, vmx->idt_vectoring_info,
                                  VM_EXIT_INSTRUCTION_LEN,
                                  IDT_VECTORING_ERROR_CODE);
@@ -5412,6 +6189,8 @@ static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
 
 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
 {
+       if (is_guest_mode(vcpu))
+               return;
        __vmx_complete_interrupts(to_vmx(vcpu),
                                  vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
                                  VM_ENTRY_INSTRUCTION_LEN,
@@ -5420,6 +6199,24 @@ static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
 }
 
+static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
+{
+       int i, nr_msrs;
+       struct perf_guest_switch_msr *msrs;
+
+       msrs = perf_guest_get_msrs(&nr_msrs);
+
+       if (!msrs)
+               return;
+
+       for (i = 0; i < nr_msrs; i++)
+               if (msrs[i].host == msrs[i].guest)
+                       clear_atomic_switch_msr(vmx, msrs[i].msr);
+               else
+                       add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
+                                       msrs[i].host);
+}
+
 #ifdef CONFIG_X86_64
 #define R "r"
 #define Q "q"
@@ -5431,6 +6228,22 @@ static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
 {
        struct vcpu_vmx *vmx = to_vmx(vcpu);
+       unsigned long debugctlmsr;
+
+       if (is_guest_mode(vcpu) && !vmx->nested.nested_run_pending) {
+               struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+               if (vmcs12->idt_vectoring_info_field &
+                               VECTORING_INFO_VALID_MASK) {
+                       vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
+                               vmcs12->idt_vectoring_info_field);
+                       vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
+                               vmcs12->vm_exit_instruction_len);
+                       if (vmcs12->idt_vectoring_info_field &
+                                       VECTORING_INFO_DELIVER_CODE_MASK)
+                               vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
+                                       vmcs12->idt_vectoring_error_code);
+               }
+       }
 
        /* Record the guest's net vcpu time for enforced NMI injections. */
        if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
@@ -5454,6 +6267,9 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
        if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
                vmx_set_interrupt_shadow(vcpu, 0);
 
+       atomic_switch_perf_msrs(vmx);
+       debugctlmsr = get_debugctlmsr();
+
        vmx->__launched = vmx->loaded_vmcs->launched;
        asm(
                /* Store host registers */
@@ -5554,6 +6370,23 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
 #endif
              );
 
+       /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
+       if (debugctlmsr)
+               update_debugctlmsr(debugctlmsr);
+
+#ifndef CONFIG_X86_64
+       /*
+        * The sysexit path does not restore ds/es, so we must set them to
+        * a reasonable value ourselves.
+        *
+        * We can't defer this to vmx_load_host_state() since that function
+        * may be executed in interrupt context, which saves and restore segments
+        * around it, nullifying its effect.
+        */
+       loadsegment(ds, __USER_DS);
+       loadsegment(es, __USER_DS);
+#endif
+
        vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
                                  | (1 << VCPU_EXREG_RFLAGS)
                                  | (1 << VCPU_EXREG_CPL)
@@ -5564,10 +6397,21 @@ static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
 
        vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
 
-       asm("mov %0, %%ds; mov %0, %%es" : : "r"(__USER_DS));
+       if (is_guest_mode(vcpu)) {
+               struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+               vmcs12->idt_vectoring_info_field = vmx->idt_vectoring_info;
+               if (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK) {
+                       vmcs12->idt_vectoring_error_code =
+                               vmcs_read32(IDT_VECTORING_ERROR_CODE);
+                       vmcs12->vm_exit_instruction_len =
+                               vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
+               }
+       }
+
        vmx->loaded_vmcs->launched = 1;
 
        vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
+       trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
 
        vmx_complete_atomic_exit(vmx);
        vmx_recover_nmi_blocking(vmx);
@@ -5650,7 +6494,7 @@ static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
        return &vmx->vcpu;
 
 free_vmcs:
-       free_vmcs(vmx->loaded_vmcs->vmcs);
+       free_loaded_vmcs(vmx->loaded_vmcs);
 free_msrs:
        kfree(vmx->guest_msrs);
 uninit_vcpu:
@@ -5708,49 +6552,6 @@ static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
        return ret;
 }
 
-#define _ER(x) { EXIT_REASON_##x, #x }
-
-static const struct trace_print_flags vmx_exit_reasons_str[] = {
-       _ER(EXCEPTION_NMI),
-       _ER(EXTERNAL_INTERRUPT),
-       _ER(TRIPLE_FAULT),
-       _ER(PENDING_INTERRUPT),
-       _ER(NMI_WINDOW),
-       _ER(TASK_SWITCH),
-       _ER(CPUID),
-       _ER(HLT),
-       _ER(INVLPG),
-       _ER(RDPMC),
-       _ER(RDTSC),
-       _ER(VMCALL),
-       _ER(VMCLEAR),
-       _ER(VMLAUNCH),
-       _ER(VMPTRLD),
-       _ER(VMPTRST),
-       _ER(VMREAD),
-       _ER(VMRESUME),
-       _ER(VMWRITE),
-       _ER(VMOFF),
-       _ER(VMON),
-       _ER(CR_ACCESS),
-       _ER(DR_ACCESS),
-       _ER(IO_INSTRUCTION),
-       _ER(MSR_READ),
-       _ER(MSR_WRITE),
-       _ER(MWAIT_INSTRUCTION),
-       _ER(MONITOR_INSTRUCTION),
-       _ER(PAUSE_INSTRUCTION),
-       _ER(MCE_DURING_VMENTRY),
-       _ER(TPR_BELOW_THRESHOLD),
-       _ER(APIC_ACCESS),
-       _ER(EPT_VIOLATION),
-       _ER(EPT_MISCONFIG),
-       _ER(WBINVD),
-       { -1, NULL }
-};
-
-#undef _ER
-
 static int vmx_get_lpage_level(void)
 {
        if (enable_ept && !cpu_has_vmx_ept_1g_page())
@@ -5780,10 +6581,673 @@ static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
                        }
                }
        }
+
+       exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
+       /* Exposing INVPCID only when PCID is exposed */
+       best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
+       if (vmx_invpcid_supported() &&
+           best && (best->ecx & bit(X86_FEATURE_INVPCID)) &&
+           guest_cpuid_has_pcid(vcpu)) {
+               exec_control |= SECONDARY_EXEC_ENABLE_INVPCID;
+               vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
+                            exec_control);
+       } else {
+               exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
+               vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
+                            exec_control);
+               if (best)
+                       best->ecx &= ~bit(X86_FEATURE_INVPCID);
+       }
 }
 
 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
 {
+       if (func == 1 && nested)
+               entry->ecx |= bit(X86_FEATURE_VMX);
+}
+
+/*
+ * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
+ * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
+ * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2
+ * guest in a way that will both be appropriate to L1's requests, and our
+ * needs. In addition to modifying the active vmcs (which is vmcs02), this
+ * function also has additional necessary side-effects, like setting various
+ * vcpu->arch fields.
+ */
+static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
+{
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
+       u32 exec_control;
+
+       vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
+       vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
+       vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
+       vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
+       vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
+       vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
+       vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
+       vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
+       vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
+       vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
+       vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
+       vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
+       vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
+       vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
+       vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
+       vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
+       vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
+       vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
+       vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
+       vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
+       vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
+       vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
+       vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
+       vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
+       vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
+       vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
+       vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
+       vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
+       vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
+       vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
+       vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
+       vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
+       vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
+       vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
+       vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
+       vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
+
+       vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
+       vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
+               vmcs12->vm_entry_intr_info_field);
+       vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
+               vmcs12->vm_entry_exception_error_code);
+       vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
+               vmcs12->vm_entry_instruction_len);
+       vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
+               vmcs12->guest_interruptibility_info);
+       vmcs_write32(GUEST_ACTIVITY_STATE, vmcs12->guest_activity_state);
+       vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
+       vmcs_writel(GUEST_DR7, vmcs12->guest_dr7);
+       vmcs_writel(GUEST_RFLAGS, vmcs12->guest_rflags);
+       vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
+               vmcs12->guest_pending_dbg_exceptions);
+       vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
+       vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
+
+       vmcs_write64(VMCS_LINK_POINTER, -1ull);
+
+       vmcs_write32(PIN_BASED_VM_EXEC_CONTROL,
+               (vmcs_config.pin_based_exec_ctrl |
+                vmcs12->pin_based_vm_exec_control));
+
+       /*
+        * Whether page-faults are trapped is determined by a combination of
+        * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
+        * If enable_ept, L0 doesn't care about page faults and we should
+        * set all of these to L1's desires. However, if !enable_ept, L0 does
+        * care about (at least some) page faults, and because it is not easy
+        * (if at all possible?) to merge L0 and L1's desires, we simply ask
+        * to exit on each and every L2 page fault. This is done by setting
+        * MASK=MATCH=0 and (see below) EB.PF=1.
+        * Note that below we don't need special code to set EB.PF beyond the
+        * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
+        * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
+        * !enable_ept, EB.PF is 1, so the "or" will always be 1.
+        *
+        * A problem with this approach (when !enable_ept) is that L1 may be
+        * injected with more page faults than it asked for. This could have
+        * caused problems, but in practice existing hypervisors don't care.
+        * To fix this, we will need to emulate the PFEC checking (on the L1
+        * page tables), using walk_addr(), when injecting PFs to L1.
+        */
+       vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
+               enable_ept ? vmcs12->page_fault_error_code_mask : 0);
+       vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
+               enable_ept ? vmcs12->page_fault_error_code_match : 0);
+
+       if (cpu_has_secondary_exec_ctrls()) {
+               u32 exec_control = vmx_secondary_exec_control(vmx);
+               if (!vmx->rdtscp_enabled)
+                       exec_control &= ~SECONDARY_EXEC_RDTSCP;
+               /* Take the following fields only from vmcs12 */
+               exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
+               if (nested_cpu_has(vmcs12,
+                               CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
+                       exec_control |= vmcs12->secondary_vm_exec_control;
+
+               if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
+                       /*
+                        * Translate L1 physical address to host physical
+                        * address for vmcs02. Keep the page pinned, so this
+                        * physical address remains valid. We keep a reference
+                        * to it so we can release it later.
+                        */
+                       if (vmx->nested.apic_access_page) /* shouldn't happen */
+                               nested_release_page(vmx->nested.apic_access_page);
+                       vmx->nested.apic_access_page =
+                               nested_get_page(vcpu, vmcs12->apic_access_addr);
+                       /*
+                        * If translation failed, no matter: This feature asks
+                        * to exit when accessing the given address, and if it
+                        * can never be accessed, this feature won't do
+                        * anything anyway.
+                        */
+                       if (!vmx->nested.apic_access_page)
+                               exec_control &=
+                                 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
+                       else
+                               vmcs_write64(APIC_ACCESS_ADDR,
+                                 page_to_phys(vmx->nested.apic_access_page));
+               }
+
+               vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
+       }
+
+
+       /*
+        * Set host-state according to L0's settings (vmcs12 is irrelevant here)
+        * Some constant fields are set here by vmx_set_constant_host_state().
+        * Other fields are different per CPU, and will be set later when
+        * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
+        */
+       vmx_set_constant_host_state();
+
+       /*
+        * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
+        * entry, but only if the current (host) sp changed from the value
+        * we wrote last (vmx->host_rsp). This cache is no longer relevant
+        * if we switch vmcs, and rather than hold a separate cache per vmcs,
+        * here we just force the write to happen on entry.
+        */
+       vmx->host_rsp = 0;
+
+       exec_control = vmx_exec_control(vmx); /* L0's desires */
+       exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
+       exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
+       exec_control &= ~CPU_BASED_TPR_SHADOW;
+       exec_control |= vmcs12->cpu_based_vm_exec_control;
+       /*
+        * Merging of IO and MSR bitmaps not currently supported.
+        * Rather, exit every time.
+        */
+       exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
+       exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
+       exec_control |= CPU_BASED_UNCOND_IO_EXITING;
+
+       vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
+
+       /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
+        * bitwise-or of what L1 wants to trap for L2, and what we want to
+        * trap. Note that CR0.TS also needs updating - we do this later.
+        */
+       update_exception_bitmap(vcpu);
+       vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
+       vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
+
+       /* Note: IA32_MODE, LOAD_IA32_EFER are modified by vmx_set_efer below */
+       vmcs_write32(VM_EXIT_CONTROLS,
+               vmcs12->vm_exit_controls | vmcs_config.vmexit_ctrl);
+       vmcs_write32(VM_ENTRY_CONTROLS, vmcs12->vm_entry_controls |
+               (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
+
+       if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)
+               vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
+       else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
+               vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
+
+
+       set_cr4_guest_host_mask(vmx);
+
+       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
+               vmcs_write64(TSC_OFFSET,
+                       vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset);
+       else
+               vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
+
+       if (enable_vpid) {
+               /*
+                * Trivially support vpid by letting L2s share their parent
+                * L1's vpid. TODO: move to a more elaborate solution, giving
+                * each L2 its own vpid and exposing the vpid feature to L1.
+                */
+               vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
+               vmx_flush_tlb(vcpu);
+       }
+
+       if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
+               vcpu->arch.efer = vmcs12->guest_ia32_efer;
+       if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
+               vcpu->arch.efer |= (EFER_LMA | EFER_LME);
+       else
+               vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
+       /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
+       vmx_set_efer(vcpu, vcpu->arch.efer);
+
+       /*
+        * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
+        * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
+        * The CR0_READ_SHADOW is what L2 should have expected to read given
+        * the specifications by L1; It's not enough to take
+        * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
+        * have more bits than L1 expected.
+        */
+       vmx_set_cr0(vcpu, vmcs12->guest_cr0);
+       vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
+
+       vmx_set_cr4(vcpu, vmcs12->guest_cr4);
+       vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
+
+       /* shadow page tables on either EPT or shadow page tables */
+       kvm_set_cr3(vcpu, vmcs12->guest_cr3);
+       kvm_mmu_reset_context(vcpu);
+
+       kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
+       kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
+}
+
+/*
+ * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
+ * for running an L2 nested guest.
+ */
+static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
+{
+       struct vmcs12 *vmcs12;
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
+       int cpu;
+       struct loaded_vmcs *vmcs02;
+
+       if (!nested_vmx_check_permission(vcpu) ||
+           !nested_vmx_check_vmcs12(vcpu))
+               return 1;
+
+       skip_emulated_instruction(vcpu);
+       vmcs12 = get_vmcs12(vcpu);
+
+       /*
+        * The nested entry process starts with enforcing various prerequisites
+        * on vmcs12 as required by the Intel SDM, and act appropriately when
+        * they fail: As the SDM explains, some conditions should cause the
+        * instruction to fail, while others will cause the instruction to seem
+        * to succeed, but return an EXIT_REASON_INVALID_STATE.
+        * To speed up the normal (success) code path, we should avoid checking
+        * for misconfigurations which will anyway be caught by the processor
+        * when using the merged vmcs02.
+        */
+       if (vmcs12->launch_state == launch) {
+               nested_vmx_failValid(vcpu,
+                       launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
+                              : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
+               return 1;
+       }
+
+       if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) &&
+                       !IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) {
+               /*TODO: Also verify bits beyond physical address width are 0*/
+               nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
+               return 1;
+       }
+
+       if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
+                       !IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) {
+               /*TODO: Also verify bits beyond physical address width are 0*/
+               nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
+               return 1;
+       }
+
+       if (vmcs12->vm_entry_msr_load_count > 0 ||
+           vmcs12->vm_exit_msr_load_count > 0 ||
+           vmcs12->vm_exit_msr_store_count > 0) {
+               pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n",
+                                   __func__);
+               nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
+               return 1;
+       }
+
+       if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
+             nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) ||
+           !vmx_control_verify(vmcs12->secondary_vm_exec_control,
+             nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) ||
+           !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
+             nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) ||
+           !vmx_control_verify(vmcs12->vm_exit_controls,
+             nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) ||
+           !vmx_control_verify(vmcs12->vm_entry_controls,
+             nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high))
+       {
+               nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
+               return 1;
+       }
+
+       if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
+           ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
+               nested_vmx_failValid(vcpu,
+                       VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
+               return 1;
+       }
+
+       if (((vmcs12->guest_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
+           ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
+               nested_vmx_entry_failure(vcpu, vmcs12,
+                       EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
+               return 1;
+       }
+       if (vmcs12->vmcs_link_pointer != -1ull) {
+               nested_vmx_entry_failure(vcpu, vmcs12,
+                       EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
+               return 1;
+       }
+
+       /*
+        * We're finally done with prerequisite checking, and can start with
+        * the nested entry.
+        */
+
+       vmcs02 = nested_get_current_vmcs02(vmx);
+       if (!vmcs02)
+               return -ENOMEM;
+
+       enter_guest_mode(vcpu);
+
+       vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET);
+
+       cpu = get_cpu();
+       vmx->loaded_vmcs = vmcs02;
+       vmx_vcpu_put(vcpu);
+       vmx_vcpu_load(vcpu, cpu);
+       vcpu->cpu = cpu;
+       put_cpu();
+
+       vmcs12->launch_state = 1;
+
+       prepare_vmcs02(vcpu, vmcs12);
+
+       /*
+        * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
+        * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
+        * returned as far as L1 is concerned. It will only return (and set
+        * the success flag) when L2 exits (see nested_vmx_vmexit()).
+        */
+       return 1;
+}
+
+/*
+ * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
+ * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
+ * This function returns the new value we should put in vmcs12.guest_cr0.
+ * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
+ *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
+ *     available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
+ *     didn't trap the bit, because if L1 did, so would L0).
+ *  2. Bits that L1 asked to trap (and therefore L0 also did) could not have
+ *     been modified by L2, and L1 knows it. So just leave the old value of
+ *     the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
+ *     isn't relevant, because if L0 traps this bit it can set it to anything.
+ *  3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
+ *     changed these bits, and therefore they need to be updated, but L0
+ *     didn't necessarily allow them to be changed in GUEST_CR0 - and rather
+ *     put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
+ */
+static inline unsigned long
+vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
+{
+       return
+       /*1*/   (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
+       /*2*/   (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
+       /*3*/   (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
+                       vcpu->arch.cr0_guest_owned_bits));
+}
+
+static inline unsigned long
+vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
+{
+       return
+       /*1*/   (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
+       /*2*/   (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
+       /*3*/   (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
+                       vcpu->arch.cr4_guest_owned_bits));
+}
+
+/*
+ * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
+ * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
+ * and this function updates it to reflect the changes to the guest state while
+ * L2 was running (and perhaps made some exits which were handled directly by L0
+ * without going back to L1), and to reflect the exit reason.
+ * Note that we do not have to copy here all VMCS fields, just those that
+ * could have changed by the L2 guest or the exit - i.e., the guest-state and
+ * exit-information fields only. Other fields are modified by L1 with VMWRITE,
+ * which already writes to vmcs12 directly.
+ */
+void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
+{
+       /* update guest state fields: */
+       vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
+       vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
+
+       kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
+       vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
+       vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
+       vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
+
+       vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
+       vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
+       vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
+       vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
+       vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
+       vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
+       vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
+       vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
+       vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
+       vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
+       vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
+       vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
+       vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
+       vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
+       vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
+       vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
+       vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
+       vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
+       vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
+       vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
+       vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
+       vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
+       vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
+       vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
+       vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
+       vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
+       vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
+       vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
+       vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
+       vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
+       vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
+       vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
+       vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
+       vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
+       vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
+       vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
+
+       vmcs12->guest_activity_state = vmcs_read32(GUEST_ACTIVITY_STATE);
+       vmcs12->guest_interruptibility_info =
+               vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
+       vmcs12->guest_pending_dbg_exceptions =
+               vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
+
+       /* TODO: These cannot have changed unless we have MSR bitmaps and
+        * the relevant bit asks not to trap the change */
+       vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
+       if (vmcs12->vm_entry_controls & VM_EXIT_SAVE_IA32_PAT)
+               vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
+       vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
+       vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
+       vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
+
+       /* update exit information fields: */
+
+       vmcs12->vm_exit_reason  = vmcs_read32(VM_EXIT_REASON);
+       vmcs12->exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
+
+       vmcs12->vm_exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
+       vmcs12->vm_exit_intr_error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
+       vmcs12->idt_vectoring_info_field =
+               vmcs_read32(IDT_VECTORING_INFO_FIELD);
+       vmcs12->idt_vectoring_error_code =
+               vmcs_read32(IDT_VECTORING_ERROR_CODE);
+       vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
+       vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
+
+       /* clear vm-entry fields which are to be cleared on exit */
+       if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
+               vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
+}
+
+/*
+ * A part of what we need to when the nested L2 guest exits and we want to
+ * run its L1 parent, is to reset L1's guest state to the host state specified
+ * in vmcs12.
+ * This function is to be called not only on normal nested exit, but also on
+ * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
+ * Failures During or After Loading Guest State").
+ * This function should be called when the active VMCS is L1's (vmcs01).
+ */
+void load_vmcs12_host_state(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
+{
+       if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
+               vcpu->arch.efer = vmcs12->host_ia32_efer;
+       if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
+               vcpu->arch.efer |= (EFER_LMA | EFER_LME);
+       else
+               vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
+       vmx_set_efer(vcpu, vcpu->arch.efer);
+
+       kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
+       kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
+       /*
+        * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
+        * actually changed, because it depends on the current state of
+        * fpu_active (which may have changed).
+        * Note that vmx_set_cr0 refers to efer set above.
+        */
+       kvm_set_cr0(vcpu, vmcs12->host_cr0);
+       /*
+        * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
+        * to apply the same changes to L1's vmcs. We just set cr0 correctly,
+        * but we also need to update cr0_guest_host_mask and exception_bitmap.
+        */
+       update_exception_bitmap(vcpu);
+       vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
+       vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
+
+       /*
+        * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
+        * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
+        */
+       vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
+       kvm_set_cr4(vcpu, vmcs12->host_cr4);
+
+       /* shadow page tables on either EPT or shadow page tables */
+       kvm_set_cr3(vcpu, vmcs12->host_cr3);
+       kvm_mmu_reset_context(vcpu);
+
+       if (enable_vpid) {
+               /*
+                * Trivially support vpid by letting L2s share their parent
+                * L1's vpid. TODO: move to a more elaborate solution, giving
+                * each L2 its own vpid and exposing the vpid feature to L1.
+                */
+               vmx_flush_tlb(vcpu);
+       }
+
+
+       vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
+       vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
+       vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
+       vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
+       vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
+       vmcs_writel(GUEST_TR_BASE, vmcs12->host_tr_base);
+       vmcs_writel(GUEST_GS_BASE, vmcs12->host_gs_base);
+       vmcs_writel(GUEST_FS_BASE, vmcs12->host_fs_base);
+       vmcs_write16(GUEST_ES_SELECTOR, vmcs12->host_es_selector);
+       vmcs_write16(GUEST_CS_SELECTOR, vmcs12->host_cs_selector);
+       vmcs_write16(GUEST_SS_SELECTOR, vmcs12->host_ss_selector);
+       vmcs_write16(GUEST_DS_SELECTOR, vmcs12->host_ds_selector);
+       vmcs_write16(GUEST_FS_SELECTOR, vmcs12->host_fs_selector);
+       vmcs_write16(GUEST_GS_SELECTOR, vmcs12->host_gs_selector);
+       vmcs_write16(GUEST_TR_SELECTOR, vmcs12->host_tr_selector);
+
+       if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT)
+               vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
+       if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
+               vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
+                       vmcs12->host_ia32_perf_global_ctrl);
+}
+
+/*
+ * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
+ * and modify vmcs12 to make it see what it would expect to see there if
+ * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
+ */
+static void nested_vmx_vmexit(struct kvm_vcpu *vcpu)
+{
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
+       int cpu;
+       struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+
+       leave_guest_mode(vcpu);
+       prepare_vmcs12(vcpu, vmcs12);
+
+       cpu = get_cpu();
+       vmx->loaded_vmcs = &vmx->vmcs01;
+       vmx_vcpu_put(vcpu);
+       vmx_vcpu_load(vcpu, cpu);
+       vcpu->cpu = cpu;
+       put_cpu();
+
+       /* if no vmcs02 cache requested, remove the one we used */
+       if (VMCS02_POOL_SIZE == 0)
+               nested_free_vmcs02(vmx, vmx->nested.current_vmptr);
+
+       load_vmcs12_host_state(vcpu, vmcs12);
+
+       /* Update TSC_OFFSET if TSC was changed while L2 ran */
+       vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset);
+
+       /* This is needed for same reason as it was needed in prepare_vmcs02 */
+       vmx->host_rsp = 0;
+
+       /* Unpin physical memory we referred to in vmcs02 */
+       if (vmx->nested.apic_access_page) {
+               nested_release_page(vmx->nested.apic_access_page);
+               vmx->nested.apic_access_page = 0;
+       }
+
+       /*
+        * Exiting from L2 to L1, we're now back to L1 which thinks it just
+        * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
+        * success or failure flag accordingly.
+        */
+       if (unlikely(vmx->fail)) {
+               vmx->fail = 0;
+               nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
+       } else
+               nested_vmx_succeed(vcpu);
+}
+
+/*
+ * L1's failure to enter L2 is a subset of a normal exit, as explained in
+ * 23.7 "VM-entry failures during or after loading guest state" (this also
+ * lists the acceptable exit-reason and exit-qualification parameters).
+ * It should only be called before L2 actually succeeded to run, and when
+ * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
+ */
+static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
+                       struct vmcs12 *vmcs12,
+                       u32 reason, unsigned long qualification)
+{
+       load_vmcs12_host_state(vcpu, vmcs12);
+       vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
+       vmcs12->exit_qualification = qualification;
+       nested_vmx_succeed(vcpu);
 }
 
 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
@@ -5862,13 +7326,13 @@ static struct kvm_x86_ops vmx_x86_ops = {
        .get_mt_mask = vmx_get_mt_mask,
 
        .get_exit_info = vmx_get_exit_info,
-       .exit_reasons_str = vmx_exit_reasons_str,
 
        .get_lpage_level = vmx_get_lpage_level,
 
        .cpuid_update = vmx_cpuid_update,
 
        .rdtscp_supported = vmx_rdtscp_supported,
+       .invpcid_supported = vmx_invpcid_supported,
 
        .set_supported_cpuid = vmx_set_supported_cpuid,
 
@@ -5878,6 +7342,7 @@ static struct kvm_x86_ops vmx_x86_ops = {
        .write_tsc_offset = vmx_write_tsc_offset,
        .adjust_tsc_offset = vmx_adjust_tsc_offset,
        .compute_tsc_offset = vmx_compute_tsc_offset,
+       .read_l1_tsc = vmx_read_l1_tsc,
 
        .set_tdp_cr3 = vmx_set_cr3,
 
@@ -5897,23 +7362,21 @@ static int __init vmx_init(void)
        if (!vmx_io_bitmap_a)
                return -ENOMEM;
 
+       r = -ENOMEM;
+
        vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
-       if (!vmx_io_bitmap_b) {
-               r = -ENOMEM;
+       if (!vmx_io_bitmap_b)
                goto out;
-       }
 
        vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL);
-       if (!vmx_msr_bitmap_legacy) {
-               r = -ENOMEM;
+       if (!vmx_msr_bitmap_legacy)
                goto out1;
-       }
+
 
        vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL);
-       if (!vmx_msr_bitmap_longmode) {
-               r = -ENOMEM;
+       if (!vmx_msr_bitmap_longmode)
                goto out2;
-       }
+
 
        /*
         * Allow direct access to the PC debug port (it is often used for I/O
@@ -5942,16 +7405,15 @@ static int __init vmx_init(void)
        vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false);
 
        if (enable_ept) {
-               bypass_guest_pf = 0;
-               kvm_mmu_set_mask_ptes(0ull, 0ull, 0ull, 0ull,
-                               VMX_EPT_EXECUTABLE_MASK);
+               kvm_mmu_set_mask_ptes(0ull,
+                       (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
+                       (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
+                       0ull, VMX_EPT_EXECUTABLE_MASK);
+               ept_set_mmio_spte_mask();
                kvm_enable_tdp();
        } else
                kvm_disable_tdp();
 
-       if (bypass_guest_pf)
-               kvm_mmu_set_nonpresent_ptes(~0xffeull, 0ull);
-
        return 0;
 
 out3: