[RFC PATCH v4 6/7] KVM: x86: Add a new guest_debug flag forcing exit to userspace

From: Kechen Lu
Date: Tue Jun 21 2022 - 20:55:20 EST


For debug and test purposes, there are needs to explicitly make
instruction triggered exits could be trapped to userspace. Simply
add a new flag for guest_debug interface could achieve this.

This patch also fills the userspace accessible field
vcpu->run->hw.hardware_exit_reason for userspace to determine the
original triggered VM-exits.

Signed-off-by: Kechen Lu <kechenl@xxxxxxxxxx>
---
arch/x86/kvm/svm/svm.c | 2 ++
arch/x86/kvm/vmx/vmx.c | 1 +
arch/x86/kvm/x86.c | 2 ++
include/uapi/linux/kvm.h | 1 +
tools/include/uapi/linux/kvm.h | 1 +
5 files changed, 7 insertions(+)

diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index 7b3d64b3b901..e7ced6c3fbea 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -3259,6 +3259,8 @@ int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
if (!svm_check_exit_valid(exit_code))
return svm_handle_invalid_exit(vcpu, exit_code);

+ vcpu->run->hw.hardware_exit_reason = exit_code;
+
#ifdef CONFIG_RETPOLINE
if (exit_code == SVM_EXIT_MSR)
return msr_interception(vcpu);
diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c
index 2d000638cc9b..c32c20c4aa4d 100644
--- a/arch/x86/kvm/vmx/vmx.c
+++ b/arch/x86/kvm/vmx/vmx.c
@@ -6151,6 +6151,7 @@ static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)

if (exit_reason.basic >= kvm_vmx_max_exit_handlers)
goto unexpected_vmexit;
+ vcpu->run->hw.hardware_exit_reason = exit_reason.basic;
#ifdef CONFIG_RETPOLINE
if (exit_reason.basic == EXIT_REASON_MSR_WRITE)
return kvm_emulate_wrmsr(vcpu);
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 6165f0b046ed..91384a56ae0a 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -8349,6 +8349,8 @@ int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
*/
if (unlikely(rflags & X86_EFLAGS_TF))
r = kvm_vcpu_do_singlestep(vcpu);
+ r &= !(vcpu->guest_debug & KVM_GUESTDBG_EXIT_USERSPACE);
+
return r;
}
EXPORT_SYMBOL_GPL(kvm_skip_emulated_instruction);
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index f2e76e436be5..23c335a6a285 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -777,6 +777,7 @@ struct kvm_s390_irq_state {

#define KVM_GUESTDBG_ENABLE 0x00000001
#define KVM_GUESTDBG_SINGLESTEP 0x00000002
+#define KVM_GUESTDBG_EXIT_USERSPACE 0x00000004

struct kvm_guest_debug {
__u32 control;
diff --git a/tools/include/uapi/linux/kvm.h b/tools/include/uapi/linux/kvm.h
index 6a184d260c7f..373b4a2b7fe9 100644
--- a/tools/include/uapi/linux/kvm.h
+++ b/tools/include/uapi/linux/kvm.h
@@ -773,6 +773,7 @@ struct kvm_s390_irq_state {

#define KVM_GUESTDBG_ENABLE 0x00000001
#define KVM_GUESTDBG_SINGLESTEP 0x00000002
+#define KVM_GUESTDBG_EXIT_USERSPACE 0x00000004

struct kvm_guest_debug {
__u32 control;
--
2.32.0