Skip to contentSkip to conversation

KVM: x86: Event/exception fixes and cleanups

PATCH Superseded Sean Christopherson 2 participants 33 messages Jul 15, 2022 – Jul 18, 2022

Subsystems (4)

v2 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Sean Christopherson

author maintainer
#0 lore raw

v2 cover KVM: x86: Event/exception fixes and cleanups

The main goal of this series is to fix KVM's longstanding bug of not honoring L1's exception intercepts wants when handling an exception that occurs during delivery of a different exception. E.g. if L0 and L1 are using shadow paging, and L2 hits a #PF, and then hits another #PF while vectoring the first #PF due to _L1_ not having a shadow page for the IDT, KVM needs to check L1's intercepts before morphing the #PF => #PF => #DF so that the #PF is routed to L1, not injected into L2 as a #DF.

nVMX has hacked around the bug for years by overriding the #PF injector for shadow paging to go straight to VM-Exit, and nSVM has started doing the same. The hacks mostly work, but they're incomplete, confusing, and lead to other hacky code, e.g. bailing from the emulator because #PF injection forced a VM-Exit and suddenly KVM is back in L1.

Maxim, I believe I addressed all of your comments, holler if I missed something.

v2:
- Collect reviews. [Maxim, Jim]
- Split a few patches into more consumable chunks. [Maxim]
- Document that KVM doesn't correctly handle SMI+MTF (or SMI priority). [Maxim]
- Add comment to document the instruction boundary (event window) aspect of block_nested_events. [Maxim]
- Add a patch to rename inject_pending_events() and add a comment to document KVM's not-quite-architecturally-correct handing of instruction boundaries and asynchronous events. [Maxim]

v1: https://lore.kernel.org/all/[email protected]

Sean Christopherson (24):
KVM: nVMX: Unconditionally purge queued/injected events on nested

    "exit"
  KVM: VMX: Drop bits 31:16 when shoving exception error code into VMCS
  KVM: x86: Don't check for code breakpoints when emulating on exception
  KVM: nVMX: Treat General Detect #DB (DR7.GD=1) as fault-like
  KVM: nVMX: Prioritize TSS T-flag #DBs over Monitor Trap Flag
  KVM: x86: Treat #DBs from the emulator as fault-like (code and
    DR7.GD=1)

KVM: x86: Use DR7_GD macro instead of open coding check in emulator
KVM: nVMX: Ignore SIPI that arrives in L2 when vCPU is not in WFS
KVM: nVMX: Unconditionally clear mtf_pending on nested VM-Exit
KVM: VMX: Inject #PF on ENCLS as "emulated" #PF
KVM: x86: Rename kvm_x86_ops.queue_exception to inject_exception
KVM: x86: Make kvm_queued_exception a properly named, visible struct
KVM: x86: Formalize blocking of nested pending exceptions
KVM: x86: Use kvm_queue_exception_e() to queue #DF
KVM: x86: Hoist nested event checks above event injection logic
KVM: x86: Evaluate ability to inject SMI/NMI/IRQ after potential
VM-Exit
KVM: nVMX: Add a helper to identify low-priority #DB traps
KVM: nVMX: Document priority of all known events on Intel CPUs
KVM: x86: Morph pending exceptions to pending VM-Exits at queue time
KVM: x86: Treat pending TRIPLE_FAULT requests as pending exceptions
KVM: VMX: Update MTF and ICEBP comments to document KVM's subtle
behavior
KVM: x86: Rename inject_pending_events() to
kvm_check_and_inject_events()
KVM: selftests: Use uapi header to get VMX and SVM exit reasons/codes
KVM: selftests: Add an x86-only test to verify nested exception
queueing

 arch/x86/include/asm/kvm-x86-ops.h            |   2 +-
 arch/x86/include/asm/kvm_host.h               |  35 +-
 arch/x86/kvm/emulate.c                        |   3 +-
 arch/x86/kvm/svm/nested.c                     | 110 ++---
 arch/x86/kvm/svm/svm.c                        |  20 +-
 arch/x86/kvm/vmx/nested.c                     | 329 ++++++++-----
 arch/x86/kvm/vmx/sgx.c                        |   2 +-
 arch/x86/kvm/vmx/vmx.c                        |  53 ++-
 arch/x86/kvm/x86.c                            | 450 ++++++++++++------
 arch/x86/kvm/x86.h                            |  11 +-
 tools/testing/selftests/kvm/.gitignore        |   1 +
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/include/x86_64/svm_util.h   |   7 +-
 .../selftests/kvm/include/x86_64/vmx.h        |  51 +-
 .../kvm/x86_64/nested_exceptions_test.c       | 295 ++++++++++++
 15 files changed, 950 insertions(+), 420 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86_64/nested_exceptions_test.c

base-commit: 8031d87aa9953ddeb047a5356ebd0b240c30f233

Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#1 lore raw

PATCH v2 1/24 KVM: nVMX: Unconditionally purge queued/injected events on nested "exit"

Drop pending exceptions and events queued for re-injection when leaving nested guest mode, even if the "exit" is due to VM-Fail, SMI, or forced by host userspace. Failure to purge events could result in an event belonging to L2 being injected into L1.

This _should_ never happen for VM-Fail as all events should be blocked by nested_run_pending, but it's possible if KVM, not the L1 hypervisor, is the source of VM-Fail when running vmcs02.

SMI is a nop (barring unknown bugs) as recognition of SMI and thus entry to SMM is blocked by pending exceptions and re-injected events.

Forced exit is definitely buggy, but has likely gone unnoticed because userspace probably follows the forced exit with KVM_SET_VCPU_EVENTS (or some other ioctl() that purges the queue).

Fixes 4f350c6dbcb9 ("kvm: nVMX: Handle deferred early VMLAUNCH/VMRESUME failure properly")
---
 arch/x86/kvm/vmx/nested.c | 19 +++++++++++--------
 1 file changed, 11 insertions(+), 8 deletions(-)
arch/x86/kvm/vmx/nested.c +11 -8
index bfa366938c49..8c2c81406248 100644
@@ -4250,14 +4250,6 @@ static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
 			nested_vmx_abort(vcpu,
 					 VMX_ABORT_SAVE_GUEST_MSR_FAIL);
 	}
-
-	/*
-	 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
-	 * preserved above and would only end up incorrectly in L1.
-	 */
-	vcpu->arch.nmi_injected = false;
-	kvm_clear_exception_queue(vcpu);
-	kvm_clear_interrupt_queue(vcpu);
 }
 
 /*
@@ -4596,6 +4588,17 @@ void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
 		WARN_ON_ONCE(nested_early_check);
 	}
 
+	/*
+	 * Drop events/exceptions that were queued for re-injection to L2
+	 * (picked up via vmx_complete_interrupts()), as well as exceptions
+	 * that were pending for L2.  Note, this must NOT be hoisted above
+	 * prepare_vmcs12(), events/exceptions queued for re-injection need to
+	 * be captured in vmcs12 (see vmcs12_save_pending_event()).
+	 */
+	vcpu->arch.nmi_injected = false;
+	kvm_clear_exception_queue(vcpu);
+	kvm_clear_interrupt_queue(vcpu);
+
 	vmx_switch_vmcs(vcpu, &vmx->vmcs01);
 
 	/* Update any VMCS fields that might have changed while L2 ran */
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#2 lore raw

PATCH v2 2/24 KVM: VMX: Drop bits 31:16 when shoving exception error code into VMCS

In reply to Sean Christopherson

Deliberately truncate the exception error code when shoving it into the VMCS (VM-Entry field for vmcs01 and vmcs02, VM-Exit field for vmcs12). Intel CPUs are incapable of handling 32-bit error codes and will never generate an error code with bits 31:16, but userspace can provide an arbitrary error code via KVM_SET_VCPU_EVENTS. Failure to drop the bits on exception injection results in failed VM-Entry, as VMX disallows setting bits 31:16. Setting the bits on VM-Exit would at best confuse L1, and at worse induce a nested VM-Entry failure, e.g. if L1 decided to reinject the exception back into L2.

---
 arch/x86/kvm/vmx/nested.c |  9 ++++++++-
 arch/x86/kvm/vmx/vmx.c    | 11 ++++++++++-
 2 files changed, 18 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/nested.c +8 -1
index 8c2c81406248..05c34a72c266 100644
@@ -3822,7 +3822,14 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
 	u32 intr_info = nr | INTR_INFO_VALID_MASK;
 
 	if (vcpu->arch.exception.has_error_code) {
-		vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
+		/*
+		 * Intel CPUs will never generate an error code with bits 31:16
+		 * set, and more importantly VMX disallows setting bits 31:16
+		 * in the injected error code for VM-Entry.  Drop the bits to
+		 * mimic hardware and avoid inducing failure on nested VM-Entry
+		 * if L1 chooses to inject the exception back to L2.
+		 */
+		vmcs12->vm_exit_intr_error_code = (u16)vcpu->arch.exception.error_code;
 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
 	}
 
arch/x86/kvm/vmx/vmx.c +10 -1
index b0cc911a8f6f..d2b3d30d6afb 100644
@@ -1621,7 +1621,16 @@ static void vmx_queue_exception(struct kvm_vcpu *vcpu)
 	kvm_deliver_exception_payload(vcpu);
 
 	if (has_error_code) {
-		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
+		/*
+		 * Despite the error code being architecturally defined as 32
+		 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
+		 * VMX don't actually supporting setting bits 31:16.  Hardware
+		 * will (should) never provide a bogus error code, but KVM's
+		 * ABI lets userspace shove in arbitrary 32-bit values.  Drop
+		 * the upper bits to avoid VM-Fail, losing information that
+		 * does't really exist is preferable to killing the VM.
+		 */
+		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code);
 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
 	}
 
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
Reviewed-by on v2 2/24
#3 lore raw

Re: [PATCH v2 02/24] KVM: VMX: Drop bits 31:16 when shoving exception error code into VMCS

Quoted 25 lines · Sean Christopherson

Deliberately truncate the exception error code when shoving it into the VMCS (VM-Entry field for vmcs01 and vmcs02, VM-Exit field for vmcs12). Intel CPUs are incapable of handling 32-bit error codes and will never generate an error code with bits 31:16, but userspace can provide an arbitrary error code via KVM_SET_VCPU_EVENTS.  Failure to drop the bits on exception injection results in failed VM-Entry, as VMX disallows setting bits 31:16.  Setting the bits on VM-Exit would at best confuse L1, and at worse induce a nested VM-Entry failure, e.g. if L1 decided to reinject the exception back into L2.

---
 arch/x86/kvm/vmx/nested.c |  9 ++++++++-
 arch/x86/kvm/vmx/vmx.c    | 11 ++++++++++-

 2 files changed, 18 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/nested.c +0 -0
index 8c2c81406248..05c34a72c266 100644
@@ -3822,7 +3822,14 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
         u32 intr_info = nr | INTR_INFO_VALID_MASK;

Quoted 8 lines

        if (vcpu->arch.exception.has_error_code) {
-               vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code; +               /*
+                * Intel CPUs will never generate an error code with bits 31:16 +                * set, and more importantly VMX disallows setting bits 31:16 +                * in the injected error code for VM-Entry.  Drop the bits to +                * mimic hardware and avoid inducing failure on nested VM-Entry +                * if L1 chooses to inject the exception back to L2.

Very small nitpick:
I think I would still prefer to have a mention that AMD CPUs can have error code > 16 bit, The above comment kind of implies this, but it would be a bit more clear, but I don't have a strong preference on this.

Quoted 19 lines

+                */
+               vmcs12->vm_exit_intr_error_code = (u16)vcpu->arch.exception.error_code; intr_info |= INTR_INFO_DELIVER_CODE_MASK;
        }

arch/x86/kvm/vmx/vmx.c +0 -0
index b0cc911a8f6f..d2b3d30d6afb 100644
@@ -1621,7 +1621,16 @@ static void vmx_queue_exception(struct kvm_vcpu *vcpu)
         kvm_deliver_exception_payload(vcpu);


        if (has_error_code) {
-               vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code); +               /*
+                * Despite the error code being architecturally defined as 32 +                * bits, and the VMCS field being 32 bits, Intel CPUs and thus +                * VMX don't actually supporting setting bits 31:16.  Hardware +                * will (should) never provide a bogus error code, but KVM's

Quoted 8 lines

+                * ABI lets userspace shove in arbitrary 32-bit values.  Drop +                * the upper bits to avoid VM-Fail, losing information that +                * does't really exist is preferable to killing the VM. +                */
+               vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code); intr_info |= INTR_INFO_DELIVER_CODE_MASK;
        }

Best regards,
Maxim Levitsky

author maintainer
#4 lore raw

Re: [PATCH v2 02/24] KVM: VMX: Drop bits 31:16 when shoving exception error code into VMCS

Quoted 31 lines · Maxim Levitsky
Quoted 30 lines · Sean Christopherson

Deliberately truncate the exception error code when shoving it into the VMCS (VM-Entry field for vmcs01 and vmcs02, VM-Exit field for vmcs12). Intel CPUs are incapable of handling 32-bit error codes and will never generate an error code with bits 31:16, but userspace can provide an arbitrary error code via KVM_SET_VCPU_EVENTS.  Failure to drop the bits on exception injection results in failed VM-Entry, as VMX disallows setting bits 31:16.  Setting the bits on VM-Exit would at best confuse L1, and at worse induce a nested VM-Entry failure, e.g. if L1 decided to reinject the exception back into L2.

---
 arch/x86/kvm/vmx/nested.c |  9 ++++++++-
 arch/x86/kvm/vmx/vmx.c    | 11 ++++++++++-

 2 files changed, 18 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/nested.c +0 -0
index 8c2c81406248..05c34a72c266 100644
@@ -3822,7 +3822,14 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
         u32 intr_info = nr | INTR_INFO_VALID_MASK;


        if (vcpu->arch.exception.has_error_code) {
-               vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code; +               /*
+                * Intel CPUs will never generate an error code with bits 31:16 +                * set, and more importantly VMX disallows setting bits 31:16

Quoted 8 lines
Quoted 3 lines

+                * in the injected error code for VM-Entry.  Drop the bits to +                * mimic hardware and avoid inducing failure on nested VM-Entry +                * if L1 chooses to inject the exception back to L2.

Very small nitpick:
I think I would still prefer to have a mention that AMD CPUs can have error code > 16 bit, The above comment kind of implies this, but it would be a bit more clear, but I don't have a strong preference on this.

Agreed, I'll reword this to make it abundantly clear that setting bits 31:16 is architecturally allowed and done by AMD, and that this is purely an Intel oddity.

Quoted 12 lines
Quoted 12 lines

+                */
+               vmcs12->vm_exit_intr_error_code = (u16)vcpu->arch.exception.error_code; intr_info |= INTR_INFO_DELIVER_CODE_MASK;
        }

arch/x86/kvm/vmx/vmx.c +0 -0
index b0cc911a8f6f..d2b3d30d6afb 100644
@@ -1621,7 +1621,16 @@ static void vmx_queue_exception(struct kvm_vcpu *vcpu)
         kvm_deliver_exception_payload(vcpu);

Quoted 8 lines
Quoted 8 lines

        if (has_error_code) {
-               vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code); +               /*
+                * Despite the error code being architecturally defined as 32 +                * bits, and the VMCS field being 32 bits, Intel CPUs and thus +                * VMX don't actually supporting setting bits 31:16.  Hardware +                * will (should) never provide a bogus error code, but KVM's +                * ABI lets userspace shove in arbitrary 32-bit values.  Drop

I'll update this to mention AMD CPUs as well.

Quoted 15 lines
Quoted 7 lines

+                * the upper bits to avoid VM-Fail, losing information that +                * does't really exist is preferable to killing the VM. +                */
+               vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code); intr_info |= INTR_INFO_DELIVER_CODE_MASK;
        }

Best regards,
Maxim Levitsky

author maintainer
#5 lore raw

PATCH v2 3/24 KVM: x86: Don't check for code breakpoints when emulating on exception

In reply to Sean Christopherson

Don't check for code breakpoints during instruction emulation if the emulation was triggered by exception interception. Code breakpoints are the highest priority fault-like exception, and KVM only emulates on exceptions that are fault-like. Thus, if hardware signaled a different exception, then the vCPU is already passed the stage of checking for hardware breakpoints.

This is likely a glorified nop in terms of functionality, and is more for clarification and is technically an optimization. Intel's SDM explicitly states vmcs.GUEST_RFLAGS.RF on exception interception is the same as the value that would have been saved on the stack had the exception not been intercepted, i.e. will be '1' due to all fault-like exceptions setting RF to '1'. AMD says "guest state saved ... is the processor state as of the moment the intercept triggers", but that begs the question, "when does the intercept trigger?".

