return 0;
 }
 
+/*
+ * Forcibly leave nested mode in order to be able to reset the VCPU later on.
+ */
+void svm_leave_nested(struct vcpu_svm *svm)
+{
+       if (is_guest_mode(&svm->vcpu)) {
+               struct vmcb *hsave = svm->nested.hsave;
+               struct vmcb *vmcb = svm->vmcb;
+
+               svm->nested.nested_run_pending = 0;
+               leave_guest_mode(&svm->vcpu);
+               copy_vmcb_control_area(&vmcb->control, &hsave->control);
+               nested_svm_uninit_mmu_context(&svm->vcpu);
+       }
+}
+
 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
 {
        u32 offset, msr, value;
 
 
 void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
 {
+       struct vcpu_svm *svm = to_svm(vcpu);
        vcpu->arch.efer = efer;
 
        if (!npt_enabled) {
                        efer &= ~EFER_LME;
        }
 
-       to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
-       mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
+       if (!(efer & EFER_SVME)) {
+               svm_leave_nested(svm);
+               svm_set_gif(svm, true);
+       }
+
+       svm->vmcb->save.efer = efer | EFER_SVME;
+       mark_dirty(svm->vmcb, VMCB_CR);
 }
 
 static int is_external_interrupt(u32 info)
 
 
 void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
                          struct vmcb *nested_vmcb);
+void svm_leave_nested(struct vcpu_svm *svm);
 int nested_svm_vmrun(struct vcpu_svm *svm);
 void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb);
 int nested_svm_vmexit(struct vcpu_svm *svm);