---
 arch/x86/kvm/x86.c | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
arch/x86/kvm/x86.c +18 -3
index f389691d8c04..4efdb61e60ba 100644
@@ -8517,8 +8517,24 @@ int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
 }
 EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
 
-static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu, int *r)
+static bool kvm_vcpu_check_code_breakpoint(struct kvm_vcpu *vcpu,
+					   int emulation_type, int *r)
 {
+	WARN_ON_ONCE(emulation_type & EMULTYPE_NO_DECODE);
+
+	/*
+	 * Do not check for code breakpoints if hardware has already done the
+	 * checks, as inferred from the emulation type.  On NO_DECODE and SKIP,
+	 * the instruction has passed all exception checks, and all intercepted
+	 * exceptions that trigger emulation have lower priority than code
+	 * breakpoints, i.e. the fact that the intercepted exception occurred
+	 * means any code breakpoints have already been serviced.
+	 */
+	if (emulation_type & (EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
+			      EMULTYPE_TRAP_UD | EMULTYPE_TRAP_UD_FORCED |
+			      EMULTYPE_VMWARE_GP | EMULTYPE_PF))
+		return false;
+
 	if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
 	    (vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
 		struct kvm_run *kvm_run = vcpu->run;
@@ -8640,8 +8656,7 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 		 * are fault-like and are higher priority than any faults on
 		 * the code fetch itself.
 		 */
-		if (!(emulation_type & EMULTYPE_SKIP) &&
-		    kvm_vcpu_check_code_breakpoint(vcpu, &r))
+		if (kvm_vcpu_check_code_breakpoint(vcpu, emulation_type, &r))
 			return r;
 
 		r = x86_decode_emulated_instruction(vcpu, emulation_type,
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#6 lore raw

PATCH v2 4/24 KVM: nVMX: Treat General Detect #DB (DR7.GD=1) as fault-like

In reply to Sean Christopherson

Exclude General Detect #DBs, which have fault-like behavior but also have a non-zero payload (DR6.BD=1), from nVMX's handling of pending debug traps. Opportunistically rewrite the comment to better document what is being checked, i.e. "has a non-zero payload" vs. "has a payload", and to call out the many caveats surrounding #DBs that KVM dodges one way or another.

Cc Oliver Upton <[email protected]>
Cc Peter Shier <[email protected]>
Fixes 684c0422da71 ("KVM: nVMX: Handle pending #DB when injecting INIT VM-exit")
---
 arch/x86/kvm/vmx/nested.c | 36 +++++++++++++++++++++++++-----------
 1 file changed, 25 insertions(+), 11 deletions(-)
arch/x86/kvm/vmx/nested.c +25 -11
index 05c34a72c266..2409ed8dbc71 100644
@@ -3846,16 +3846,29 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
 }
 
 /*
- * Returns true if a debug trap is pending delivery.
+ * Returns true if a debug trap is (likely) pending delivery.  Infer the class
+ * of a #DB (trap-like vs. fault-like) from the exception payload (to-be-DR6).
+ * Using the payload is flawed because code breakpoints (fault-like) and data
+ * breakpoints (trap-like) set the same bits in DR6 (breakpoint detected), i.e.
+ * this will return false positives if a to-be-injected code breakpoint #DB is
+ * pending (from KVM's perspective, but not "pending" across an instruction
+ * boundary).  ICEBP, a.k.a. INT1, is also not reflected here even though it
+ * too is trap-like.
  *
- * In KVM, debug traps bear an exception payload. As such, the class of a #DB
- * exception may be inferred from the presence of an exception payload.
+ * KVM "works" despite these flaws as ICEBP isn't currently supported by the
+ * emulator, Monitor Trap Flag is not marked pending on intercepted #DBs (the
+ * #DB has already happened), and MTF isn't marked pending on code breakpoints
+ * from the emulator (because such #DBs are fault-like and thus don't trigger
+ * actions that fire on instruction retire).
  */
-static inline bool vmx_pending_dbg_trap(struct kvm_vcpu *vcpu)
+static inline unsigned long vmx_get_pending_dbg_trap(struct kvm_vcpu *vcpu)
 {
-	return vcpu->arch.exception.pending &&
-			vcpu->arch.exception.nr == DB_VECTOR &&
-			vcpu->arch.exception.payload;
+	if (!vcpu->arch.exception.pending ||
+	    vcpu->arch.exception.nr != DB_VECTOR)
+		return 0;
+
+	/* General Detect #DBs are always fault-like. */
+	return vcpu->arch.exception.payload & ~DR6_BD;
 }
 
 /*
@@ -3867,9 +3880,10 @@ static inline bool vmx_pending_dbg_trap(struct kvm_vcpu *vcpu)
  */
 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
 {
-	if (vmx_pending_dbg_trap(vcpu))
-		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
-			    vcpu->arch.exception.payload);
+	unsigned long pending_dbg = vmx_get_pending_dbg_trap(vcpu);
+
+	if (pending_dbg)
+		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, pending_dbg);
 }
 
 static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
@@ -3926,7 +3940,7 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	 * while delivering the pending exception.
 	 */
 
-	if (vcpu->arch.exception.pending && !vmx_pending_dbg_trap(vcpu)) {
+	if (vcpu->arch.exception.pending && !vmx_get_pending_dbg_trap(vcpu)) {
 		if (vmx->nested.nested_run_pending)
 			return -EBUSY;
 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#7 lore raw

PATCH v2 5/24 KVM: nVMX: Prioritize TSS T-flag #DBs over Monitor Trap Flag

In reply to Sean Christopherson

Service TSS T-flag #DBs prior to pending MTFs, as such #DBs are higher priority than MTF. KVM itself doesn't emulate TSS #DBs, and any such exceptions injected from L1 will be handled by hardware (or morphed to a fault-like exception if injection fails), but theoretically userspace could pend a TSS T-flag #DB in conjunction with a pending MTF.

Note, there's no known use case this fixes, it's purely to be technically correct with respect to Intel's SDM.

Cc Oliver Upton <[email protected]>
Cc Peter Shier <[email protected]>
Fixes 5ef8acbdd687 ("KVM: nVMX: Emulate MTF when performing instruction emulation")
---
 arch/x86/kvm/vmx/nested.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
arch/x86/kvm/vmx/nested.c +5 -3
index 2409ed8dbc71..bc5759f82a3f 100644
@@ -3932,15 +3932,17 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	}
 
 	/*
-	 * Process any exceptions that are not debug traps before MTF.
+	 * Process exceptions that are higher priority than Monitor Trap Flag:
+	 * fault-like exceptions, TSS T flag #DB (not emulated by KVM, but
+	 * could theoretically come in from userspace), and ICEBP (INT1).
 	 *
 	 * Note that only a pending nested run can block a pending exception.
 	 * Otherwise an injected NMI/interrupt should either be
 	 * lost or delivered to the nested hypervisor in the IDT_VECTORING_INFO,
 	 * while delivering the pending exception.
 	 */
-
-	if (vcpu->arch.exception.pending && !vmx_get_pending_dbg_trap(vcpu)) {
+	if (vcpu->arch.exception.pending &&
+	    !(vmx_get_pending_dbg_trap(vcpu) & ~DR6_BT)) {
 		if (vmx->nested.nested_run_pending)
 			return -EBUSY;
 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#8 lore raw

PATCH v2 6/24 KVM: x86: Treat #DBs from the emulator as fault-like (code and DR7.GD=1)

In reply to Sean Christopherson

Add a dedicated "exception type" for #DBs, as #DBs can be fault-like or trap-like depending the sub-type of #DB, and effectively defer the decision of what to do with the #DB to the caller.

For the emulator's two calls to exception_type(), treat the #DB as fault-like, as the emulator handles only code breakpoint and general detect #DBs, both of which are fault-like.

For event injection, which uses exception_type() to determine whether to set EFLAGS.RF=1 on the stack, keep the current behavior of not setting RF=1 for #DBs. Intel and AMD explicitly state RF isn't set on code #DBs, so exempting by failing the "== EXCPT_FAULT" check is correct. The only other fault-like #DB is General Detect, and despite Intel and AMD both strongly implying (through omission) that General Detect #DBs should set RF=1, hardware (multiple generations of both Intel and AMD), in fact does not. Through insider knowledge, extreme foresight, sheer dumb luck, or some combination thereof, KVM correctly handled RF for General Detect #DBs.

Fixes 38827dbd3fb8 ("KVM: x86: Do not update EFLAGS on faulting emulation")
---
 arch/x86/kvm/x86.c | 27 +++++++++++++++++++++++++--
 1 file changed, 25 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +25 -2
index 4efdb61e60ba..37d686dbb6aa 100644
@@ -529,6 +529,7 @@ static int exception_class(int vector)
 #define EXCPT_TRAP		1
 #define EXCPT_ABORT		2
 #define EXCPT_INTERRUPT		3
+#define EXCPT_DB		4
 
 static int exception_type(int vector)
 {
@@ -539,8 +540,14 @@ static int exception_type(int vector)
 
 	mask = 1 << vector;
 
-	/* #DB is trap, as instruction watchpoints are handled elsewhere */
-	if (mask & ((1 << DB_VECTOR) | (1 << BP_VECTOR) | (1 << OF_VECTOR)))
+	/*
+	 * #DBs can be trap-like or fault-like, the caller must check other CPU
+	 * state, e.g. DR6, to determine whether a #DB is a trap or fault.
+	 */
+	if (mask & (1 << DB_VECTOR))
+		return EXCPT_DB;
+
+	if (mask & ((1 << BP_VECTOR) | (1 << OF_VECTOR)))
 		return EXCPT_TRAP;
 
 	if (mask & ((1 << DF_VECTOR) | (1 << MC_VECTOR)))
@@ -8785,6 +8792,12 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 		unsigned long rflags = static_call(kvm_x86_get_rflags)(vcpu);
 		toggle_interruptibility(vcpu, ctxt->interruptibility);
 		vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
+
+		/*
+		 * Note, EXCPT_DB is assumed to be fault-like as the emulator
+		 * only supports code breakpoints and general detect #DB, both
+		 * of which are fault-like.
+		 */
 		if (!ctxt->have_exception ||
 		    exception_type(ctxt->exception.vector) == EXCPT_TRAP) {
 			kvm_pmu_trigger_event(vcpu, PERF_COUNT_HW_INSTRUCTIONS);
@@ -9701,6 +9714,16 @@ static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
 
 	/* try to inject new event if pending */
 	if (vcpu->arch.exception.pending) {
+		/*
+		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
+		 * value pushed on the stack.  Trap-like exception and all #DBs
+		 * leave RF as-is (KVM follows Intel's behavior in this regard;
+		 * AMD states that code breakpoint #DBs excplitly clear RF=0).
+		 *
+		 * Note, most versions of Intel's SDM and AMD's APM incorrectly
+		 * describe the behavior of General Detect #DBs, which are
+		 * fault-like.  They do _not_ set RF, a la code breakpoints.
+		 */
 		if (exception_type(vcpu->arch.exception.nr) == EXCPT_FAULT)
 			__kvm_set_rflags(vcpu, kvm_get_rflags(vcpu) |
 					     X86_EFLAGS_RF);
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#9 lore raw

PATCH v2 7/24 KVM: x86: Use DR7_GD macro instead of open coding check in emulator

In reply to Sean Christopherson

Use DR7_GD in the emulator instead of open coding the check, and drop a comically wrong comment.

---
 arch/x86/kvm/emulate.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
arch/x86/kvm/emulate.c +1 -2
index bd9e9c5627d0..fdeccf446b28 100644
@@ -4181,8 +4181,7 @@ static int check_dr7_gd(struct x86_emulate_ctxt *ctxt)
 
 	ctxt->ops->get_dr(ctxt, 7, &dr7);
 
-	/* Check if DR7.Global_Enable is set */
-	return dr7 & (1 << 13);
+	return dr7 & DR7_GD;
 }
 
 static int check_dr_read(struct x86_emulate_ctxt *ctxt)
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#10 lore raw

PATCH v2 8/24 KVM: nVMX: Ignore SIPI that arrives in L2 when vCPU is not in WFS

In reply to Sean Christopherson

Fall through to handling other pending exception/events for L2 if SIPI is pending while the CPU is not in Wait-for-SIPI. KVM correctly ignores the event, but incorrectly returns immediately, e.g. a SIPI coincident with another event could lead to KVM incorrectly routing the event to L1 instead of L2.

Fixes bf0cd88ce363 ("KVM: x86: emulate wait-for-SIPI and SIPI-VMExit")
---
 arch/x86/kvm/vmx/nested.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/nested.c +4 -2
index bc5759f82a3f..104f233ddd5d 100644
@@ -3925,10 +3925,12 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 			return -EBUSY;
 
 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
-		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED)
+		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
 			nested_vmx_vmexit(vcpu, EXIT_REASON_SIPI_SIGNAL, 0,
 						apic->sipi_vector & 0xFFUL);
-		return 0;
+			return 0;
+		}
+		/* Fallthrough, the SIPI is completely ignored. */
 	}
 
 	/*
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#11 lore raw

PATCH v2 9/24 KVM: nVMX: Unconditionally clear mtf_pending on nested VM-Exit

In reply to Sean Christopherson

Clear mtf_pending on nested VM-Exit instead of handling the clear on a case-by-case basis in vmx_check_nested_events(). The pending MTF should never survive nested VM-Exit, as it is a property of KVM's run of the current L2, i.e. should never affect the next L2 run by L1. In practice, this is likely a nop as getting to L1 with nested_run_pending is impossible, and KVM doesn't correctly handle morphing a pending exception that occurs on a prior injected exception (need for re-injected exception being the other case where MTF isn't cleared). However, KVM will hopefully soon correctly deal with a pending exception on top of an injected exception.

Add a TODO to document that KVM has an inversion priority bug between SMIs and MTF (and trap-like #DBS), and that KVM also doesn't properly save/restore MTF across SMI/RSM.

---
 arch/x86/kvm/vmx/nested.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)
arch/x86/kvm/vmx/nested.c +12 -9
index 104f233ddd5d..a85f31cee149 100644
@@ -3898,16 +3898,8 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	unsigned long exit_qual;
 	bool block_nested_events =
 	    vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
-	bool mtf_pending = vmx->nested.mtf_pending;
 	struct kvm_lapic *apic = vcpu->arch.apic;
 
-	/*
-	 * Clear the MTF state. If a higher priority VM-exit is delivered first,
-	 * this state is discarded.
-	 */
-	if (!block_nested_events)
-		vmx->nested.mtf_pending = false;
-
 	if (lapic_in_kernel(vcpu) &&
 		test_bit(KVM_APIC_INIT, &apic->pending_events)) {
 		if (block_nested_events)
@@ -3916,6 +3908,9 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 		clear_bit(KVM_APIC_INIT, &apic->pending_events);
 		if (vcpu->arch.mp_state != KVM_MP_STATE_INIT_RECEIVED)
 			nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
+
+		/* MTF is discarded if the vCPU is in WFS. */
+		vmx->nested.mtf_pending = false;
 		return 0;
 	}
 
@@ -3938,6 +3933,11 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	 * fault-like exceptions, TSS T flag #DB (not emulated by KVM, but
 	 * could theoretically come in from userspace), and ICEBP (INT1).
 	 *
+	 * TODO: SMIs have higher priority than MTF and trap-like #DBs (except
+	 * for TSS T flag #DBs).  KVM also doesn't save/restore pending MTF
+	 * across SMI/RSM as it should; that needs to be addressed in order to
+	 * prioritize SMI over MTF and trap-like #DBs.
+	 *
 	 * Note that only a pending nested run can block a pending exception.
 	 * Otherwise an injected NMI/interrupt should either be
 	 * lost or delivered to the nested hypervisor in the IDT_VECTORING_INFO,
@@ -3953,7 +3953,7 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 		return 0;
 	}
 
-	if (mtf_pending) {
+	if (vmx->nested.mtf_pending) {
 		if (block_nested_events)
 			return -EBUSY;
 		nested_vmx_update_pending_dbg(vcpu);
@@ -4549,6 +4549,9 @@ void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
 
+	/* Pending MTF traps are discarded on VM-Exit. */
+	vmx->nested.mtf_pending = false;
+
 	/* trying to cancel vmlaunch/vmresume is a bug */
 	WARN_ON_ONCE(vmx->nested.nested_run_pending);
 
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
#12 lore raw

Re: [PATCH v2 09/24] KVM: nVMX: Unconditionally clear mtf_pending on nested VM-Exit

Quoted 53 lines · Sean Christopherson

Clear mtf_pending on nested VM-Exit instead of handling the clear on a case-by-case basis in vmx_check_nested_events().  The pending MTF should never survive nested VM-Exit, as it is a property of KVM's run of the current L2, i.e. should never affect the next L2 run by L1.  In practice, this is likely a nop as getting to L1 with nested_run_pending is impossible, and KVM doesn't correctly handle morphing a pending exception that occurs on a prior injected exception (need for re-injected exception being the other case where MTF isn't cleared).  However, KVM will hopefully soon correctly deal with a pending exception on top of an injected exception.

Add a TODO to document that KVM has an inversion priority bug between SMIs and MTF (and trap-like #DBS), and that KVM also doesn't properly save/restore MTF across SMI/RSM.

---
 arch/x86/kvm/vmx/nested.c | 21 ++++++++++++---------

 1 file changed, 12 insertions(+), 9 deletions(-)
arch/x86/kvm/vmx/nested.c +0 -0
index 104f233ddd5d..a85f31cee149 100644
@@ -3898,16 +3898,8 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
         unsigned long exit_qual;

        bool block_nested_events =
            vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu); -       bool mtf_pending = vmx->nested.mtf_pending;
        struct kvm_lapic *apic = vcpu->arch.apic;

-       /*
-        * Clear the MTF state. If a higher priority VM-exit is delivered first, -        * this state is discarded.
-        */
-       if (!block_nested_events)
-               vmx->nested.mtf_pending = false;
-
        if (lapic_in_kernel(vcpu) &&
                test_bit(KVM_APIC_INIT, &apic->pending_events)) { if (block_nested_events)

arch/x86/kvm/vmx/nested.c +3 -0
@@ -3916,6 +3908,9 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
                 clear_bit(KVM_APIC_INIT, &apic->pending_events);
                 if (vcpu->arch.mp_state != KVM_MP_STATE_INIT_RECEIVED)
                         nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0);
+
+               /* MTF is discarded if the vCPU is in WFS. */
+               vmx->nested.mtf_pending = false;
                 return 0;
         }

arch/x86/kvm/vmx/nested.c static int vmx_check_nested_events(struct kvm_vcpu *vcpu) · line 3939

Quoted 7 lines
arch/x86/kvm/vmx/nested.c +4 -0
@@ -3938,6 +3933,11 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
          * fault-like exceptions, TSS T flag #DB (not emulated by KVM, but
          * could theoretically come in from userspace), and ICEBP (INT1).
          *
+        * TODO: SMIs have higher priority than MTF and trap-like #DBs (except
+        * for TSS T flag #DBs).  KVM also doesn't save/restore pending MTF
+        * across SMI/RSM as it should; that needs to be addressed in order to
+        * prioritize SMI over MTF and trap-like #DBs.

Thanks, makes sense.

Best regards,
Maxim Levitsky

Quoted 23 lines
arch/x86/kvm/vmx/nested.c +1 -0
+        *
          * Note that only a pending nested run can block a pending exception.
          * Otherwise an injected NMI/interrupt should either be
          * lost or delivered to the nested hypervisor in the IDT_VECTORING_INFO,
@@ -3953,7 +3953,7 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
                 return 0;
         }


-       if (mtf_pending) {
+       if (vmx->nested.mtf_pending) {
                if (block_nested_events) return -EBUSY; nested_vmx_update_pending_dbg(vcpu);

arch/x86/kvm/vmx/nested.c +0 -0
@@ -4549,6 +4549,9 @@ void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
         struct vcpu_vmx *vmx = to_vmx(vcpu);
         struct vmcs12 *vmcs12 = get_vmcs12(vcpu);


+       /* Pending MTF traps are discarded on VM-Exit. */ +       vmx->nested.mtf_pending = false;
+
        /* trying to cancel vmlaunch/vmresume is a bug */ WARN_ON_ONCE(vmx->nested.nested_run_pending);

author maintainer
#13 lore raw

PATCH v2 10/24 KVM: VMX: Inject #PF on ENCLS as "emulated" #PF

In reply to Sean Christopherson

Treat #PFs that occur during emulation of ENCLS as, wait for it, emulated page faults. Practically speaking, this is a glorified nop as the exception is never of the nested flavor, and it's extremely unlikely the guest is relying on the side effect of an implicit INVLPG on the faulting address.

Fixes 70210c044b4e ("KVM: VMX: Add SGX ENCLS[ECREATE] handler to enforce CPUID restrictions")
---
 arch/x86/kvm/vmx/sgx.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kvm/vmx/sgx.c +1 -1
index aba8cebdc587..8f95c7c01433 100644
@@ -129,7 +129,7 @@ static int sgx_inject_fault(struct kvm_vcpu *vcpu, gva_t gva, int trapnr)
 		ex.address = gva;
 		ex.error_code_valid = true;
 		ex.nested_page_fault = false;
-		kvm_inject_page_fault(vcpu, &ex);
+		kvm_inject_emulated_page_fault(vcpu, &ex);
 	} else {
 		kvm_inject_gp(vcpu, 0);
 	}
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#14 lore raw

PATCH v2 11/24 KVM: x86: Rename kvm_x86_ops.queue_exception to inject_exception

In reply to Sean Christopherson

Rename the kvm_x86_ops hook for exception injection to better reflect reality, and to align with pretty much every other related function name in KVM.

No functional change intended.

---
 arch/x86/include/asm/kvm-x86-ops.h | 2 +-
 arch/x86/include/asm/kvm_host.h    | 2 +-
 arch/x86/kvm/svm/svm.c             | 4 ++--
 arch/x86/kvm/vmx/vmx.c             | 4 ++--
 arch/x86/kvm/x86.c                 | 2 +-
 5 files changed, 7 insertions(+), 7 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -1
index 51f777071584..82ba4a564e58 100644
@@ -67,7 +67,7 @@ KVM_X86_OP(get_interrupt_shadow)
 KVM_X86_OP(patch_hypercall)
 KVM_X86_OP(inject_irq)
 KVM_X86_OP(inject_nmi)
-KVM_X86_OP(queue_exception)
+KVM_X86_OP(inject_exception)
 KVM_X86_OP(cancel_injection)
 KVM_X86_OP(interrupt_allowed)
 KVM_X86_OP(nmi_allowed)
arch/x86/include/asm/kvm_host.h +1 -1
index e8281d64a431..dbb9eab979d4 100644
@@ -1523,7 +1523,7 @@ struct kvm_x86_ops {
 				unsigned char *hypercall_addr);
 	void (*inject_irq)(struct kvm_vcpu *vcpu, bool reinjected);
 	void (*inject_nmi)(struct kvm_vcpu *vcpu);
-	void (*queue_exception)(struct kvm_vcpu *vcpu);
+	void (*inject_exception)(struct kvm_vcpu *vcpu);
 	void (*cancel_injection)(struct kvm_vcpu *vcpu);
 	int (*interrupt_allowed)(struct kvm_vcpu *vcpu, bool for_injection);
 	int (*nmi_allowed)(struct kvm_vcpu *vcpu, bool for_injection);
arch/x86/kvm/svm/svm.c +2 -2
index ba81a7e58f75..a254d3b9926c 100644
@@ -452,7 +452,7 @@ static int svm_update_soft_interrupt_rip(struct kvm_vcpu *vcpu)
 	return 0;
 }
 
-static void svm_queue_exception(struct kvm_vcpu *vcpu)
+static void svm_inject_exception(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
 	unsigned nr = vcpu->arch.exception.nr;
@@ -4796,7 +4796,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.patch_hypercall = svm_patch_hypercall,
 	.inject_irq = svm_inject_irq,
 	.inject_nmi = svm_inject_nmi,
-	.queue_exception = svm_queue_exception,
+	.inject_exception = svm_inject_exception,
 	.cancel_injection = svm_cancel_injection,
 	.interrupt_allowed = svm_interrupt_allowed,
 	.nmi_allowed = svm_nmi_allowed,
arch/x86/kvm/vmx/vmx.c +2 -2
index d2b3d30d6afb..34d3f29bfa50 100644
@@ -1610,7 +1610,7 @@ static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
 		vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
 }
 
-static void vmx_queue_exception(struct kvm_vcpu *vcpu)
+static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 	unsigned nr = vcpu->arch.exception.nr;
@@ -8013,7 +8013,7 @@ static struct kvm_x86_ops vmx_x86_ops __initdata = {
 	.patch_hypercall = vmx_patch_hypercall,
 	.inject_irq = vmx_inject_irq,
 	.inject_nmi = vmx_inject_nmi,
-	.queue_exception = vmx_queue_exception,
+	.inject_exception = vmx_inject_exception,
 	.cancel_injection = vmx_cancel_injection,
 	.interrupt_allowed = vmx_interrupt_allowed,
 	.nmi_allowed = vmx_nmi_allowed,
arch/x86/kvm/x86.c +1 -1
index 37d686dbb6aa..dbf95dc53c66 100644
@@ -9659,7 +9659,7 @@ static void kvm_inject_exception(struct kvm_vcpu *vcpu)
 
 	if (vcpu->arch.exception.error_code && !is_protmode(vcpu))
 		vcpu->arch.exception.error_code = false;
-	static_call(kvm_x86_queue_exception)(vcpu);
+	static_call(kvm_x86_inject_exception)(vcpu);
 }
 
 static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#15 lore raw

PATCH v2 12/24 KVM: x86: Make kvm_queued_exception a properly named, visible struct

In reply to Sean Christopherson

Move the definition of "struct kvm_queued_exception" out of kvm_vcpu_arch in anticipation of adding a second instance in kvm_vcpu_arch to handle exceptions that occur when vectoring an injected exception and are morphed to VM-Exit instead of leading to #DF.

Opportunistically take advantage of the churn to rename "nr" to "vector".

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 23 +++++-----
 arch/x86/kvm/svm/nested.c       | 45 ++++++++++---------
 arch/x86/kvm/svm/svm.c          | 14 +++---
 arch/x86/kvm/vmx/nested.c       | 42 +++++++++--------
 arch/x86/kvm/vmx/vmx.c          | 20 ++++-----
 arch/x86/kvm/x86.c              | 80 ++++++++++++++++-----------------
 arch/x86/kvm/x86.h              |  3 +-
 7 files changed, 111 insertions(+), 116 deletions(-)
arch/x86/include/asm/kvm_host.h +13 -10
index dbb9eab979d4..0a6a05e25f24 100644
@@ -639,6 +639,17 @@ struct kvm_vcpu_xen {
 	struct timer_list poll_timer;
 };
 
+struct kvm_queued_exception {
+	bool pending;
+	bool injected;
+	bool has_error_code;
+	u8 vector;
+	u32 error_code;
+	unsigned long payload;
+	bool has_payload;
+	u8 nested_apf;
+};
+
 struct kvm_vcpu_arch {
 	/*
 	 * rip and regs accesses must go through
@@ -737,16 +748,8 @@ struct kvm_vcpu_arch {
 
 	u8 event_exit_inst_len;
 
-	struct kvm_queued_exception {
-		bool pending;
-		bool injected;
-		bool has_error_code;
-		u8 nr;
-		u32 error_code;
-		unsigned long payload;
-		bool has_payload;
-		u8 nested_apf;
-	} exception;
+	/* Exceptions to be injected to the guest. */
+	struct kvm_queued_exception exception;
 
 	struct kvm_queued_interrupt {
 		bool injected;
arch/x86/kvm/svm/nested.c +23 -22

79 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +6 -8
index a254d3b9926c..a336517b563e 100644
@@ -454,22 +454,20 @@ static int svm_update_soft_interrupt_rip(struct kvm_vcpu *vcpu)
 
 static void svm_inject_exception(struct kvm_vcpu *vcpu)
 {
+	struct kvm_queued_exception *ex = &vcpu->arch.exception;
 	struct vcpu_svm *svm = to_svm(vcpu);
-	unsigned nr = vcpu->arch.exception.nr;
-	bool has_error_code = vcpu->arch.exception.has_error_code;
-	u32 error_code = vcpu->arch.exception.error_code;
 
-	kvm_deliver_exception_payload(vcpu);
+	kvm_deliver_exception_payload(vcpu, ex);
 
-	if (kvm_exception_is_soft(nr) &&
+	if (kvm_exception_is_soft(ex->vector) &&
 	    svm_update_soft_interrupt_rip(vcpu))
 		return;
 
-	svm->vmcb->control.event_inj = nr
+	svm->vmcb->control.event_inj = ex->vector
 		| SVM_EVTINJ_VALID
-		| (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
+		| (ex->has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
 		| SVM_EVTINJ_TYPE_EXEPT;
-	svm->vmcb->control.event_inj_err = error_code;
+	svm->vmcb->control.event_inj_err = ex->error_code;
 }
 
 static void svm_init_erratum_383(void)
arch/x86/kvm/vmx/nested.c +20 -22

85 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.c +9 -11
index 34d3f29bfa50..7d3abe2a206a 100644
@@ -1585,7 +1585,7 @@ static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
 	 */
 	if (nested_cpu_has_mtf(vmcs12) &&
 	    (!vcpu->arch.exception.pending ||
-	     vcpu->arch.exception.nr == DB_VECTOR))
+	     vcpu->arch.exception.vector == DB_VECTOR))
 		vmx->nested.mtf_pending = true;
 	else
 		vmx->nested.mtf_pending = false;
@@ -1612,15 +1612,13 @@ static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
 
 static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 {
+	struct kvm_queued_exception *ex = &vcpu->arch.exception;
+	u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
-	unsigned nr = vcpu->arch.exception.nr;
-	bool has_error_code = vcpu->arch.exception.has_error_code;
-	u32 error_code = vcpu->arch.exception.error_code;
-	u32 intr_info = nr | INTR_INFO_VALID_MASK;
 
-	kvm_deliver_exception_payload(vcpu);
+	kvm_deliver_exception_payload(vcpu, ex);
 
-	if (has_error_code) {
+	if (ex->has_error_code) {
 		/*
 		 * Despite the error code being architecturally defined as 32
 		 * bits, and the VMCS field being 32 bits, Intel CPUs and thus
@@ -1630,21 +1628,21 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 		 * the upper bits to avoid VM-Fail, losing information that
 		 * does't really exist is preferable to killing the VM.
 		 */
-		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)error_code);
+		vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code);
 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
 	}
 
 	if (vmx->rmode.vm86_active) {
 		int inc_eip = 0;
-		if (kvm_exception_is_soft(nr))
+		if (kvm_exception_is_soft(ex->vector))
 			inc_eip = vcpu->arch.event_exit_inst_len;
-		kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
+		kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip);
 		return;
 	}
 
 	WARN_ON_ONCE(vmx->emulation_required);
 
-	if (kvm_exception_is_soft(nr)) {
+	if (kvm_exception_is_soft(ex->vector)) {
 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
 			     vmx->vcpu.arch.event_exit_inst_len);
 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
arch/x86/kvm/x86.c +38 -42

175 lines not on this page · raw message

arch/x86/kvm/x86.h +2 -1
index 501b884b8cc4..dc2af0146220 100644
@@ -286,7 +286,8 @@ int kvm_write_guest_virt_system(struct kvm_vcpu *vcpu,
 
 int handle_ud(struct kvm_vcpu *vcpu);
 
-void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu);
+void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
+				   struct kvm_queued_exception *ex);
 
 void kvm_vcpu_mtrr_init(struct kvm_vcpu *vcpu);
 u8 kvm_mtrr_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn);
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#16 lore raw

PATCH v2 13/24 KVM: x86: Formalize blocking of nested pending exceptions

In reply to Sean Christopherson

Capture nested_run_pending as block_pending_exceptions so that the logic of why exceptions are blocked only needs to be documented once instead of at every place that employs the logic.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 26 ++++++++++++++++----------
 arch/x86/kvm/vmx/nested.c | 29 ++++++++++++++++++-----------
 2 files changed, 34 insertions(+), 21 deletions(-)
arch/x86/kvm/svm/nested.c +16 -10
index f4cc12ee21d1..f5676c2679d0 100644
@@ -1352,10 +1352,22 @@ static inline bool nested_exit_on_init(struct vcpu_svm *svm)
 
 static int svm_check_nested_events(struct kvm_vcpu *vcpu)
 {
-	struct vcpu_svm *svm = to_svm(vcpu);
-	bool block_nested_events =
-		kvm_event_needs_reinjection(vcpu) || svm->nested.nested_run_pending;
 	struct kvm_lapic *apic = vcpu->arch.apic;
+	struct vcpu_svm *svm = to_svm(vcpu);
+	/*
+	 * Only a pending nested run blocks a pending exception.  If there is a
+	 * previously injected event, the pending exception occurred while said
+	 * event was being delivered and thus needs to be handled.
+	 */
+	bool block_nested_exceptions = svm->nested.nested_run_pending;
+	/*
+	 * New events (not exceptions) are only recognized at instruction
+	 * boundaries.  If an event needs reinjection, then KVM is handling a
+	 * VM-Exit that occurred _during_ instruction execution; new events are
+	 * blocked until the instruction completes.
+	 */
+	bool block_nested_events = block_nested_exceptions ||
+				   kvm_event_needs_reinjection(vcpu);
 
 	if (lapic_in_kernel(vcpu) &&
 	    test_bit(KVM_APIC_INIT, &apic->pending_events)) {
@@ -1368,13 +1380,7 @@ static int svm_check_nested_events(struct kvm_vcpu *vcpu)
 	}
 
 	if (vcpu->arch.exception.pending) {
-		/*
-		 * Only a pending nested run can block a pending exception.
-		 * Otherwise an injected NMI/interrupt should either be
-		 * lost or delivered to the nested hypervisor in the EXITINTINFO
-		 * vmcb field, while delivering the pending exception.
-		 */
-		if (svm->nested.nested_run_pending)
+		if (block_nested_exceptions)
                         return -EBUSY;
 		if (!nested_exit_on_exception(svm))
 			return 0;
arch/x86/kvm/vmx/nested.c +18 -11
index 42eccdcc2a4b..a0a4eddce445 100644
@@ -3892,11 +3892,23 @@ static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
 
 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 {
-	struct vcpu_vmx *vmx = to_vmx(vcpu);
-	unsigned long exit_qual;
-	bool block_nested_events =
-	    vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
 	struct kvm_lapic *apic = vcpu->arch.apic;
+	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	unsigned long exit_qual;
+	/*
+	 * Only a pending nested run blocks a pending exception.  If there is a
+	 * previously injected event, the pending exception occurred while said
+	 * event was being delivered and thus needs to be handled.
+	 */
+	bool block_nested_exceptions = vmx->nested.nested_run_pending;
+	/*
+	 * New events (not exceptions) are only recognized at instruction
+	 * boundaries.  If an event needs reinjection, then KVM is handling a
+	 * VM-Exit that occurred _during_ instruction execution; new events are
+	 * blocked until the instruction completes.
+	 */
+	bool block_nested_events = block_nested_exceptions ||
+				   kvm_event_needs_reinjection(vcpu);
 
 	if (lapic_in_kernel(vcpu) &&
 		test_bit(KVM_APIC_INIT, &apic->pending_events)) {
@@ -3935,15 +3947,10 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	 * for TSS T flag #DBs).  KVM also doesn't save/restore pending MTF
 	 * across SMI/RSM as it should; that needs to be addressed in order to
 	 * prioritize SMI over MTF and trap-like #DBs.
-	 *
-	 * Note that only a pending nested run can block a pending exception.
-	 * Otherwise an injected NMI/interrupt should either be
-	 * lost or delivered to the nested hypervisor in the IDT_VECTORING_INFO,
-	 * while delivering the pending exception.
 	 */
 	if (vcpu->arch.exception.pending &&
 	    !(vmx_get_pending_dbg_trap(vcpu) & ~DR6_BT)) {
-		if (vmx->nested.nested_run_pending)
+		if (block_nested_exceptions)
 			return -EBUSY;
 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
 			goto no_vmexit;
@@ -3960,7 +3967,7 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	}
 
 	if (vcpu->arch.exception.pending) {
-		if (vmx->nested.nested_run_pending)
+		if (block_nested_exceptions)
 			return -EBUSY;
 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
 			goto no_vmexit;
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#17 lore raw

PATCH v2 14/24 KVM: x86: Use kvm_queue_exception_e() to queue #DF

In reply to Sean Christopherson

Queue #DF by recursing on kvm_multiple_exception() by way of kvm_queue_exception_e() instead of open coding the behavior. This will allow KVM to Just Work when a future commit moves exception interception checks (for L2 => L1) into kvm_multiple_exception().

No functional change intended.

---
 arch/x86/kvm/x86.c | 21 +++++++++------------
 1 file changed, 9 insertions(+), 12 deletions(-)
arch/x86/kvm/x86.c +9 -12
index c4f758edf353..5aaa1d8de0b3 100644
@@ -663,25 +663,22 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
 	}
 	class1 = exception_class(prev_nr);
 	class2 = exception_class(nr);
-	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
-		|| (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
+	if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY) ||
+	    (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
 		/*
-		 * Generate double fault per SDM Table 5-5.  Set
-		 * exception.pending = true so that the double fault
-		 * can trigger a nested vmexit.
+		 * Synthesize #DF.  Clear the previously injected or pending
+		 * exception so as not to incorrectly trigger shutdown.
 		 */
-		vcpu->arch.exception.pending = true;
 		vcpu->arch.exception.injected = false;
-		vcpu->arch.exception.has_error_code = true;
-		vcpu->arch.exception.vector = DF_VECTOR;
-		vcpu->arch.exception.error_code = 0;
-		vcpu->arch.exception.has_payload = false;
-		vcpu->arch.exception.payload = 0;
-	} else
+		vcpu->arch.exception.pending = false;
+
+		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
+	} else {
 		/* replace previous exception with a new one in a hope
 		   that instruction re-execution will regenerate lost
 		   exception */
 		goto queue;
+	}
 }
 
 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#18 lore raw

PATCH v2 15/24 KVM: x86: Hoist nested event checks above event injection logic

In reply to Sean Christopherson

Perform nested event checks before re-injecting exceptions/events into L2. If a pending exception causes VM-Exit to L1, re-injecting events into vmcs02 is premature and wasted effort. Take care to ensure events that need to be re-injected are still re-injected if checking for nested events "fails", i.e. if KVM needs to force an immediate entry+exit to complete the to-be-re-injecteed event.

Keep the "can_inject" logic the same for now; it too can be pushed below the nested checks, but is a slightly riskier change (see past bugs about events not being properly purged on nested VM-Exit).

Add and/or modify comments to better document the various interactions. Of note is the comment regarding "blocking" previously injected NMIs and IRQs if an exception is pending. The old comment isn't wrong strictly speaking, but it failed to capture the reason why the logic even exists.

---
 arch/x86/kvm/x86.c | 89 +++++++++++++++++++++++++++-------------------
 1 file changed, 53 insertions(+), 36 deletions(-)
arch/x86/kvm/x86.c +53 -36
index 5aaa1d8de0b3..9e20d34d856d 100644
@@ -9657,53 +9657,70 @@ static void kvm_inject_exception(struct kvm_vcpu *vcpu)
 
 static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
 {
+	bool can_inject = !kvm_event_needs_reinjection(vcpu);
 	int r;
-	bool can_inject = true;
 
-	/* try to reinject previous events if any */
+	/*
+	 * Process nested events first, as nested VM-Exit supercedes event
+	 * re-injection.  If there's an event queued for re-injection, it will
+	 * be saved into the appropriate vmc{b,s}12 fields on nested VM-Exit.
+	 */
+	if (is_guest_mode(vcpu))
+		r = kvm_check_nested_events(vcpu);
+	else
+		r = 0;
 
-	if (vcpu->arch.exception.injected) {
+	/*
+	 * Re-inject exceptions and events *especially* if immediate entry+exit
+	 * to/from L2 is needed, as any event that has already been injected
+	 * into L2 needs to complete its lifecycle before injecting a new event.
+	 *
+	 * Don't re-inject an NMI or interrupt if there is a pending exception.
+	 * This collision arises if an exception occurred while vectoring the
+	 * injected event, KVM intercepted said exception, and KVM ultimately
+	 * determined the fault belongs to the guest and queues the exception
+	 * for injection back into the guest.
+	 *
+	 * "Injected" interrupts can also collide with pending exceptions if
+	 * userspace ignores the "ready for injection" flag and blindly queues
+	 * an interrupt.  In that case, prioritizing the exception is correct,
+	 * as the exception "occurred" before the exit to userspace.  Trap-like
+	 * exceptions, e.g. most #DBs, have higher priority than interrupts.
+	 * And while fault-like exceptions, e.g. #GP and #PF, are the lowest
+	 * priority, they're only generated (pended) during instruction
+	 * execution, and interrupts are recognized at instruction boundaries.
+	 * Thus a pending fault-like exception means the fault occurred on the
+	 * *previous* instruction and must be serviced prior to recognizing any
+	 * new events in order to fully complete the previous instruction.
+	 */
+	if (vcpu->arch.exception.injected)
 		kvm_inject_exception(vcpu);
-		can_inject = false;
-	}
+	else if (vcpu->arch.exception.pending)
+		; /* see above */
+	else if (vcpu->arch.nmi_injected)
+		static_call(kvm_x86_inject_nmi)(vcpu);
+	else if (vcpu->arch.interrupt.injected)
+		static_call(kvm_x86_inject_irq)(vcpu, true);
+
 	/*
-	 * Do not inject an NMI or interrupt if there is a pending
-	 * exception.  Exceptions and interrupts are recognized at
-	 * instruction boundaries, i.e. the start of an instruction.
-	 * Trap-like exceptions, e.g. #DB, have higher priority than
-	 * NMIs and interrupts, i.e. traps are recognized before an
-	 * NMI/interrupt that's pending on the same instruction.
-	 * Fault-like exceptions, e.g. #GP and #PF, are the lowest
-	 * priority, but are only generated (pended) during instruction
-	 * execution, i.e. a pending fault-like exception means the
-	 * fault occurred on the *previous* instruction and must be
-	 * serviced prior to recognizing any new events in order to
-	 * fully complete the previous instruction.
+	 * Exceptions that morph to VM-Exits are handled above, and pending
+	 * exceptions on top of injected exceptions that do not VM-Exit should
+	 * either morph to #DF or, sadly, override the injected exception.
 	 */
-	else if (!vcpu->arch.exception.pending) {
-		if (vcpu->arch.nmi_injected) {
-			static_call(kvm_x86_inject_nmi)(vcpu);
-			can_inject = false;
-		} else if (vcpu->arch.interrupt.injected) {
-			static_call(kvm_x86_inject_irq)(vcpu, true);
-			can_inject = false;
-		}
-	}
-
 	WARN_ON_ONCE(vcpu->arch.exception.injected &&
 		     vcpu->arch.exception.pending);
 
 	/*
-	 * Call check_nested_events() even if we reinjected a previous event
-	 * in order for caller to determine if it should require immediate-exit
-	 * from L2 to L1 due to pending L1 events which require exit
-	 * from L2 to L1.
+	 * Bail if immediate entry+exit to/from the guest is needed to complete
+	 * nested VM-Enter or event re-injection so that a different pending
+	 * event can be serviced (or if KVM needs to exit to userspace).
+	 *
+	 * Otherwise, continue processing events even if VM-Exit occurred.  The
+	 * VM-Exit will have cleared exceptions that were meant for L2, but
+	 * there may now be events that can be injected into L1.
 	 */
-	if (is_guest_mode(vcpu)) {
-		r = kvm_check_nested_events(vcpu);
-		if (r < 0)
-			goto out;
-	}
+	if (r < 0)
+		goto out;
 
 	/* try to inject new event if pending */
 	if (vcpu->arch.exception.pending) {
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#19 lore raw

PATCH v2 16/24 KVM: x86: Evaluate ability to inject SMI/NMI/IRQ after potential VM-Exit

In reply to Sean Christopherson

Determine whether or not new events can be injected after checking nested events. If a VM-Exit occurred during nested event handling, any previous event that needed re-injection is gone from's KVM perspective; the event is captured in the vmc*12 VM-Exit information, but doesn't exist in terms of what needs to be done for entry to L1.

---
 arch/x86/kvm/x86.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +8 -2
index 9e20d34d856d..795c799fc767 100644
@@ -9657,7 +9657,7 @@ static void kvm_inject_exception(struct kvm_vcpu *vcpu)
 
 static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
 {
-	bool can_inject = !kvm_event_needs_reinjection(vcpu);
+	bool can_inject;
 	int r;
 
 	/*
@@ -9722,7 +9722,13 @@ static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
 	if (r < 0)
 		goto out;
 
-	/* try to inject new event if pending */
+	/*
+	 * New events, other than exceptions, cannot be injected if KVM needs
+	 * to re-inject a previous event.  See above comments on re-injecting
+	 * for why pending exceptions get priority.
+	 */
+	can_inject = !kvm_event_needs_reinjection(vcpu);
+
 	if (vcpu->arch.exception.pending) {
 		/*
 		 * Fault-class exceptions, except #DBs, set RF=1 in the RFLAGS
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#20 lore raw

PATCH v2 17/24 KVM: nVMX: Add a helper to identify low-priority #DB traps

In reply to Sean Christopherson

Add a helper to identify "low"-priority #DB traps, i.e. trap-like #DBs that aren't TSS T flag #DBs, and tweak the related code to operate on any queued exception. A future commit will separate exceptions that are intercepted by L1, i.e. cause nested VM-Exit, from those that do NOT trigger nested VM-Exit. I.e. there will be multiple exception structs and multiple invocations of the helpers.

No functional change intended.

---
 arch/x86/kvm/vmx/nested.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
arch/x86/kvm/vmx/nested.c +17 -6
index a0a4eddce445..c3fc8b484785 100644
@@ -3859,14 +3859,24 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
  * from the emulator (because such #DBs are fault-like and thus don't trigger
  * actions that fire on instruction retire).
  */
-static inline unsigned long vmx_get_pending_dbg_trap(struct kvm_vcpu *vcpu)
+static unsigned long vmx_get_pending_dbg_trap(struct kvm_queued_exception *ex)
 {
-	if (!vcpu->arch.exception.pending ||
-	    vcpu->arch.exception.vector != DB_VECTOR)
+	if (!ex->pending || ex->vector != DB_VECTOR)
 		return 0;
 
 	/* General Detect #DBs are always fault-like. */
-	return vcpu->arch.exception.payload & ~DR6_BD;
+	return ex->payload & ~DR6_BD;
+}
+
+/*
+ * Returns true if there's a pending #DB exception that is lower priority than
+ * a pending Monitor Trap Flag VM-Exit.  TSS T-flag #DBs are not emulated by
+ * KVM, but could theoretically be injected by userspace.  Note, this code is
+ * imperfect, see above.
+ */
+static bool vmx_is_low_priority_db_trap(struct kvm_queued_exception *ex)
+{
+	return vmx_get_pending_dbg_trap(ex) & ~DR6_BT;
 }
 
 /*
@@ -3878,8 +3888,9 @@ static inline unsigned long vmx_get_pending_dbg_trap(struct kvm_vcpu *vcpu)
  */
 static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
 {
-	unsigned long pending_dbg = vmx_get_pending_dbg_trap(vcpu);
+	unsigned long pending_dbg;
 
+	pending_dbg = vmx_get_pending_dbg_trap(&vcpu->arch.exception);
 	if (pending_dbg)
 		vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, pending_dbg);
 }
@@ -3949,7 +3960,7 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 	 * prioritize SMI over MTF and trap-like #DBs.
 	 */
 	if (vcpu->arch.exception.pending &&
-	    !(vmx_get_pending_dbg_trap(vcpu) & ~DR6_BT)) {
+	    !vmx_is_low_priority_db_trap(&vcpu->arch.exception)) {
 		if (block_nested_exceptions)
 			return -EBUSY;
 		if (!nested_vmx_check_exception(vcpu, &exit_qual))
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
Reviewed-by on v2 17/24
#21 lore raw

Re: [PATCH v2 17/24] KVM: nVMX: Add a helper to identify low-priority #DB traps

Quoted 61 lines · Sean Christopherson

Add a helper to identify "low"-priority #DB traps, i.e. trap-like #DBs that aren't TSS T flag #DBs, and tweak the related code to operate on any queued exception.  A future commit will separate exceptions that are intercepted by L1, i.e. cause nested VM-Exit, from those that do NOT trigger nested VM-Exit.  I.e. there will be multiple exception structs and multiple invocations of the helpers.

No functional change intended.

---
 arch/x86/kvm/vmx/nested.c | 23 +++++++++++++++++------

 1 file changed, 17 insertions(+), 6 deletions(-)
arch/x86/kvm/vmx/nested.c +2 -3
index a0a4eddce445..c3fc8b484785 100644
@@ -3859,14 +3859,24 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
   * from the emulator (because such #DBs are fault-like and thus don't trigger
   * actions that fire on instruction retire).
   */
-static inline unsigned long vmx_get_pending_dbg_trap(struct kvm_vcpu *vcpu)
+static unsigned long vmx_get_pending_dbg_trap(struct kvm_queued_exception *ex)
  {
-       if (!vcpu->arch.exception.pending ||
-           vcpu->arch.exception.vector != DB_VECTOR)
+       if (!ex->pending || ex->vector != DB_VECTOR)
                 return 0;


        /* General Detect #DBs are always fault-like. */ -       return vcpu->arch.exception.payload & ~DR6_BD; +       return ex->payload & ~DR6_BD;

arch/x86/kvm/vmx/nested.c +11 -0
+}
+
+/*
+ * Returns true if there's a pending #DB exception that is lower priority than
+ * a pending Monitor Trap Flag VM-Exit.  TSS T-flag #DBs are not emulated by
+ * KVM, but could theoretically be injected by userspace.  Note, this code is
+ * imperfect, see above.
+ */
+static bool vmx_is_low_priority_db_trap(struct kvm_queued_exception *ex)
+{
+       return vmx_get_pending_dbg_trap(ex) & ~DR6_BT;

 }

 /*

arch/x86/kvm/vmx/nested.c +1 -1
@@ -3878,8 +3888,9 @@ static inline unsigned long vmx_get_pending_dbg_trap(struct kvm_vcpu *vcpu)
   */
  static void nested_vmx_update_pending_dbg(struct kvm_vcpu *vcpu)
  {
-       unsigned long pending_dbg = vmx_get_pending_dbg_trap(vcpu);
+       unsigned long pending_dbg;


+       pending_dbg = vmx_get_pending_dbg_trap(&vcpu->arch.exception); if (pending_dbg) vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, pending_dbg); }

arch/x86/kvm/vmx/nested.c +0 -0
@@ -3949,7 +3960,7 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
          * prioritize SMI over MTF and trap-like #DBs.
          */
Quoted 6 lines

        if (vcpu->arch.exception.pending &&
-           !(vmx_get_pending_dbg_trap(vcpu) & ~DR6_BT)) { +           !vmx_is_low_priority_db_trap(&vcpu->arch.exception)) { if (block_nested_exceptions)
                        return -EBUSY;
                if (!nested_vmx_check_exception(vcpu, &exit_qual))

Best regards,
Maxim Levitsky

author maintainer
#22 lore raw

PATCH v2 18/24 KVM: nVMX: Document priority of all known events on Intel CPUs

In reply to Sean Christopherson

Add a gigantic comment above vmx_check_nested_events() to document the priorities of all known events on Intel CPUs. Intel's SDM doesn't include VMX-specific events in its "Priority Among Concurrent Events", which makes it painfully difficult to suss out the correct priority between things like Monitor Trap Flag VM-Exits and pending #DBs.

Kudos to Jim Mattson for doing the hard work of collecting and interpreting the priorities from various locations throughtout the SDM (because putting them all in one place in the SDM would be too easy).

---
 arch/x86/kvm/vmx/nested.c | 83 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 83 insertions(+)
arch/x86/kvm/vmx/nested.c +83 -0
index c3fc8b484785..981f98ef96f1 100644
@@ -3901,6 +3901,89 @@ static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
 	       to_vmx(vcpu)->nested.preemption_timer_expired;
 }
 
+/*
+ * Per the Intel SDM's table "Priority Among Concurrent Events", with minor
+ * edits to fill in missing examples, e.g. #DB due to split-lock accesses,
+ * and less minor edits to splice in the priority of VMX Non-Root specific
+ * events, e.g. MTF and NMI/INTR-window exiting.
+ *
+ * 1 Hardware Reset and Machine Checks
+ *	- RESET
+ *	- Machine Check
+ *
+ * 2 Trap on Task Switch
+ *	- T flag in TSS is set (on task switch)
+ *
+ * 3 External Hardware Interventions
+ *	- FLUSH
+ *	- STOPCLK
+ *	- SMI
+ *	- INIT
+ *
+ * 3.5 Monitor Trap Flag (MTF) VM-exit[1]
+ *
+ * 4 Traps on Previous Instruction
+ *	- Breakpoints
+ *	- Trap-class Debug Exceptions (#DB due to TF flag set, data/I-O
+ *	  breakpoint, or #DB due to a split-lock access)
+ *
+ * 4.3	VMX-preemption timer expired VM-exit
+ *
+ * 4.6	NMI-window exiting VM-exit[2]
+ *
+ * 5 Nonmaskable Interrupts (NMI)
+ *
+ * 5.5 Interrupt-window exiting VM-exit and Virtual-interrupt delivery
+ *
+ * 6 Maskable Hardware Interrupts
+ *
+ * 7 Code Breakpoint Fault
+ *
+ * 8 Faults from Fetching Next Instruction
+ *	- Code-Segment Limit Violation
+ *	- Code Page Fault
+ *	- Control protection exception (missing ENDBRANCH at target of indirect
+ *					call or jump)
+ *
+ * 9 Faults from Decoding Next Instruction
+ *	- Instruction length > 15 bytes
+ *	- Invalid Opcode
+ *	- Coprocessor Not Available
+ *
+ *10 Faults on Executing Instruction
+ *	- Overflow
+ *	- Bound error
+ *	- Invalid TSS
+ *	- Segment Not Present
+ *	- Stack fault
+ *	- General Protection
+ *	- Data Page Fault
+ *	- Alignment Check
+ *	- x86 FPU Floating-point exception
+ *	- SIMD floating-point exception
+ *	- Virtualization exception
+ *	- Control protection exception
+ *
+ * [1] Per the "Monitor Trap Flag" section: System-management interrupts (SMIs),
+ *     INIT signals, and higher priority events take priority over MTF VM exits.
+ *     MTF VM exits take priority over debug-trap exceptions and lower priority
+ *     events.
+ *
+ * [2] Debug-trap exceptions and higher priority events take priority over VM exits
+ *     caused by the VMX-preemption timer.  VM exits caused by the VMX-preemption
+ *     timer take priority over VM exits caused by the "NMI-window exiting"
+ *     VM-execution control and lower priority events.
+ *
+ * [3] Debug-trap exceptions and higher priority events take priority over VM exits
+ *     caused by "NMI-window exiting".  VM exits caused by this control take
+ *     priority over non-maskable interrupts (NMIs) and lower priority events.
+ *
+ * [4] Virtual-interrupt delivery has the same priority as that of VM exits due to
+ *     the 1-setting of the "interrupt-window exiting" VM-execution control.  Thus,
+ *     non-maskable interrupts (NMIs) and higher priority events take priority over
+ *     delivery of a virtual interrupt; delivery of a virtual interrupt takes
+ *     priority over external interrupts and lower priority events.
+ */
 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 {
 	struct kvm_lapic *apic = vcpu->arch.apic;
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
Reviewed-by on v2 18/24
#23 lore raw

Re: [PATCH v2 18/24] KVM: nVMX: Document priority of all known events on Intel CPUs

Quoted 102 lines · Sean Christopherson

Add a gigantic comment above vmx_check_nested_events() to document the priorities of all known events on Intel CPUs.  Intel's SDM doesn't include VMX-specific events in its "Priority Among Concurrent Events", which makes it painfully difficult to suss out the correct priority between things like Monitor Trap Flag VM-Exits and pending #DBs.

Kudos to Jim Mattson for doing the hard work of collecting and interpreting the priorities from various locations throughtout the SDM (because putting them all in one place in the SDM would be too easy).

---
 arch/x86/kvm/vmx/nested.c | 83 +++++++++++++++++++++++++++++++++++++++

 1 file changed, 83 insertions(+)
arch/x86/kvm/vmx/nested.c +0 -0
index c3fc8b484785..981f98ef96f1 100644
@@ -3901,6 +3901,89 @@ static bool nested_vmx_preemption_timer_pending(struct kvm_vcpu *vcpu)
                to_vmx(vcpu)->nested.preemption_timer_expired;
  }


+/*
+ * Per the Intel SDM's table "Priority Among Concurrent Events", with minor
+ * edits to fill in missing examples, e.g. #DB due to split-lock accesses,
+ * and less minor edits to splice in the priority of VMX Non-Root specific
+ * events, e.g. MTF and NMI/INTR-window exiting.
+ *
+ * 1 Hardware Reset and Machine Checks
+ *     - RESET
+ *     - Machine Check
+ *
+ * 2 Trap on Task Switch
+ *     - T flag in TSS is set (on task switch)
+ *
+ * 3 External Hardware Interventions
+ *     - FLUSH
+ *     - STOPCLK
+ *     - SMI
+ *     - INIT
+ *
+ * 3.5 Monitor Trap Flag (MTF) VM-exit[1]
+ *
+ * 4 Traps on Previous Instruction
+ *     - Breakpoints
+ *     - Trap-class Debug Exceptions (#DB due to TF flag set, data/I-O
+ *       breakpoint, or #DB due to a split-lock access)
+ *
+ * 4.3 VMX-preemption timer expired VM-exit
+ *
+ * 4.6 NMI-window exiting VM-exit[2]
+ *
+ * 5 Nonmaskable Interrupts (NMI)
+ *
+ * 5.5 Interrupt-window exiting VM-exit and Virtual-interrupt delivery
+ *
+ * 6 Maskable Hardware Interrupts
+ *
+ * 7 Code Breakpoint Fault
+ *
+ * 8 Faults from Fetching Next Instruction
+ *     - Code-Segment Limit Violation
+ *     - Code Page Fault
+ *     - Control protection exception (missing ENDBRANCH at target of indirect
+ *                                     call or jump)
+ *
+ * 9 Faults from Decoding Next Instruction
+ *     - Instruction length > 15 bytes
+ *     - Invalid Opcode
+ *     - Coprocessor Not Available
+ *
+ *10 Faults on Executing Instruction
+ *     - Overflow
+ *     - Bound error
+ *     - Invalid TSS
+ *     - Segment Not Present
+ *     - Stack fault
+ *     - General Protection
+ *     - Data Page Fault
+ *     - Alignment Check
+ *     - x86 FPU Floating-point exception
+ *     - SIMD floating-point exception
+ *     - Virtualization exception
+ *     - Control protection exception
+ *
+ * [1] Per the "Monitor Trap Flag" section: System-management interrupts (SMIs),
+ *     INIT signals, and higher priority events take priority over MTF VM exits.
+ *     MTF VM exits take priority over debug-trap exceptions and lower priority
+ *     events.
+ *
+ * [2] Debug-trap exceptions and higher priority events take priority over VM exits
+ *     caused by the VMX-preemption timer.  VM exits caused by the VMX-preemption
+ *     timer take priority over VM exits caused by the "NMI-window exiting"
+ *     VM-execution control and lower priority events.
+ *
+ * [3] Debug-trap exceptions and higher priority events take priority over VM exits
+ *     caused by "NMI-window exiting".  VM exits caused by this control take
+ *     priority over non-maskable interrupts (NMIs) and lower priority events.
+ *
+ * [4] Virtual-interrupt delivery has the same priority as that of VM exits due to

Quoted 8 lines

+ *     the 1-setting of the "interrupt-window exiting" VM-execution control.  Thus,
+ *     non-maskable interrupts (NMIs) and higher priority events take priority over
+ *     delivery of a virtual interrupt; delivery of a virtual interrupt takes
+ *     priority over external interrupts and lower priority events.
+ */
 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
 {
        struct kvm_lapic *apic = vcpu->arch.apic;

Best regards,
Maxim Levitsky

author maintainer
#24 lore raw

PATCH v2 19/24 KVM: x86: Morph pending exceptions to pending VM-Exits at queue time

In reply to Sean Christopherson

Morph pending exceptions to pending VM-Exits (due to interception) when the exception is queued instead of waiting until nested events are checked at VM-Entry. This fixes a longstanding bug where KVM fails to handle an exception that occurs during delivery of a previous exception, KVM (L0) and L1 both want to intercept the exception (e.g. #PF for shadow paging), and KVM determines that the exception is in the guest's domain, i.e. queues the new exception for L2. Deferring the interception check causes KVM to esclate various combinations of injected+pending exceptions to double fault (#DF) without consulting L1's interception desires, and ends up injecting a spurious #DF into L2.

KVM has fudged around the issue for #PF by special casing emulated #PF injection for shadow paging, but the underlying issue is not unique to shadow paging in L0, e.g. if KVM is intercepting #PF because the guest has a smaller maxphyaddr and L1 (but not L0) is using shadow paging. Other exceptions are affected as well, e.g. if KVM is intercepting #GP for one of SVM's workaround or for the VMware backdoor emulation stuff. The other cases have gone unnoticed because the #DF is spurious if and only if L1 resolves the exception, e.g. KVM's goofs go unnoticed if L1 would have injected #DF anyways.

The hack-a-fix has also led to ugly code, e.g. bailing from the emulator if #PF injection forced a nested VM-Exit and the emulator finds itself back in L1. Allowing for direct-to-VM-Exit queueing also neatly solves the async #PF in L2 mess; no need to set a magic flag and token, simply queue a #PF nested VM-Exit.

Deal with event migration by flagging that a pending exception was queued by userspace and check for interception at the next KVM_RUN, e.g. so that KVM does the right thing regardless of the order in which userspace restores nested state vs. event state.

When "getting" events from userspace, simply drop any pending excpetion that is destined to be intercepted if there is also an injected exception to be migrated. Ideally, KVM would migrate both events, but that would require new ABI, and practically speaking losing the event is unlikely to be noticed, let alone fatal. The injected exception is captured, RIP still points at the original faulting instruction, etc... So either the injection on the target will trigger the same intercepted exception, or the source of the intercepted exception was transient and/or non-deterministic, thus dropping it is ok-ish.

Fixes a04aead144fd ("KVM: nSVM: fix running nested guests when npt=0")
Fixes feaf0c7dc473 ("KVM: nVMX: Do not generate #DF if #PF happens during exception delivery into L2")
Cc Jim Mattson <[email protected]>
---
 arch/x86/include/asm/kvm_host.h |  12 ++-
 arch/x86/kvm/svm/nested.c       |  41 +++-----
 arch/x86/kvm/vmx/nested.c       | 109 ++++++++++------------
 arch/x86/kvm/vmx/vmx.c          |   6 +-
 arch/x86/kvm/x86.c              | 159 ++++++++++++++++++++++----------
 arch/x86/kvm/x86.h              |   7 ++
 6 files changed, 187 insertions(+), 147 deletions(-)
arch/x86/include/asm/kvm_host.h +7 -5
index 0a6a05e25f24..6bcbffb42420 100644
@@ -647,7 +647,6 @@ struct kvm_queued_exception {
 	u32 error_code;
 	unsigned long payload;
 	bool has_payload;
-	u8 nested_apf;
 };
 
 struct kvm_vcpu_arch {
@@ -748,8 +747,12 @@ struct kvm_vcpu_arch {
 
 	u8 event_exit_inst_len;
 
+	bool exception_from_userspace;
+
 	/* Exceptions to be injected to the guest. */
 	struct kvm_queued_exception exception;
+	/* Exception VM-Exits to be synthesized to L1. */
+	struct kvm_queued_exception exception_vmexit;
 
 	struct kvm_queued_interrupt {
 		bool injected;
@@ -860,7 +863,6 @@ struct kvm_vcpu_arch {
 		u32 id;
 		bool send_user_only;
 		u32 host_apf_flags;
-		unsigned long nested_apf_token;
 		bool delivery_as_pf_vmexit;
 		bool pageready_pending;
 	} apf;
@@ -1636,9 +1638,9 @@ struct kvm_x86_ops {
 
 struct kvm_x86_nested_ops {
 	void (*leave_nested)(struct kvm_vcpu *vcpu);
+	bool (*is_exception_vmexit)(struct kvm_vcpu *vcpu, u8 vector,
+				    u32 error_code);
 	int (*check_events)(struct kvm_vcpu *vcpu);
-	bool (*handle_page_fault_workaround)(struct kvm_vcpu *vcpu,
-					     struct x86_exception *fault);
 	bool (*hv_timer_pending)(struct kvm_vcpu *vcpu);
 	void (*triple_fault)(struct kvm_vcpu *vcpu);
 	int (*get_state)(struct kvm_vcpu *vcpu,
@@ -1865,7 +1867,7 @@ void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr, unsigned long pay
 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr);
 void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault);
-bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
+void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 				    struct x86_exception *fault);
 bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl);
 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr);
arch/x86/kvm/svm/nested.c +12 -29

79 lines not on this page · raw message

arch/x86/kvm/vmx/nested.c +47 -62

160 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.c +4 -2
index 7d3abe2a206a..5302b046110f 100644
@@ -1585,7 +1585,9 @@ static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
 	 */
 	if (nested_cpu_has_mtf(vmcs12) &&
 	    (!vcpu->arch.exception.pending ||
-	     vcpu->arch.exception.vector == DB_VECTOR))
+	     vcpu->arch.exception.vector == DB_VECTOR) &&
+	    (!vcpu->arch.exception_vmexit.pending ||
+	     vcpu->arch.exception_vmexit.vector == DB_VECTOR))
 		vmx->nested.mtf_pending = true;
 	else
 		vmx->nested.mtf_pending = false;
@@ -5637,7 +5639,7 @@ static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
 	return vmx->emulation_required && !vmx->rmode.vm86_active &&
-	       (vcpu->arch.exception.pending || vcpu->arch.exception.injected);
+	       (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected);
 }
 
 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
arch/x86/kvm/x86.c +110 -49

291 lines not on this page · raw message

arch/x86/kvm/x86.h +7 -0
index dc2af0146220..eee259e387d3 100644
@@ -82,10 +82,17 @@ static inline unsigned int __shrink_ple_window(unsigned int val,
 void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu);
 int kvm_check_nested_events(struct kvm_vcpu *vcpu);
 
+static inline bool kvm_is_exception_pending(struct kvm_vcpu *vcpu)
+{
+	return vcpu->arch.exception.pending ||
+	       vcpu->arch.exception_vmexit.pending;
+}
+
 static inline void kvm_clear_exception_queue(struct kvm_vcpu *vcpu)
 {
 	vcpu->arch.exception.pending = false;
 	vcpu->arch.exception.injected = false;
+	vcpu->arch.exception_vmexit.pending = false;
 }
 
 static inline void kvm_queue_interrupt(struct kvm_vcpu *vcpu, u8 vector,
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
Reviewed-by on v2 19/24
#25 lore raw

Re: [PATCH v2 19/24] KVM: x86: Morph pending exceptions to pending VM-Exits at queue time

Quoted 717 lines · Sean Christopherson

Morph pending exceptions to pending VM-Exits (due to interception) when the exception is queued instead of waiting until nested events are checked at VM-Entry.  This fixes a longstanding bug where KVM fails to handle an exception that occurs during delivery of a previous exception, KVM (L0) and L1 both want to intercept the exception (e.g. #PF for shadow paging), and KVM determines that the exception is in the guest's domain, i.e. queues the new exception for L2.  Deferring the interception check causes KVM to esclate various combinations of injected+pending exceptions to double fault (#DF) without consulting L1's interception desires, and ends up injecting a spurious #DF into L2.

KVM has fudged around the issue for #PF by special casing emulated #PF injection for shadow paging, but the underlying issue is not unique to shadow paging in L0, e.g. if KVM is intercepting #PF because the guest has a smaller maxphyaddr and L1 (but not L0) is using shadow paging. Other exceptions are affected as well, e.g. if KVM is intercepting #GP for one of SVM's workaround or for the VMware backdoor emulation stuff. The other cases have gone unnoticed because the #DF is spurious if and only if L1 resolves the exception, e.g. KVM's goofs go unnoticed if L1 would have injected #DF anyways.

The hack-a-fix has also led to ugly code, e.g. bailing from the emulator if #PF injection forced a nested VM-Exit and the emulator finds itself back in L1.  Allowing for direct-to-VM-Exit queueing also neatly solves the async #PF in L2 mess; no need to set a magic flag and token, simply queue a #PF nested VM-Exit.

Deal with event migration by flagging that a pending exception was queued by userspace and check for interception at the next KVM_RUN, e.g. so that KVM does the right thing regardless of the order in which userspace restores nested state vs. event state.

When "getting" events from userspace, simply drop any pending excpetion that is destined to be intercepted if there is also an injected exception to be migrated.  Ideally, KVM would migrate both events, but that would require new ABI, and practically speaking losing the event is unlikely to be noticed, let alone fatal.  The injected exception is captured, RIP still points at the original faulting instruction, etc...  So either the injection on the target will trigger the same intercepted exception, or the source of the intercepted exception was transient and/or non-deterministic, thus dropping it is ok-ish.

Fixes a04aead144fd ("KVM: nSVM: fix running nested guests when npt=0")
Fixes feaf0c7dc473 ("KVM: nVMX: Do not generate #DF if #PF happens during exception delivery into L2")
Cc Jim Mattson <[email protected]>

---
 arch/x86/include/asm/kvm_host.h |  12 ++- arch/x86/kvm/svm/nested.c       |  41 +++----- arch/x86/kvm/vmx/nested.c       | 109 ++++++++++------------ arch/x86/kvm/vmx/vmx.c          |   6 +-
 arch/x86/kvm/x86.c              | 159 ++++++++++++++++++++++---------- arch/x86/kvm/x86.h              |   7 ++

 6 files changed, 187 insertions(+), 147 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -1
index 0a6a05e25f24..6bcbffb42420 100644
@@ -647,7 +647,6 @@ struct kvm_queued_exception {
         u32 error_code;
         unsigned long payload;
         bool has_payload;
-       u8 nested_apf;
  };


 struct kvm_vcpu_arch {

arch/x86/include/asm/kvm_host.h +0 -0
@@ -748,8 +747,12 @@ struct kvm_vcpu_arch {


        u8 event_exit_inst_len;

+       bool exception_from_userspace;
+
        /* Exceptions to be injected to the guest. */ struct kvm_queued_exception exception;
+       /* Exception VM-Exits to be synthesized to L1. */ +       struct kvm_queued_exception exception_vmexit;
        struct kvm_queued_interrupt {
                bool injected;

arch/x86/include/asm/kvm_host.h +0 -1
@@ -860,7 +863,6 @@ struct kvm_vcpu_arch {
                 u32 id;
                 bool send_user_only;
                 u32 host_apf_flags;
-               unsigned long nested_apf_token;
                 bool delivery_as_pf_vmexit;
                 bool pageready_pending;
         } apf;
@@ -1636,9 +1638,9 @@ struct kvm_x86_ops {


 struct kvm_x86_nested_ops {
        void (*leave_nested)(struct kvm_vcpu *vcpu);
+       bool (*is_exception_vmexit)(struct kvm_vcpu *vcpu, u8 vector, +                                   u32 error_code);
        int (*check_events)(struct kvm_vcpu *vcpu);
-       bool (*handle_page_fault_workaround)(struct kvm_vcpu *vcpu, -                                            struct x86_exception *fault); bool (*hv_timer_pending)(struct kvm_vcpu *vcpu);
        void (*triple_fault)(struct kvm_vcpu *vcpu);
        int (*get_state)(struct kvm_vcpu *vcpu,

arch/x86/include/asm/kvm_host.h +1 -1
@@ -1865,7 +1867,7 @@ void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr, unsigned long pay
  void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr);
  void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
  void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault);
-bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
+void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
                                     struct x86_exception *fault);
  bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl);
  bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr);
arch/x86/kvm/svm/nested.c +0 -0
index f5676c2679d0..0a8ee5f28319 100644
@@ -55,28 +55,6 @@ static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
         nested_svm_vmexit(svm);
  }

arch/x86/kvm/svm/nested.c +0 -22
-static bool nested_svm_handle_page_fault_workaround(struct kvm_vcpu *vcpu,
-                                                   struct x86_exception *fault)
-{
-       struct vcpu_svm *svm = to_svm(vcpu);
-       struct vmcb *vmcb = svm->vmcb;
-
-       WARN_ON(!is_guest_mode(vcpu));
-
-       if (vmcb12_is_intercept(&svm->nested.ctl,
-                               INTERCEPT_EXCEPTION_OFFSET + PF_VECTOR) &&
-           !WARN_ON_ONCE(svm->nested.nested_run_pending)) {
-               vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + PF_VECTOR;
-               vmcb->control.exit_code_hi = 0;
-               vmcb->control.exit_info_1 = fault->error_code;
-               vmcb->control.exit_info_2 = fault->address;
-               nested_svm_vmexit(svm);
-               return true;
-       }
-
-       return false;
-}
-

 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index) {
        struct vcpu_svm *svm = to_svm(vcpu);

arch/x86/kvm/svm/nested.c +0 -0
@@ -1302,16 +1280,17 @@ int nested_svm_check_permissions(struct kvm_vcpu *vcpu)
         return 0;
  }

arch/x86/kvm/svm/nested.c +2 -1
-static bool nested_exit_on_exception(struct vcpu_svm *svm)
+static bool nested_svm_is_exception_vmexit(struct kvm_vcpu *vcpu, u8 vector,
+                                          u32 error_code)

 {
-       unsigned int vector = svm->vcpu.arch.exception.vector;
+       struct vcpu_svm *svm = to_svm(vcpu);

        return (svm->nested.ctl.intercepts[INTERCEPT_EXCEPTION] & BIT(vector)); }

 static void nested_svm_inject_exception_vmexit(struct kvm_vcpu *vcpu) {
-       struct kvm_queued_exception *ex = &vcpu->arch.exception;
+       struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit; struct vcpu_svm *svm = to_svm(vcpu);
        struct vmcb *vmcb = svm->vmcb;

arch/x86/kvm/svm/nested.c +0 -0
@@ -1379,15 +1358,19 @@ static int svm_check_nested_events(struct kvm_vcpu *vcpu)
                 return 0;
         }


-       if (vcpu->arch.exception.pending) {
+       if (vcpu->arch.exception_vmexit.pending) {
                if (block_nested_exceptions)
                         return -EBUSY;
-               if (!nested_exit_on_exception(svm))
-                       return 0; nested_svm_inject_exception_vmexit(vcpu); return 0;
        }

+       if (vcpu->arch.exception.pending) {
+               if (block_nested_exceptions)
+                       return -EBUSY;
+               return 0;
+       }
+
        if (vcpu->arch.smi_pending && !svm_smi_blocked(vcpu)) { if (block_nested_events)
                        return -EBUSY;

arch/x86/kvm/svm/nested.c +0 -0
@@ -1725,8 +1708,8 @@ static bool svm_get_nested_state_pages(struct kvm_vcpu *vcpu)


 struct kvm_x86_nested_ops svm_nested_ops = {
        .leave_nested = svm_leave_nested,
+       .is_exception_vmexit = nested_svm_is_exception_vmexit, .check_events = svm_check_nested_events,
-       .handle_page_fault_workaround = nested_svm_handle_page_fault_workaround, .triple_fault = nested_svm_triple_fault, .get_nested_state_pages = svm_get_nested_state_pages, .get_state = svm_get_nested_state,

arch/x86/kvm/vmx/nested.c +0 -0
index 981f98ef96f1..5a6ba62dcd49 100644
@@ -439,59 +439,22 @@ static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
         return inequality ^ bit;
  }

arch/x86/kvm/vmx/nested.c +2 -38
-
-/*
- * 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.
- */
-static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
-{
-       struct kvm_queued_exception *ex = &vcpu->arch.exception;
-       struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
-
-       if (ex->vector == PF_VECTOR) {
-               if (ex->nested_apf) {
-                       *exit_qual = vcpu->arch.apf.nested_apf_token;
-                       return 1;
-               }
-               if (nested_vmx_is_page_fault_vmexit(vmcs12, ex->error_code)) {
-                       *exit_qual = ex->has_payload ? ex->payload : vcpu->arch.cr2;
-                       return 1;
-               }
-       } else if (vmcs12->exception_bitmap & (1u << ex->vector)) {
-               if (ex->vector == DB_VECTOR) {
-                       if (ex->has_payload) {
-                               *exit_qual = ex->payload;
-                       } else {
-                               *exit_qual = vcpu->arch.dr6;
-                               *exit_qual &= ~DR6_BT;
-                               *exit_qual ^= DR6_ACTIVE_LOW;
-                       }
-               } else
-                       *exit_qual = 0;
-               return 1;
-       }
-
-       return 0;
-}
-
-static bool nested_vmx_handle_page_fault_workaround(struct kvm_vcpu *vcpu,
-                                                   struct x86_exception *fault)
+static bool nested_vmx_is_exception_vmexit(struct kvm_vcpu *vcpu, u8 vector,
+                                          u32 error_code)

 {
        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);

-       WARN_ON(!is_guest_mode(vcpu));
+       /*
+        * Drop bits 31:16 of the error code when performing the #PF mask+match +        * check.  All VMCS fields involved are 32 bits, but Intel CPUs never +        * set bits 31:16 and VMX disallows setting bits 31:16 in the injected +        * error code.  Including the to-be-dropped bits in the check might +        * result in an "impossible" or missed exit from L1's perspective. +        */
+       if (vector == PF_VECTOR)
+               return nested_vmx_is_page_fault_vmexit(vmcs12, (u16)error_code);
-       if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) && -           !WARN_ON_ONCE(to_vmx(vcpu)->nested.nested_run_pending)) {
-               vmcs12->vm_exit_intr_error_code = fault->error_code;
-               nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
-                                 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION | -                                 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK, -                                 fault->address);
-               return true;
-       }
-       return false;
+       return (vmcs12->exception_bitmap & (1u << vector));
 }

 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,

arch/x86/kvm/vmx/nested.c +0 -0
@@ -3812,12 +3775,24 @@ static int vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
         return -ENXIO;
  }

arch/x86/kvm/vmx/nested.c +1 -2
-static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
-                                              unsigned long exit_qual)
+static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu)

 {
-       struct kvm_queued_exception *ex = &vcpu->arch.exception; +       struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit; u32 intr_info = ex->vector | INTR_INFO_VALID_MASK; struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
+       unsigned long exit_qual;
+
+       if (ex->has_payload) {
+               exit_qual = ex->payload;
+       } else if (ex->vector == PF_VECTOR) {
+               exit_qual = vcpu->arch.cr2;
+       } else if (ex->vector == DB_VECTOR) {
+               exit_qual = vcpu->arch.dr6;
+               exit_qual &= ~DR6_BT;
+               exit_qual ^= DR6_ACTIVE_LOW;
+       } else {
+               exit_qual = 0;
+       }

        if (ex->has_error_code) {
                /*

arch/x86/kvm/vmx/nested.c +9 -1
@@ -3988,7 +3963,6 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
  {
         struct kvm_lapic *apic = vcpu->arch.apic;
         struct vcpu_vmx *vmx = to_vmx(vcpu);
-       unsigned long exit_qual;
         /*
          * Only a pending nested run blocks a pending exception.  If there is a
          * previously injected event, the pending exception occurred while said
@@ -4042,14 +4016,20 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
          * across SMI/RSM as it should; that needs to be addressed in order to
          * prioritize SMI over MTF and trap-like #DBs.
          */
+       if (vcpu->arch.exception_vmexit.pending &&
+           !vmx_is_low_priority_db_trap(&vcpu->arch.exception_vmexit)) {
+               if (block_nested_exceptions)
+                       return -EBUSY;
+
+               nested_vmx_inject_exception_vmexit(vcpu);
+               return 0;
+       }
+

        if (vcpu->arch.exception.pending && !vmx_is_low_priority_db_trap(&vcpu->arch.exception)) { if (block_nested_exceptions)
                        return -EBUSY;
-               if (!nested_vmx_check_exception(vcpu, &exit_qual)) -                       goto no_vmexit;
-               nested_vmx_inject_exception_vmexit(vcpu, exit_qual); -               return 0;
+               goto no_vmexit;
        }

        if (vmx->nested.mtf_pending) {

arch/x86/kvm/vmx/nested.c +0 -0
@@ -4060,13 +4040,18 @@ static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
                 return 0;
         }


+       if (vcpu->arch.exception_vmexit.pending) { +               if (block_nested_exceptions) +                       return -EBUSY;

arch/x86/kvm/vmx/nested.c +5 -0
+
+               nested_vmx_inject_exception_vmexit(vcpu);
+               return 0;
+       }
+

        if (vcpu->arch.exception.pending) {
                if (block_nested_exceptions)
                        return -EBUSY;
-               if (!nested_vmx_check_exception(vcpu, &exit_qual)) -                       goto no_vmexit;
-               nested_vmx_inject_exception_vmexit(vcpu, exit_qual); -               return 0;
+               goto no_vmexit;
        }

        if (nested_vmx_preemption_timer_pending(vcpu)) {

arch/x86/kvm/vmx/nested.c +0 -0
@@ -6952,8 +6937,8 @@ __init int nested_vmx_hardware_setup(int (*exit_handlers[])(struct kvm_vcpu *))


 struct kvm_x86_nested_ops vmx_nested_ops = {
        .leave_nested = vmx_leave_nested,
+       .is_exception_vmexit = nested_vmx_is_exception_vmexit, .check_events = vmx_check_nested_events,
-       .handle_page_fault_workaround = nested_vmx_handle_page_fault_workaround, .hv_timer_pending = nested_vmx_preemption_timer_pending, .triple_fault = nested_vmx_triple_fault,
        .get_state = vmx_get_nested_state,

arch/x86/kvm/vmx/vmx.c +0 -0
index 7d3abe2a206a..5302b046110f 100644
@@ -1585,7 +1585,9 @@ static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
          */

        if (nested_cpu_has_mtf(vmcs12) && (!vcpu->arch.exception.pending ||
-            vcpu->arch.exception.vector == DB_VECTOR)) +            vcpu->arch.exception.vector == DB_VECTOR) && +           (!vcpu->arch.exception_vmexit.pending || +            vcpu->arch.exception_vmexit.vector == DB_VECTOR)) vmx->nested.mtf_pending = true;
        else
                vmx->nested.mtf_pending = false;

arch/x86/kvm/vmx/vmx.c +0 -0
@@ -5637,7 +5639,7 @@ static bool vmx_emulation_required_with_pending_exception(struct kvm_vcpu *vcpu)
         struct vcpu_vmx *vmx = to_vmx(vcpu);


        return vmx->emulation_required && !vmx->rmode.vm86_active && -              (vcpu->arch.exception.pending || vcpu->arch.exception.injected); +              (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected); }

 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)

arch/x86/kvm/x86.c +0 -0
index 795c799fc767..9be2fdf834ad 100644
@@ -609,6 +609,21 @@ void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
  }
  EXPORT_SYMBOL_GPL(kvm_deliver_exception_payload);

arch/x86/kvm/x86.c +15 -0
+static void kvm_queue_exception_vmexit(struct kvm_vcpu *vcpu, unsigned int vector,
+                                      bool has_error_code, u32 error_code,
+                                      bool has_payload, unsigned long payload)
+{
+       struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
+
+       ex->vector = vector;
+       ex->injected = false;
+       ex->pending = true;
+       ex->has_error_code = has_error_code;
+       ex->error_code = error_code;
+       ex->has_payload = has_payload;
+       ex->payload = payload;
+}
+

 static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned nr, bool has_error, u32 error_code, bool has_payload, unsigned long payload, bool reinject)

arch/x86/kvm/x86.c +0 -0
@@ -618,18 +633,31 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,


        kvm_make_request(KVM_REQ_EVENT, vcpu);

+       /*
+        * If the exception is destined for L2 and isn't being reinjected, +        * morph it to a VM-Exit if L1 wants to intercept the exception.  A +        * previously injected exception is not checked because it was checked +        * when it was original queued, and re-checking is incorrect if _L1_ +        * injected the exception, in which case it's exempt from interception. +        */
+       if (!reinject && is_guest_mode(vcpu) &&
+           kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, nr, error_code)) { +               kvm_queue_exception_vmexit(vcpu, nr, has_error, error_code, +                                          has_payload, payload);
+               return;
+       }
+
        if (!vcpu->arch.exception.pending && !vcpu->arch.exception.injected) { queue:
                if (reinject) {
                        /*
-                        * On vmentry, vcpu->arch.exception.pending is only -                        * true if an event injection was blocked by -                        * nested_run_pending.  In that case, however, -                        * vcpu_enter_guest requests an immediate exit, -                        * and the guest shouldn't proceed far enough to -                        * need reinjection.
+                        * On VM-Entry, an exception can be pending if and only +                        * if event injection was blocked by nested_run_pending. +                        * In that case, however, vcpu_enter_guest() requests an +                        * immediate exit, and the guest shouldn't proceed far +                        * enough to need reinjection.
                         */
-                       WARN_ON_ONCE(vcpu->arch.exception.pending); +                       WARN_ON_ONCE(kvm_is_exception_pending(vcpu)); vcpu->arch.exception.injected = true;
                        if (WARN_ON_ONCE(has_payload)) {
                                /*

arch/x86/kvm/x86.c +10 -7
@@ -732,20 +760,22 @@ static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
  void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
  {
         ++vcpu->stat.pf_guest;
-       vcpu->arch.exception.nested_apf =
-               is_guest_mode(vcpu) && fault->async_page_fault;
-       if (vcpu->arch.exception.nested_apf) {
-               vcpu->arch.apf.nested_apf_token = fault->address;
-               kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
-       } else {
+
+       /*
+        * Async #PF in L2 is always forwarded to L1 as a VM-Exit regardless of
+        * whether or not L1 wants to intercept "regular" #PF.
+        */
+       if (is_guest_mode(vcpu) && fault->async_page_fault)
+               kvm_queue_exception_vmexit(vcpu, PF_VECTOR,
+                                          true, fault->error_code,
+                                          true, fault->address);
+       else
                 kvm_queue_exception_e_p(vcpu, PF_VECTOR, fault->error_code,
                                         fault->address);
-       }
  }
  EXPORT_SYMBOL_GPL(kvm_inject_page_fault);

arch/x86/kvm/x86.c +1 -2
-/* Returns true if the page fault was immediately morphed into a VM-Exit. */
-bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
+void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,

                                    struct x86_exception *fault) {
        struct kvm_mmu *fault_mmu;

arch/x86/kvm/x86.c +0 -0
@@ -763,26 +793,7 @@ bool kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
                 kvm_mmu_invalidate_gva(vcpu, fault_mmu, fault->address,
                                        fault_mmu->root.hpa);


-       /*
-        * A workaround for KVM's bad exception handling.  If KVM injected an -        * exception into L2, and L2 encountered a #PF while vectoring the -        * injected exception, manually check to see if L1 wants to intercept -        * #PF, otherwise queuing the #PF will lead to #DF or a lost exception. -        * In all other cases, defer the check to nested_ops->check_events(), -        * which will correctly handle priority (this does not).  Note, other -        * exceptions, e.g. #GP, are theoretically affected, #PF is simply the -        * most problematic, e.g. when L0 and L1 are both intercepting #PF for -        * shadow paging.
-        *
-        * TODO: Rewrite exception handling to track injected and pending -        *       (VM-Exit) exceptions separately.
-        */
-       if (unlikely(vcpu->arch.exception.injected && is_guest_mode(vcpu)) && -           kvm_x86_ops.nested_ops->handle_page_fault_workaround(vcpu, fault)) -               return true;
-
        fault_mmu->inject_page_fault(vcpu, fault);
-       return false;
 }
 EXPORT_SYMBOL_GPL(kvm_inject_emulated_page_fault);

arch/x86/kvm/x86.c +0 -0
@@ -4820,7 +4831,7 @@ static int kvm_vcpu_ready_for_interrupt_injection(struct kvm_vcpu *vcpu)

        return (kvm_arch_interrupt_allowed(vcpu) && kvm_cpu_accept_dm_intr(vcpu) && !kvm_event_needs_reinjection(vcpu) && -               !vcpu->arch.exception.pending);
+               !kvm_is_exception_pending(vcpu)); }

 static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,

arch/x86/kvm/x86.c +1 -1
@@ -4995,13 +5006,27 @@ static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
  static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
                                                struct kvm_vcpu_events *events)
  {
-       struct kvm_queued_exception *ex = &vcpu->arch.exception;
+       struct kvm_queued_exception *ex;


        process_nmi(vcpu);

        if (kvm_check_request(KVM_REQ_SMI, vcpu)) process_smi(vcpu);

+       /*
+        * KVM's ABI only allows for one exception to be migrated.  Luckily, +        * the only time there can be two queued exceptions is if there's a +        * non-exiting _injected_ exception, and a pending exiting exception. +        * In that case, ignore the VM-Exiting exception as it's an extension +        * of the injected exception.
+        */
+       if (vcpu->arch.exception_vmexit.pending &&
+           !vcpu->arch.exception.pending &&
+           !vcpu->arch.exception.injected)
+               ex = &vcpu->arch.exception_vmexit;
+       else
+               ex = &vcpu->arch.exception;
+
        /*
         * In guest mode, payload delivery should be deferred if the exception
         * will be intercepted by L1, e.g. KVM should not modifying CR2 if L1

arch/x86/kvm/x86.c +0 -0
@@ -5108,6 +5133,19 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
                 return -EINVAL;


        process_nmi(vcpu);

arch/x86/kvm/x86.c +13 -0
+
+       /*
+        * Flag that userspace is stuffing an exception, the next KVM_RUN will
+        * morph the exception to a VM-Exit if appropriate.  Do this only for
+        * pending exceptions, already-injected exceptions are not subject to
+        * intercpetion.  Note, userspace that conflates pending and injected
+        * is hosed, and will incorrectly convert an injected exception into a
+        * pending exception, which in turn may cause a spurious VM-Exit.
+        */
+       vcpu->arch.exception_from_userspace = events->exception.pending;
+
+       vcpu->arch.exception_vmexit.pending = false;
+

        vcpu->arch.exception.injected = events->exception.injected; vcpu->arch.exception.pending = events->exception.pending; vcpu->arch.exception.vector = events->exception.nr;

arch/x86/kvm/x86.c +0 -0
@@ -8130,18 +8168,17 @@ static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
         }
  }

arch/x86/kvm/x86.c +1 -1
-static bool inject_emulated_exception(struct kvm_vcpu *vcpu)
+static void inject_emulated_exception(struct kvm_vcpu *vcpu)

 {
        struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt; +
        if (ctxt->exception.vector == PF_VECTOR)
-               return kvm_inject_emulated_page_fault(vcpu, &ctxt->exception); -
-       if (ctxt->exception.error_code_valid)
+               kvm_inject_emulated_page_fault(vcpu, &ctxt->exception); +       else if (ctxt->exception.error_code_valid) kvm_queue_exception_e(vcpu, ctxt->exception.vector, ctxt->exception.error_code); else
                kvm_queue_exception(vcpu, ctxt->exception.vector); -       return false;
 }

 static struct x86_emulate_ctxt *alloc_emulate_ctxt(struct kvm_vcpu *vcpu)

arch/x86/kvm/x86.c +0 -0
@@ -8754,8 +8791,7 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,


        if (ctxt->have_exception) {
                r = 1;
-               if (inject_emulated_exception(vcpu))
-                       return r;
+               inject_emulated_exception(vcpu);
        } else if (vcpu->arch.pio.count) {
                if (!vcpu->arch.pio.in) {
                        /* FIXME: return into emulator if single-stepping.  */

arch/x86/kvm/x86.c +1 -1
@@ -9695,7 +9731,7 @@ static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
          */
         if (vcpu->arch.exception.injected)
                 kvm_inject_exception(vcpu);
-       else if (vcpu->arch.exception.pending)
+       else if (kvm_is_exception_pending(vcpu))

                ; /* see above */
        else if (vcpu->arch.nmi_injected) static_call(kvm_x86_inject_nmi)(vcpu);

arch/x86/kvm/x86.c +0 -0
@@ -9722,6 +9758,14 @@ static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
         if (r < 0)
                 goto out;


+       /*
+        * A pending exception VM-Exit should either result in nested VM-Exit +        * or force an immediate re-entry and exit to/from L2, and exception +        * VM-Exits cannot be injected (flag should _never_ be set). +        */
+       WARN_ON_ONCE(vcpu->arch.exception_vmexit.injected ||
+                    vcpu->arch.exception_vmexit.pending);
+
        /*
         * New events, other than exceptions, cannot be injected if KVM needs
         * to re-inject a previous event.  See above comments on re-injecting

arch/x86/kvm/x86.c +0 -0
@@ -9821,7 +9865,7 @@ static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
             kvm_x86_ops.nested_ops->hv_timer_pending(vcpu))
                 *req_immediate_exit = true;


-       WARN_ON(vcpu->arch.exception.pending);
+       WARN_ON(kvm_is_exception_pending(vcpu));
        return 0;

 out:

arch/x86/kvm/x86.c +0 -0
@@ -10839,6 +10883,7 @@ static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)


 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 {
+       struct kvm_queued_exception *ex = &vcpu->arch.exception; struct kvm_run *kvm_run = vcpu->run;
        int r;

arch/x86/kvm/x86.c +0 -0
@@ -10897,6 +10942,21 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
                 }
         }


+       /*
+        * If userspace set a pending exception and L2 is active, convert it to +        * a pending VM-Exit if L1 wants to intercept the exception. +        */
+       if (vcpu->arch.exception_from_userspace && is_guest_mode(vcpu) && +           kvm_x86_ops.nested_ops->is_exception_vmexit(vcpu, ex->vector, +                                                       ex->error_code)) { +               kvm_queue_exception_vmexit(vcpu, ex->vector,
+                                          ex->has_error_code, ex->error_code, +                                          ex->has_payload, ex->payload); +               ex->injected = false;
+               ex->pending = false;
+       }
+       vcpu->arch.exception_from_userspace = false;
+
        if (unlikely(vcpu->arch.complete_userspace_io)) {
                int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io; vcpu->arch.complete_userspace_io = NULL;

arch/x86/kvm/x86.c +0 -0
@@ -11003,6 +11063,7 @@ static void __set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
         kvm_set_rflags(vcpu, regs->rflags | X86_EFLAGS_FIXED);


        vcpu->arch.exception.pending = false; +       vcpu->arch.exception_vmexit.pending = false;
        kvm_make_request(KVM_REQ_EVENT, vcpu); }

arch/x86/kvm/x86.c +0 -0
@@ -11370,7 +11431,7 @@ int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,


        if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) { r = -EBUSY;
-               if (vcpu->arch.exception.pending)
+               if (kvm_is_exception_pending(vcpu))
                        goto out;
                if (dbg->control & KVM_GUESTDBG_INJECT_DB) kvm_queue_exception(vcpu, DB_VECTOR);

arch/x86/kvm/x86.c +0 -0
@@ -12554,7 +12615,7 @@ static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
         if (vcpu->arch.pv.pv_unhalted)
                 return true;


-       if (vcpu->arch.exception.pending) +       if (kvm_is_exception_pending(vcpu)) return true;

        if (kvm_test_request(KVM_REQ_NMI, vcpu) ||

arch/x86/kvm/x86.c +0 -0
@@ -12809,7 +12870,7 @@ bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
  {

        if (unlikely(!lapic_in_kernel(vcpu) || kvm_event_needs_reinjection(vcpu) ||
-                    vcpu->arch.exception.pending))
+                    kvm_is_exception_pending(vcpu)))
                return false;

        if (kvm_hlt_in_guest(vcpu->kvm) && !kvm_can_deliver_async_pf(vcpu))

arch/x86/kvm/x86.h +0 -0
index dc2af0146220..eee259e387d3 100644
@@ -82,10 +82,17 @@ static inline unsigned int __shrink_ple_window(unsigned int val,
  void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu);
  int kvm_check_nested_events(struct kvm_vcpu *vcpu);

arch/x86/kvm/x86.h +6 -0
+static inline bool kvm_is_exception_pending(struct kvm_vcpu *vcpu)
+{
+       return vcpu->arch.exception.pending ||
+              vcpu->arch.exception_vmexit.pending;
+}
+
Quoted 8 lines

 static inline void kvm_clear_exception_queue(struct kvm_vcpu *vcpu) {
        vcpu->arch.exception.pending = false; vcpu->arch.exception.injected = false;
+       vcpu->arch.exception_vmexit.pending = false;
 }

 static inline void kvm_queue_interrupt(struct kvm_vcpu *vcpu, u8 vector,

The patch is large, I could have missed something though.

Best regards,
Maxim Levitsky

author maintainer
#26 lore raw

PATCH v2 20/24 KVM: x86: Treat pending TRIPLE_FAULT requests as pending exceptions

In reply to Sean Christopherson

Treat pending TRIPLE_FAULTS as pending exceptions. A triple fault is an exception for all intents and purposes, it's just not tracked as such because there's no vector associated the exception. E.g. if userspace were to set vcpu->request_interrupt_window while running L2 and L2 hit a triple fault, a triple fault nested VM-Exit should be synthesized to L1 before exiting to userspace with KVM_EXIT_IRQ_WINDOW_OPEN.

---
 arch/x86/kvm/x86.c | 3 ---
 arch/x86/kvm/x86.h | 3 ++-
 2 files changed, 2 insertions(+), 4 deletions(-)
arch/x86/kvm/x86.c +0 -3
index 9be2fdf834ad..b924afb76b72 100644
@@ -12644,9 +12644,6 @@ static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
 	if (kvm_xen_has_pending_events(vcpu))
 		return true;
 
-	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu))
-		return true;
-
 	return false;
 }
 
arch/x86/kvm/x86.h +2 -1
index eee259e387d3..078765287ec6 100644
@@ -85,7 +85,8 @@ int kvm_check_nested_events(struct kvm_vcpu *vcpu);
 static inline bool kvm_is_exception_pending(struct kvm_vcpu *vcpu)
 {
 	return vcpu->arch.exception.pending ||
-	       vcpu->arch.exception_vmexit.pending;
+	       vcpu->arch.exception_vmexit.pending ||
+	       kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
 }
 
 static inline void kvm_clear_exception_queue(struct kvm_vcpu *vcpu)
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#27 lore raw

PATCH v2 21/24 KVM: VMX: Update MTF and ICEBP comments to document KVM's subtle behavior

In reply to Sean Christopherson

Document the oddities of ICEBP interception (trap-like #DB is intercepted as a fault-like exception), and how using VMX's inner "skip" helper deliberately bypasses the pending MTF and single-step #DB logic.

No functional change intended.

---
 arch/x86/kvm/vmx/vmx.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/vmx.c +11 -5
index 5302b046110f..de6fcfa0ef02 100644
@@ -1578,9 +1578,13 @@ static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
 
 	/*
 	 * Per the SDM, MTF takes priority over debug-trap exceptions besides
-	 * T-bit traps. As instruction emulation is completed (i.e. at the
-	 * instruction boundary), any #DB exception pending delivery must be a
-	 * debug-trap. Record the pending MTF state to be delivered in
+	 * TSS T-bit traps and ICEBP (INT1).  KVM doesn't emulate T-bit traps
+	 * or ICEBP (in the emulator proper), and skipping of ICEBP after an
+	 * intercepted #DB deliberately avoids single-step #DB and MTF updates
+	 * as ICEBP is higher priority than both.  As instruction emulation is
+	 * completed at this point (i.e. KVM is at the instruction boundary),
+	 * any #DB exception pending delivery must be a debug-trap of lower
+	 * priority than MTF.  Record the pending MTF state to be delivered in
 	 * vmx_check_nested_events().
 	 */
 	if (nested_cpu_has_mtf(vmcs12) &&
@@ -5084,8 +5088,10 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
 			 * instruction.  ICEBP generates a trap-like #DB, but
 			 * despite its interception control being tied to #DB,
 			 * is an instruction intercept, i.e. the VM-Exit occurs
-			 * on the ICEBP itself.  Note, skipping ICEBP also
-			 * clears STI and MOVSS blocking.
+			 * on the ICEBP itself.  Use the inner "skip" helper to
+			 * avoid single-step #DB and MTF updates, as ICEBP is
+			 * higher priority.  Note, skipping ICEBP still clears
+			 * STI and MOVSS blocking.
 			 *
 			 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
 			 * if single-step is enabled in RFLAGS and STI or MOVSS
Signature · 1 line
2.37.0.170.g444d1eabd0-goog
Reviewed-by on v2 21/24
#28 lore raw

Re: [PATCH v2 21/24] KVM: VMX: Update MTF and ICEBP comments to document KVM's subtle behavior

Quoted 35 lines · Sean Christopherson

Document the oddities of ICEBP interception (trap-like #DB is intercepted as a fault-like exception), and how using VMX's inner "skip" helper deliberately bypasses the pending MTF and single-step #DB logic.

No functional change intended.

---
 arch/x86/kvm/vmx/vmx.c | 16 +++++++++++-----

 1 file changed, 11 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/vmx.c +0 -0
index 5302b046110f..de6fcfa0ef02 100644
@@ -1578,9 +1578,13 @@ static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)


        /*
         * Per the SDM, MTF takes priority over debug-trap exceptions besides -        * T-bit traps. As instruction emulation is completed (i.e. at the -        * instruction boundary), any #DB exception pending delivery must be a -        * debug-trap. Record the pending MTF state to be delivered in +        * TSS T-bit traps and ICEBP (INT1).  KVM doesn't emulate T-bit traps +        * or ICEBP (in the emulator proper), and skipping of ICEBP after an +        * intercepted #DB deliberately avoids single-step #DB and MTF updates +        * as ICEBP is higher priority than both.  As instruction emulation is +        * completed at this point (i.e. KVM is at the instruction boundary), +        * any #DB exception pending delivery must be a debug-trap of lower +        * priority than MTF.  Record the pending MTF state to be delivered in
         * vmx_check_nested_events().
         */
        if (nested_cpu_has_mtf(vmcs12) &&

arch/x86/kvm/vmx/vmx.c +0 -0
@@ -5084,8 +5088,10 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
                          * instruction.  ICEBP generates a trap-like #DB, but
                          * despite its interception control being tied to #DB,

arch/x86/kvm/vmx/vmx.c static int handle_exception_nmi(struct kvm_vcpu *vcpu) · line 5097

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +4 -2
                          * is an instruction intercept, i.e. the VM-Exit occurs
-                        * on the ICEBP itself.  Note, skipping ICEBP also
-                        * clears STI and MOVSS blocking.
+                        * on the ICEBP itself.  Use the inner "skip" helper to
+                        * avoid single-step #DB and MTF updates, as ICEBP is
+                        * higher priority.  Note, skipping ICEBP still clears
+                        * STI and MOVSS blocking.
                          *
                          * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS
                          * if single-step is enabled in RFLAGS and STI or MOVSS

Best regards,
Maxim Levitsky

author maintainer
#29 lore raw

PATCH v2 22/24 KVM: x86: Rename inject_pending_events() to kvm_check_and_inject_events()

In reply to Sean Christopherson

Rename inject_pending_events() to kvm_check_and_inject_events() in order to capture the fact that it handles more than just pending events, and to (mostly) align with kvm_check_nested_events(), which omits the "inject" for brevity.

Add a comment above kvm_check_and_inject_events() to provide a high-level synopsis, and to document a virtualization hole (KVM erratum if you will) that exists due to KVM not strictly tracking instruction boundaries with respect to coincident instruction restarts and asynchronous events.

No functional change inteded.

---
 arch/x86/kvm/svm/nested.c |  2 +-
 arch/x86/kvm/svm/svm.c    |  2 +-
 arch/x86/kvm/x86.c        | 46 ++++++++++++++++++++++++++++++++++++---
 3 files changed, 45 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/nested.c +1 -1
index 0a8ee5f28319..028e180a74b6 100644
@@ -1310,7 +1310,7 @@ static void nested_svm_inject_exception_vmexit(struct kvm_vcpu *vcpu)
 		else
 			vmcb->control.exit_info_2 = vcpu->arch.cr2;
 	} else if (ex->vector == DB_VECTOR) {
-		/* See inject_pending_event.  */
+		/* See kvm_check_and_inject_events().  */
 		kvm_deliver_exception_payload(vcpu, ex);
 
 		if (vcpu->arch.dr7 & DR7_GD) {
arch/x86/kvm/svm/svm.c +1 -1
index a336517b563e..95bdf127d531 100644
@@ -3518,7 +3518,7 @@ void svm_complete_interrupt_delivery(struct kvm_vcpu *vcpu, int delivery_mode,
 
 	/* Note, this is called iff the local APIC is in-kernel. */
 	if (!READ_ONCE(vcpu->arch.apic->apicv_active)) {
-		/* Process the interrupt via inject_pending_event */
+		/* Process the interrupt via kvm_check_and_inject_events(). */
 		kvm_make_request(KVM_REQ_EVENT, vcpu);
 		kvm_vcpu_kick(vcpu);
 		return;
arch/x86/kvm/x86.c +43 -3

64 lines not on this page · raw message

Signature · 1 line
2.37.0.170.g444d1eabd0-goog
Reviewed-by on v2 22/24
#30 lore raw

Re: [PATCH v2 22/24] KVM: x86: Rename inject_pending_events() to kvm_check_and_inject_events()

Quoted 110 lines · Sean Christopherson

Rename inject_pending_events() to kvm_check_and_inject_events() in order to capture the fact that it handles more than just pending events, and to (mostly) align with kvm_check_nested_events(), which omits the "inject" for brevity.

Add a comment above kvm_check_and_inject_events() to provide a high-level synopsis, and to document a virtualization hole (KVM erratum if you will) that exists due to KVM not strictly tracking instruction boundaries with respect to coincident instruction restarts and asynchronous events.

No functional change inteded.

---
 arch/x86/kvm/svm/nested.c |  2 +-
 arch/x86/kvm/svm/svm.c    |  2 +-
 arch/x86/kvm/x86.c        | 46 ++++++++++++++++++++++++++++++++++++---

 3 files changed, 45 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/nested.c +0 -0
index 0a8ee5f28319..028e180a74b6 100644
@@ -1310,7 +1310,7 @@ static void nested_svm_inject_exception_vmexit(struct kvm_vcpu *vcpu)

                else
                        vmcb->control.exit_info_2 = vcpu->arch.cr2; } else if (ex->vector == DB_VECTOR) {
-               /* See inject_pending_event.  */
+               /* See kvm_check_and_inject_events().  */ kvm_deliver_exception_payload(vcpu, ex);
                if (vcpu->arch.dr7 & DR7_GD) {

arch/x86/kvm/svm/svm.c +0 -0
index a336517b563e..95bdf127d531 100644
@@ -3518,7 +3518,7 @@ void svm_complete_interrupt_delivery(struct kvm_vcpu *vcpu, int delivery_mode,


        /* Note, this is called iff the local APIC is in-kernel. */ if (!READ_ONCE(vcpu->arch.apic->apicv_active)) {
-               /* Process the interrupt via inject_pending_event */ +               /* Process the interrupt via kvm_check_and_inject_events(). */ kvm_make_request(KVM_REQ_EVENT, vcpu); kvm_vcpu_kick(vcpu);
                return;

arch/x86/kvm/x86.c +0 -0
index b924afb76b72..69b9725beff3 100644
@@ -9691,7 +9691,47 @@ static void kvm_inject_exception(struct kvm_vcpu *vcpu)
         static_call(kvm_x86_inject_exception)(vcpu);
  }

arch/x86/kvm/x86.c +41 -1
-static int inject_pending_event(struct kvm_vcpu *vcpu, bool *req_immediate_exit)
+/*
+ * Check for any event (interrupt or exception) that is ready to be injected,
+ * and if there is at least one event, inject the event with the highest
+ * priority.  This handles both "pending" events, i.e. events that have never
+ * been injected into the guest, and "injected" events, i.e. events that were
+ * injected as part of a previous VM-Enter, but weren't successfully delivered
+ * and need to be re-injected.
+ *
+ * Note, this is not guaranteed to be invoked on a guest instruction boundary,
+ * i.e. doesn't guarantee that there's an event window in the guest.  KVM must
+ * be able to inject exceptions in the "middle" of an instruction, and so must
+ * also be able to re-inject NMIs and IRQs in the middle of an instruction.
+ * I.e. for exceptions and re-injected events, NOT invoking this on instruction
+ * boundaries is necessary and correct.
+ *
+ * For simplicity, KVM uses a single path to inject all events (except events
+ * that are injected directly from L1 to L2) and doesn't explicitly track
+ * instruction boundaries for asynchronous events.  However, because VM-Exits
+ * that can occur during instruction execution typically result in KVM skipping
+ * the instruction or injecting an exception, e.g. instruction and exception
+ * intercepts, and because pending exceptions have higher priority than pending
+ * interrupts, KVM still honors instruction boundaries in most scenarios.
+ *
+ * But, if a VM-Exit occurs during instruction execution, and KVM does NOT skip
+ * the instruction or inject an exception, then KVM can incorrecty inject a new
+ * asynchrounous event if the event became pending after the CPU fetched the
+ * instruction (in the guest).  E.g. if a page fault (#PF, #NPF, EPT violation)
+ * occurs and is resolved by KVM, a coincident NMI, SMI, IRQ, etc... can be
+ * injected on the restarted instruction instead of being deferred until the
+ * instruction completes.
+ *
+ * In practice, this virtualization hole is unlikely to be observed by the
+ * guest, and even less likely to cause functional problems.  To detect the
+ * hole, the guest would have to trigger an event on a side effect of an early
+ * phase of instruction execution, e.g. on the instruction fetch from memory.
+ * And for it to be a functional problem, the guest would need to depend on the
+ * ordering between that side effect, the instruction completing, _and_ the
+ * delivery of the asynchronous event.
+ */
+static int kvm_check_and_inject_events(struct kvm_vcpu *vcpu,
+                                      bool *req_immediate_exit)

 {
        bool can_inject;
        int r;

arch/x86/kvm/x86.c +1 -1
@@ -10170,7 +10210,7 @@ void kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu)
          * When APICv gets disabled, we may still have injected interrupts
          * pending. At the same time, KVM_REQ_EVENT may not be set as APICv was
          * still active when the interrupt got accepted. Make sure
-        * inject_pending_event() is called to check for that.
+        * kvm_check_and_inject_events() is called to check for that.
          */
         if (!apic->apicv_active)
                 kvm_make_request(KVM_REQ_EVENT, vcpu);
@@ -10467,7 +10507,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
                         goto out;
                 }
Quoted 6 lines


-               r = inject_pending_event(vcpu, &req_immediate_exit); +               r = kvm_check_and_inject_events(vcpu, &req_immediate_exit); if (r < 0) {
                        r = 0;
                        goto out;

Makes sense.

Best regards,
Maxim Levitsky

author maintainer
#31 lore raw

PATCH v2 23/24 KVM: selftests: Use uapi header to get VMX and SVM exit reasons/codes

In reply to Sean Christopherson

Include the vmx.h and svm.h uapi headers that KVM so kindly provides instead of manually defining all the same exit reasons/code.

---
 .../selftests/kvm/include/x86_64/svm_util.h   |  7 +--
 .../selftests/kvm/include/x86_64/vmx.h        | 51 +------------------
 2 files changed, 4 insertions(+), 54 deletions(-)
tools/testing/selftests/kvm/include/x86_64/svm_util.h +2 -5
index a339b537a575..7aee6244ab6a 100644
@@ -9,15 +9,12 @@
 #ifndef SELFTEST_KVM_SVM_UTILS_H
 #define SELFTEST_KVM_SVM_UTILS_H
 
+#include <asm/svm.h>
+
 #include <stdint.h>
 #include "svm.h"
 #include "processor.h"
 
-#define SVM_EXIT_EXCP_BASE	0x040
-#define SVM_EXIT_HLT		0x078
-#define SVM_EXIT_MSR		0x07c
-#define SVM_EXIT_VMMCALL	0x081
-
 struct svm_test_data {
 	/* VMCB */
 	struct vmcb *vmcb; /* gva */
tools/testing/selftests/kvm/include/x86_64/vmx.h +2 -49

63 lines not on this page · raw message

Signature · 1 line
2.37.0.170.g444d1eabd0-goog
author maintainer
#32 lore raw

PATCH v2 24/24 KVM: selftests: Add an x86-only test to verify nested exception queueing

In reply to Sean Christopherson

Add a test to verify that KVM_{G,S}ET_EVENTS play nice with pending vs. injected exceptions when an exception is being queued for L2, and that KVM correctly handles L1's exception intercept wants.

---
 tools/testing/selftests/kvm/.gitignore        |   1 +
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../kvm/x86_64/nested_exceptions_test.c       | 295 ++++++++++++++++++
 3 files changed, 297 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86_64/nested_exceptions_test.c
tools/testing/selftests/kvm/.gitignore +1 -0
index 91429330faea..6c0c37fe81b6 100644
@@ -28,6 +28,7 @@
 /x86_64/max_vcpuid_cap_test
 /x86_64/mmio_warning_test
 /x86_64/monitor_mwait_test
+/x86_64/nested_exceptions_test
 /x86_64/nx_huge_pages_test
 /x86_64/platform_info_test
 /x86_64/pmu_event_filter_test
tools/testing/selftests/kvm/Makefile +1 -0
index 6b22fb1ce2b9..c6a67c389ac7 100644
@@ -88,6 +88,7 @@ TEST_GEN_PROGS_x86_64 += x86_64/kvm_clock_test
 TEST_GEN_PROGS_x86_64 += x86_64/kvm_pv_test
 TEST_GEN_PROGS_x86_64 += x86_64/mmio_warning_test
 TEST_GEN_PROGS_x86_64 += x86_64/monitor_mwait_test
+TEST_GEN_PROGS_x86_64 += x86_64/nested_exceptions_test
 TEST_GEN_PROGS_x86_64 += x86_64/platform_info_test
 TEST_GEN_PROGS_x86_64 += x86_64/pmu_event_filter_test
 TEST_GEN_PROGS_x86_64 += x86_64/set_boot_cpu_id
tools/testing/selftests/kvm/x86_64/nested_exceptions_test.c new file +295 -0

295 lines not on this page · raw message

Signature · 1 line
2.37.0.170.g444d1eabd0-goog