Skip to contentSkip to conversation

KVM: selftests: Stress save+restore and #PF (ft. nested)

PATCH Superseded Yosry Ahmed 3 participants 24 messages Jul 27 – Jul 28

Subsystems (3)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v4 cover KVM: selftests: Stress save+restore and #PF (ft. nested)

Add a stress test for save+restore while the guest is triggering and handling #PFs, in both L1 and L2. The goal was to create a generic selftest that would catch bugs like the one fixed by commit 5c247d08bc81 ("KVM: nSVM: Use vcpu->arch.cr2 when updating vmcb12 on nested #VMEXIT"), instead of relying on high-level testing (e.g. building GCC in L2) to catch it.

The test tries to be as generic as possible by triggering #PFs in a guest and installing a proper #PF handler, while the host is continuously doing save+restore cycles. Exiting to userspace is randomly triggered by a second thread that constantly signals the vCPU thread.

Patches (1-6) are prep patches, fixing GPR and RFLAGS switching for nSVM and generalizing GPR switching to cover nVMX, which is needed for the test to run properly with nVMX. Patch 6 removes HORRIFIC_L2_UCALL_CLOBBER_HACK, as it is no longer needed. While this series does not have the "complete" fix added by commit 6783ca4105a7 ("KVM: selftests: Add a shameful hack to preserve/clobber GPRs across ucall"), it's a good step in the right direction.

Patches (7-8) add minor infrastructure improvements (assertion failure formatting and exposing MMU masks to the guest).

Patches (9-12) add the actual test. The test is first introduced as a simple (read: dummy) stress test that just explicitly syncs to userspace after each #PF handling to do save+restore, then gradually evolves to add the random signaling, nested support, and triggering L2->L1 exits. After the last patch, the test reliably reproduces the CR2 bug.

v3 -> v4:
- Switch guest_regs back to a struct and provide struct offsets as ASM constraints similar to kvm-unit-tests [Sean].
- Expose PTE masks to guests as part of a guest MMU [Sean].
- Use __stringify() from <linux/stringify.h> instead of custom STR() and XSTR() macros [Sean].
- Handle guest RFLAGS save/restore as part of guest_regs.
- Run both L0 and L2 tests sequentially by default if nested is supported, instead of requiring a '-n' command line argument [Sean].
- Minor fixups and cleanups [Sean].

v2 -> v3:
- Rebased on top of L2 stack rework in selftests.
- Fix GPR array size (i.e. NR_GUEST_REGS) [Sashiko].
- Handle evmcs_vmlaunch() and evmcs_vmresume() [Sashiko].
- Fix off-by-one assertion error in intermediate patches.
- Increase inter-signal delay from 100us to 1msec.

v1 -> v2:
- Switch guest_regs to an array, which simplifies the offsets calculation and forgoes the dependency on using OFFSET() or defining the struct offsets for assembly otherwise.
- Move page table mapping to the test (instead of a generic helper), as the helper mistakenly tried to map the entire memslot, not just page tables.
- Do not use identity mappings for page tables as it collisions with GVAs used for ELF in some cases.
- Simplify page table walking by using loops.
- Make sure the signals are ignored before creating the signaling thread [Sashiko]
- Assert that the guest actually ran and had page faults [Sashiko]
- Add a patch to fix RAX and RFLAGS offsets in run_guest() [Sashiko]
- Initialize exception_has_payload when injecting a #UD [Sashiko]
- Only check KVM_STATE_NESTED_GUEST_MODE when running in nested mode [Sashiko]

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

Yosry Ahmed (12):
KVM: selftests: Use __stringify() instead of custom XSTR() macros
KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2
KVM: selftests: Rework GPR registers switching for SVM (and fix
offsets)
KVM: selftests: Handle rflags save/restore for SVM in guest_regs
KVM: selftests: Reuse GPR switching logic for nVMX
KVM: selftests: Drop HORRIFIC_L2_UCALL_CLOBBER_HACK
KVM: selftests: Add a blank line before logging assertion failures
KVM: selftests: Expose PTE masks to guests as part of an MMU
KVM: selftests: Add basic stress test for save+restore and #PF
handling
KVM: selftests: Trigger save+restore randomly in the #PF stress test
KVM: selftests: Support running stress save+restore and #PF test in L2
KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test

 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../testing/selftests/kvm/include/test_util.h |   1 +
 .../testing/selftests/kvm/include/x86/evmcs.h |  46 +--
 .../selftests/kvm/include/x86/processor.h     |  53 +++-
 tools/testing/selftests/kvm/include/x86/vmx.h |  69 ++---
 tools/testing/selftests/kvm/lib/assert.c      |   2 +-
 .../testing/selftests/kvm/lib/x86/processor.c |  14 +
 tools/testing/selftests/kvm/lib/x86/svm.c     |  62 ++--
 tools/testing/selftests/kvm/lib/x86/ucall.c   |  32 +-
 .../kvm/x86/evmcs_smm_controls_test.c         |   5 +-
 .../selftests/kvm/x86/fix_hypercall_test.c    |   1 -
 .../kvm/x86/save_restore_pf_stress_test.c     | 291 ++++++++++++++++++
 tools/testing/selftests/kvm/x86/smm_test.c    |   5 +-
 13 files changed, 442 insertions(+), 140 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c

base-commit: 271255273d5ff348fe29d89fe4712b2f7f7907c3

Signature · 1 line
2.55.0.229.g6434b31f56-goog
#1 lore raw

PATCH v4 1/12 KVM: selftests: Use __stringify() instead of custom XSTR() macros

Drop the custom defined XSTR() macros in KVM selftests and use __stringify() instead. Include stringify.h in test_util.h to make it available for all tests instead of including it in all the tests that need it, as more tests will start using it.

No functional change intended.

---
 tools/testing/selftests/kvm/include/test_util.h           | 1 +
 tools/testing/selftests/kvm/x86/evmcs_smm_controls_test.c | 5 +----
 tools/testing/selftests/kvm/x86/fix_hypercall_test.c      | 1 -
 tools/testing/selftests/kvm/x86/smm_test.c                | 5 +----
 4 files changed, 3 insertions(+), 9 deletions(-)
tools/testing/selftests/kvm/include/test_util.h +1 -0
index d64c8a228207a..e8356ee54d7b9 100644
@@ -23,6 +23,7 @@
 
 #include <linux/mman.h>
 #include <linux/types.h>
+#include <linux/stringify.h>
 
 #define msecs_to_usecs(msec)    ((msec) * 1000ULL)
 
tools/testing/selftests/kvm/x86/evmcs_smm_controls_test.c +1 -4
index 77ce87c41a868..aa7f3b405fd32 100644
@@ -22,9 +22,6 @@
 
 #define SYNC_PORT	0xe
 
-#define STR(x) #x
-#define XSTR(s) STR(s)
-
 /*
  * SMI handler: runs in real-address mode.
  * Reports SMRAM_STAGE via port IO, then does RSM.
@@ -37,7 +34,7 @@ static u8 smi_handler[] = {
 
 static inline void sync_with_host(u64 phase)
 {
-	asm volatile("in $" XSTR(SYNC_PORT) ", %%al \n"
+	asm volatile("in $" __stringify(SYNC_PORT) ", %%al \n"
 		     : "+a" (phase));
 }
 
tools/testing/selftests/kvm/x86/fix_hypercall_test.c +0 -1
index 753a0e730ea8d..4931ec22768ee 100644
@@ -6,7 +6,6 @@
  */
 #include <asm/kvm_para.h>
 #include <linux/kvm_para.h>
-#include <linux/stringify.h>
 #include <stdint.h>
 
 #include "kvm_test_harness.h"
tools/testing/selftests/kvm/x86/smm_test.c +1 -4
index e2542f4ced605..d1edafd5af755 100644
@@ -22,9 +22,6 @@
 #define SMRAM_GPA 0x1000000
 #define SMRAM_STAGE 0xfe
 
-#define STR(x) #x
-#define XSTR(s) STR(s)
-
 #define SYNC_PORT 0xe
 #define DONE 0xff
 
@@ -42,7 +39,7 @@ u8 smi_handler[] = {
 
 static inline void sync_with_host(u64 phase)
 {
-	asm volatile("in $" XSTR(SYNC_PORT)", %%al \n"
+	asm volatile("in $" __stringify(SYNC_PORT)", %%al \n"
 		     : "+a" (phase));
 }
 
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#2 lore raw

PATCH v4 2/12 KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2

In reply to Yosry Ahmed

The offsets used (0x170 and 0x1f8) are offsets within vmcb_save_area, not vmcb. The correct offsets should include the base of vmcb_save_area within vmcb (which is 0x400 -- so 0x570 and 0x5f8).

Instead of just correcting the offsets, use vmcb->save.rax and vmcb->save.rflags as parameters to the asm block and avoid hardcoding offsets completely. While at it, also use guest_regs.rax directly instead of assuming it's at offset 0 of guest_regs.

Note: "+m" must be used for vmcb_rax and vmcb_rflags, as caching those fields in registers would be wrong as the underlying KVM will update them in memory.

The same problem was recently fixed (differently) for kvm-unit-tests [1].

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

---
 tools/testing/selftests/kvm/lib/x86/svm.c | 19 +++++++++++--------
 1 file changed, 11 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/lib/x86/svm.c +11 -8
index 1445b890986fd..766d15f1d534a 100644
@@ -164,19 +164,22 @@ void run_guest(struct vmcb *vmcb, u64 vmcb_gpa)
 {
 	asm volatile (
 		"vmload %[vmcb_gpa]\n\t"
-		"mov rflags, %%r15\n\t"	// rflags
-		"mov %%r15, 0x170(%[vmcb])\n\t"
-		"mov guest_regs, %%r15\n\t"	// rax
-		"mov %%r15, 0x1f8(%[vmcb])\n\t"
+		"mov rflags, %%r15\n\t"
+		"mov %%r15, %[vmcb_rflags]\n\t"
+		"mov %[guest_regs_rax], %%r15\n\t"
+		"mov %%r15, %[vmcb_rax]\n\t"
 		LOAD_GPR_C
 		"vmrun %[vmcb_gpa]\n\t"
 		SAVE_GPR_C
-		"mov 0x170(%[vmcb]), %%r15\n\t"	// rflags
+		"mov %[vmcb_rflags], %%r15\n\t"
 		"mov %%r15, rflags\n\t"
-		"mov 0x1f8(%[vmcb]), %%r15\n\t"	// rax
-		"mov %%r15, guest_regs\n\t"
+		"mov %[vmcb_rax], %%r15\n\t"	// rax
+		"mov %%r15, %[guest_regs_rax]\n\t"
 		"vmsave %[vmcb_gpa]\n\t"
-		: : [vmcb] "r" (vmcb), [vmcb_gpa] "a" (vmcb_gpa)
+		: [vmcb_rflags] "+m" (vmcb->save.rflags),
+		  [vmcb_rax] "+m" (vmcb->save.rax),
+		  [guest_regs_rax] "+rm" (guest_regs.rax)
+		: [vmcb_gpa] "a" (vmcb_gpa)
 		: "r15", "memory");
 }
 
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#3 lore raw

Re: [PATCH v4 02/12] KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] The hardcoded offsets in LOAD_GPR_C and SAVE_GPR_C are misaligned with struct gpr64_regs by 8 bytes, causing out-of-bounds memory corruption and shifting L1/L2 registers to incorrect offsets. --

--- Patch [2]: [PATCH v4 02/12] KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2 --- commit 828b231275dca6c618d4ec1f5e43abd20a4b5e54
Author: Yosry Ahmed <[email protected]>

KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2

This commit fixes incorrect vmcb_save_area offsets by using vmcb->save.rax and vmcb->save.rflags as parameters to the assembly block. This avoids hardcoding offsets completely and also directly uses guest_regs.rax instead of assuming it is at offset 0.

Quoted 9 lines
tools/testing/selftests/kvm/lib/x86/svm.c +0 -1
index 1445b890986fd..766d15f1d534a 100644
@@ -164,19 +164,22 @@ void run_guest(struct vmcb *vmcb, u64 vmcb_gpa)
 {
 	asm volatile (
 		"vmload %[vmcb_gpa]\n\t"
-		"mov rflags, %%r15\n\t"	// rflags

tools/testing/selftests/kvm/lib/x86/svm.c void run_guest(struct vmcb *vmcb, u64 vmcb_gpa) · line 173

Quoted 10 lines
tools/testing/selftests/kvm/lib/x86/svm.c +4 -3
-		"mov %%r15, 0x170(%[vmcb])\n\t"
-		"mov guest_regs, %%r15\n\t"	// rax
-		"mov %%r15, 0x1f8(%[vmcb])\n\t"
+		"mov rflags, %%r15\n\t"
+		"mov %%r15, %[vmcb_rflags]\n\t"
+		"mov %[guest_regs_rax], %%r15\n\t"
+		"mov %%r15, %[vmcb_rax]\n\t"
 		LOAD_GPR_C
 		"vmrun %[vmcb_gpa]\n\t"
 		SAVE_GPR_C

[Severity: High]
This isn't a bug introduced by this patch, but do the hardcoded memory offsets in LOAD_GPR_C and SAVE_GPR_C cause an out-of-bounds memory access?

These macros use offsets that appear to be misaligned with the layout of struct gpr64_regs by 8 bytes. For instance, SAVE_GPR_C exchanges %r15 with guest_regs+0x80.

Since guest_regs has a total size of exactly 0x80 bytes, doesn't this result in an 8-byte out-of-bounds memory write past the end of the structure that could corrupt adjacent globals?

Quoted 14 lines
tools/testing/selftests/kvm/lib/x86/svm.c +6 -4
-		"mov 0x170(%[vmcb]), %%r15\n\t"	// rflags
 		"mov %%r15, rflags\n\t"
-		"mov 0x1f8(%[vmcb]), %%r15\n\t"	// rax
-		"mov %%r15, guest_regs\n\t"
+		"mov %[vmcb_rax], %%r15\n\t"	// rax
+		"mov %%r15, %[guest_regs_rax]\n\t"
 		"vmsave %[vmcb_gpa]\n\t"
-		: : [vmcb] "r" (vmcb), [vmcb_gpa] "a" (vmcb_gpa)
+		: [vmcb_rflags] "+m" (vmcb->save.rflags),
+		  [vmcb_rax] "+m" (vmcb->save.rax),
+		  [guest_regs_rax] "+rm" (guest_regs.rax)
+		: [vmcb_gpa] "a" (vmcb_gpa)
 		: "r15", "memory");
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#4 lore raw

Re: [PATCH v4 02/12] KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2

Quoted 36 lines · On Mon, Jul 27, 2026 at 5:07 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] The hardcoded offsets in LOAD_GPR_C and SAVE_GPR_C are misaligned with struct gpr64_regs by 8 bytes, causing out-of-bounds memory corruption and shifting L1/L2 registers to incorrect offsets. --

--- Patch [2]: [PATCH v4 02/12] KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2 --- commit 828b231275dca6c618d4ec1f5e43abd20a4b5e54
Author: Yosry Ahmed <[email protected]>

KVM: selftests: Fix RAX and RFLAGS VMCB offsets when running L2

This commit fixes incorrect vmcb_save_area offsets by using vmcb->save.rax and vmcb->save.rflags as parameters to the assembly block. This avoids hardcoding offsets completely and also directly uses guest_regs.rax instead of assuming it is at offset 0.

Quoted 15 lines
tools/testing/selftests/kvm/lib/x86/svm.c +3 -4
index 1445b890986fd..766d15f1d534a 100644
@@ -164,19 +164,22 @@ void run_guest(struct vmcb *vmcb, u64 vmcb_gpa)
 {
      asm volatile (
              "vmload %[vmcb_gpa]\n\t"
-             "mov rflags, %%r15\n\t" // rflags
-             "mov %%r15, 0x170(%[vmcb])\n\t"
-             "mov guest_regs, %%r15\n\t"     // rax
-             "mov %%r15, 0x1f8(%[vmcb])\n\t"
+             "mov rflags, %%r15\n\t"
+             "mov %%r15, %[vmcb_rflags]\n\t"
+             "mov %[guest_regs_rax], %%r15\n\t"
Quoted 8 lines

tools/testing/selftests/kvm/lib/x86/svm.c void run_guest(struct vmcb *vmcb, u64 vmcb_gpa) · line 173

Quoted 4 lines
tools/testing/selftests/kvm/lib/x86/svm.c +1 -0
+             "mov %%r15, %[vmcb_rax]\n\t"
              LOAD_GPR_C
              "vmrun %[vmcb_gpa]\n\t"
              SAVE_GPR_C

[Severity: High]
This isn't a bug introduced by this patch, but do the hardcoded memory offsets in LOAD_GPR_C and SAVE_GPR_C cause an out-of-bounds memory access?

Yes, this is fixed in following patches.

#5 lore raw

PATCH v4 3/12 KVM: selftests: Rework GPR registers switching for SVM (and fix offsets)

In reply to Yosry Ahmed

The assembly code defined by SAVE_GPR_C uses the wrong offsets for some registers in guest_regs. For example, the offset of RCX should be 0x08 not 0x10. Also, the last offset in the struct (R15) is 0x78, not 0x80, so the code actually saves and restore beyond the end of gpr64_regs.

Eliminate hardcoded offsets by dynamically generating offsets using offset_of() and using macros to pass the offsets to assembly as asm constraints.

To avoid register conflicts in inline assembly (since almost all GPRs are context-switched), access guest_regs via absolute symbol addressing (guest_regs + offset) rather than using a base register which could get overwritten mid-assembly.

While at it, rename SAVE_GPR_C and LOAD_GPR_C to a single macro, SVM_SWITCH_GPRS_ASM, rename gpr64_regs to guest_regs, and expose it in processor.h (in preparation for reusing it for VMX).

Assisted-by Gemini:Gemini-Next
---
 .../selftests/kvm/include/x86/processor.h     | 31 +++++++++++-
 .../testing/selftests/kvm/lib/x86/processor.c |  2 +
 tools/testing/selftests/kvm/lib/x86/svm.c     | 49 +++++++++----------
 3 files changed, 54 insertions(+), 28 deletions(-)
tools/testing/selftests/kvm/include/x86/processor.h +29 -2
index b161174ece453..d7f1acaddd4ee 100644
@@ -398,8 +398,7 @@ static inline unsigned int x86_model(unsigned int eax)
 #define PTE_GET_PA(pte)		((pte) & PHYSICAL_PAGE_MASK)
 #define PTE_GET_PFN(pte)        (PTE_GET_PA(pte) >> PAGE_SHIFT)
 
-/* General Registers in 64-Bit Mode */
-struct gpr64_regs {
+struct guest_regs {
 	u64 rax;
 	u64 rcx;
 	u64 rdx;
@@ -418,6 +417,34 @@ struct gpr64_regs {
 	u64 r15;
 };
 
+extern struct guest_regs guest_regs;
+
+#define GUEST_REG_OFFSET(name) \
+	[off_##name] "i" (offsetof(struct guest_regs, name))
+
+#define GUEST_REGS_OFFSETS	\
+	GUEST_REG_OFFSET(rax),	\
+	GUEST_REG_OFFSET(rcx),	\
+	GUEST_REG_OFFSET(rdx),	\
+	GUEST_REG_OFFSET(rbx),	\
+	GUEST_REG_OFFSET(rsp),	\
+	GUEST_REG_OFFSET(rbp),	\
+	GUEST_REG_OFFSET(rsi),	\
+	GUEST_REG_OFFSET(rdi),	\
+	GUEST_REG_OFFSET(r8),	\
+	GUEST_REG_OFFSET(r9),	\
+	GUEST_REG_OFFSET(r10),	\
+	GUEST_REG_OFFSET(r11),	\
+	GUEST_REG_OFFSET(r12),	\
+	GUEST_REG_OFFSET(r13),	\
+	GUEST_REG_OFFSET(r14),	\
+	GUEST_REG_OFFSET(r15)
+
+#define GUEST_REG(name) "guest_regs + %c[off_" #name "]"
+
+#define GUEST_SWITCH_GPR_ASM(name) \
+	"xchg %%" #name ", " GUEST_REG(name) "\n\t"
+
 struct desc64 {
 	u16 limit0;
 	u16 base0;
tools/testing/selftests/kvm/lib/x86/processor.c +2 -0
index ef56dcefe0119..1f9201590f5b3 100644
@@ -29,6 +29,8 @@ bool host_cpu_is_amd_compatible;
 bool is_forced_emulation_enabled;
 u64 guest_tsc_khz;
 
+struct guest_regs guest_regs;
+
 const char *ex_str(int vector)
 {
 	switch (vector) {
tools/testing/selftests/kvm/lib/x86/svm.c +23 -26

77 lines not on this page · raw message

Signature · 1 line
2.55.0.229.g6434b31f56-goog
#6 lore raw

PATCH v4 4/12 KVM: selftests: Handle rflags save/restore for SVM in guest_regs

In reply to Yosry Ahmed

Instead of handling rflags separately, add it to guest_regs. No functional change intended.

Assisted-by Gemini:Gemini-Next
---
 tools/testing/selftests/kvm/include/x86/processor.h | 4 +++-
 tools/testing/selftests/kvm/lib/x86/svm.c           | 6 ++----
 2 files changed, 5 insertions(+), 5 deletions(-)
tools/testing/selftests/kvm/include/x86/processor.h +3 -1
index d7f1acaddd4ee..dab64688e8eae 100644
@@ -415,6 +415,7 @@ struct guest_regs {
 	u64 r13;
 	u64 r14;
 	u64 r15;
+	u64 rflags;
 };
 
 extern struct guest_regs guest_regs;
@@ -438,7 +439,8 @@ extern struct guest_regs guest_regs;
 	GUEST_REG_OFFSET(r12),	\
 	GUEST_REG_OFFSET(r13),	\
 	GUEST_REG_OFFSET(r14),	\
-	GUEST_REG_OFFSET(r15)
+	GUEST_REG_OFFSET(r15),	\
+	GUEST_REG_OFFSET(rflags)
 
 #define GUEST_REG(name) "guest_regs + %c[off_" #name "]"
 
tools/testing/selftests/kvm/lib/x86/svm.c +2 -4
index 7db38faded89e..b05be50f075d6 100644
@@ -13,8 +13,6 @@
 
 #define SEV_DEV_PATH "/dev/sev"
 
-u64 rflags;
-
 /* Allocate memory regions for nested SVM tests.
  *
  * Input Args:
@@ -161,7 +159,7 @@ void run_guest(struct vmcb *vmcb, u64 vmcb_gpa)
 {
 	asm volatile (
 		"vmload %[vmcb_gpa]\n\t"
-		"mov rflags, %%r15\n\t"
+		"mov " GUEST_REG(rflags) ", %%r15\n\t"
 		"mov %%r15, %[vmcb_rflags]\n\t"
 		"mov " GUEST_REG(rax) ", %%r15\n\t"
 		"mov %%r15, %[vmcb_rax]\n\t"
@@ -169,7 +167,7 @@ void run_guest(struct vmcb *vmcb, u64 vmcb_gpa)
 		"vmrun %[vmcb_gpa]\n\t"
 		SVM_SWITCH_GPRS_ASM
 		"mov %[vmcb_rflags], %%r15\n\t"
-		"mov %%r15, rflags\n\t"
+		"mov %%r15, " GUEST_REG(rflags) "\n\t"
 		"mov %[vmcb_rax], %%r15\n\t"	// rax
 		"mov %%r15, " GUEST_REG(rax) "\n\t"
 		"vmsave %[vmcb_gpa]\n\t"
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#7 lore raw

PATCH v4 5/12 KVM: selftests: Reuse GPR switching logic for nVMX

In reply to Yosry Ahmed

Reuse the GPR switching logic for nVMX by defining VMX_SWITCH_GPRS_ASM, which is essentially the same as SVM_SWITCH_GPRS_ASM but also switches RAX and doesn't switch RFLAGS, replacing the push/pop of a subset of the registers.

The long clobber list of registers is no longer needed as registers are saved and restored appropriately (and not clobbered by L2).

Define VMX_SWITCH_GPRS_ASM before including evmcs.h, such that it can be used by evmcs_vmlaunch() and evmcs_vmresume().

This replaces the apparently thread-safe push/pop sequence with the global GPR switching logic used by SVM, which isn't thread-safe at all.

However this is still an improvement because:
- The VMX logic is half-baked and prompts the UCALL clobber hack as it doesn't properly save/restore everything. Reusing the GPR switching logic used by SVM allows for dropping that hack.

- Hitting a problem due to half-baked GPR save/restore logic is arguably more likely than thread-safety. Evidently, adding more involved stress tests fails on VMX with the existing push/pop sequence. OTOH, there are no known failures on SVM due to lack of thread-safety fo save/restore. Only one test currently uses more than one vCPU with nested (the memstress test).

The logical next step is to move the guest_regs to be per-vCPU, making it thread-safe for both VMX and SVM in a proper way.

Assisted-by Gemini:gemini-3.1-pro
---
 .../testing/selftests/kvm/include/x86/evmcs.h | 46 +++++--------
 tools/testing/selftests/kvm/include/x86/vmx.h | 69 +++++++++----------
 2 files changed, 49 insertions(+), 66 deletions(-)
tools/testing/selftests/kvm/include/x86/evmcs.h +16 -30
index be79bda024bf1..82a8ea6b661f0 100644
@@ -1207,30 +1207,23 @@ static inline int evmcs_vmlaunch(void)
 
 	current_evmcs->hv_clean_fields = 0;
 
-	__asm__ __volatile__("push %%rbp;"
-			     "push %%rcx;"
-			     "push %%rdx;"
-			     "push %%rsi;"
-			     "push %%rdi;"
-			     "push $0;"
+	__asm__ __volatile__("push $0;"
 			     "mov %%rsp, (%[host_rsp]);"
 			     "lea 1f(%%rip), %%rax;"
 			     "mov %%rax, (%[host_rip]);"
+			     VMX_SWITCH_GPRS_ASM
 			     "vmlaunch;"
 			     "incq (%%rsp);"
-			     "1: pop %%rax;"
-			     "pop %%rdi;"
-			     "pop %%rsi;"
-			     "pop %%rdx;"
-			     "pop %%rcx;"
-			     "pop %%rbp;"
+			     "1: ;"
+			     VMX_SWITCH_GPRS_ASM
+			     "pop %%rax;"
 			     : [ret]"=&a"(ret)
 			     : [host_rsp]"r"
 			       ((u64)&current_evmcs->host_rsp),
 			       [host_rip]"r"
-			       ((u64)&current_evmcs->host_rip)
-			     : "memory", "cc", "rbx", "r8", "r9", "r10",
-			       "r11", "r12", "r13", "r14", "r15");
+			       ((u64)&current_evmcs->host_rip),
+			       GUEST_REGS_OFFSETS
+			     : "memory", "cc");
 	return ret;
 }
 
@@ -1246,30 +1239,23 @@ static inline int evmcs_vmresume(void)
 	/* HOST_RSP */
 	current_evmcs->hv_clean_fields &= ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_HOST_POINTER;
 
-	__asm__ __volatile__("push %%rbp;"
-			     "push %%rcx;"
-			     "push %%rdx;"
-			     "push %%rsi;"
-			     "push %%rdi;"
-			     "push $0;"
+	__asm__ __volatile__("push $0;"
 			     "mov %%rsp, (%[host_rsp]);"
 			     "lea 1f(%%rip), %%rax;"
 			     "mov %%rax, (%[host_rip]);"
+			     VMX_SWITCH_GPRS_ASM
 			     "vmresume;"
 			     "incq (%%rsp);"
-			     "1: pop %%rax;"
-			     "pop %%rdi;"
-			     "pop %%rsi;"
-			     "pop %%rdx;"
-			     "pop %%rcx;"
-			     "pop %%rbp;"
+			     "1: ;"
+			     VMX_SWITCH_GPRS_ASM
+			     "pop %%rax;"
 			     : [ret]"=&a"(ret)
 			     : [host_rsp]"r"
 			       ((u64)&current_evmcs->host_rsp),
 			       [host_rip]"r"
-			       ((u64)&current_evmcs->host_rip)
-			     : "memory", "cc", "rbx", "r8", "r9", "r10",
-			       "r11", "r12", "r13", "r14", "r15");
+			       ((u64)&current_evmcs->host_rip),
+			       GUEST_REGS_OFFSETS
+			     : "memory", "cc");
 	return ret;
 }
 
tools/testing/selftests/kvm/include/x86/vmx.h +33 -36

110 lines not on this page · raw message

Signature · 1 line
2.55.0.229.g6434b31f56-goog
#8 lore raw

Re: [PATCH v4 05/12] KVM: selftests: Reuse GPR switching logic for nVMX

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The commit introduces a severe data race by switching VMX nested tests to use a global…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The commit introduces a severe data race by switching VMX nested tests to use a global guest_regs structure for GPR switching, intentionally breaking multi-vCPU tests. --

--- Patch [5]: [PATCH v4 05/12] KVM: selftests: Reuse GPR switching logic for nVMX --- commit 685ecb766edbf0f5d0df447d92a4e818914eeff2
Author: Yosry Ahmed <[email protected]>

KVM: selftests: Reuse GPR switching logic for nVMX

This commit replaces the stack-based thread-safe GPR switching in nVMX tests with a global GPR switching logic used by SVM. It adds VMX_SWITCH_GPRS_ASM which switches registers into a global guest_regs structure during vmlaunch and vmresume.

Quoted 4 lines
tools/testing/selftests/kvm/include/x86/evmcs.h +0 -0
index be79bda024bf1..82a8ea6b661f0 100644

[ ... ]

Quoted 5 lines
tools/testing/selftests/kvm/include/x86/evmcs.h +0 -1
@@ -1207,30 +1207,23 @@ static inline int evmcs_vmlaunch(void)
 
 	current_evmcs->hv_clean_fields = 0;
 
-	__asm__ __volatile__("push %%rbp;"

tools/testing/selftests/kvm/include/x86/evmcs.h static inline int evmcs_vmlaunch(void) · line 1214

Quoted 10 lines
tools/testing/selftests/kvm/include/x86/evmcs.h +2 -5
-			     "push %%rcx;"
-			     "push %%rdx;"
-			     "push %%rsi;"
-			     "push %%rdi;"
-			     "push $0;"
+	__asm__ __volatile__("push $0;"
 			     "mov %%rsp, (%[host_rsp]);"
 			     "lea 1f(%%rip), %%rax;"
 			     "mov %%rax, (%[host_rip]);"
+			     VMX_SWITCH_GPRS_ASM

[Severity: Medium]
Will this corrupt register state in multi-vCPU nested tests?

By moving from a thread-safe stack push/pop sequence to using VMX_SWITCH_GPRS_ASM, concurrent tests that execute evmcs_vmlaunch() could overwrite each other's saved GPRs.

This happens because the registers are swapped into a global guest_regs structure rather than being pushed to each thread's local stack.

Quoted 2 lines
tools/testing/selftests/kvm/include/x86/evmcs.h +0 -0
 			     "vmlaunch;"
 			     "incq (%%rsp);"

[ ... ]

Quoted 4 lines
tools/testing/selftests/kvm/include/x86/vmx.h +0 -0
index 4bcfd60e3aecb..04f5e34dea3ae 100644

[ ... ]

Quoted 11 lines
tools/testing/selftests/kvm/include/x86/vmx.h +7 -0
@@ -290,6 +290,23 @@ struct vmx_msr_entry {
 	u64 value;
 } __attribute__ ((aligned(16)));
 
+#define VMX_SWITCH_GPRS_ASM \
+	GUEST_SWITCH_GPR_ASM(rax) \
+	GUEST_SWITCH_GPR_ASM(rbx) \
+	GUEST_SWITCH_GPR_ASM(rcx) \
+	GUEST_SWITCH_GPR_ASM(rdx) \
+	GUEST_SWITCH_GPR_ASM(rbp) \
+	GUEST_SWITCH_GPR_ASM(rsi) \

tools/testing/selftests/kvm/include/x86/vmx.h struct vmx_msr_entry { · line 309

Quoted 10 lines
tools/testing/selftests/kvm/include/x86/vmx.h +10 -0
+	GUEST_SWITCH_GPR_ASM(rdi) \
+	GUEST_SWITCH_GPR_ASM(r8)  \
+	GUEST_SWITCH_GPR_ASM(r9)  \
+	GUEST_SWITCH_GPR_ASM(r10) \
+	GUEST_SWITCH_GPR_ASM(r11) \
+	GUEST_SWITCH_GPR_ASM(r12) \
+	GUEST_SWITCH_GPR_ASM(r13) \
+	GUEST_SWITCH_GPR_ASM(r14) \
+	GUEST_SWITCH_GPR_ASM(r15)
+

[Severity: Medium]
Could this macro introduce data races during GPR switching?

Since VMX_SWITCH_GPRS_ASM generates instructions that rely on a shared global guest_regs structure, any multi-vCPU nested tests (like the memstress framework) running concurrent operations might crash due to host threads clobbering the global state.

Quoted 3 lines
tools/testing/selftests/kvm/include/x86/vmx.h +0 -0
 #include "evmcs.h"
 
 static inline int vmxon(u64 phys)

[ ... ]

Quoted 6 lines
tools/testing/selftests/kvm/include/x86/vmx.h +0 -2
@@ -373,34 +387,24 @@ static inline int vmlaunch(void)
 	if (enable_evmcs)
 		return evmcs_vmlaunch();
 
-	__asm__ __volatile__("push %%rbp;"
-			     "push %%rcx;"

tools/testing/selftests/kvm/include/x86/vmx.h static inline int vmlaunch(void) · line 395

Quoted 10 lines
tools/testing/selftests/kvm/include/x86/vmx.h +2 -4
-			     "push %%rdx;"
-			     "push %%rsi;"
-			     "push %%rdi;"
-			     "push $0;"
+	__asm__ __volatile__("push $0;"
 			     "vmwrite %%rsp, %[host_rsp];"
 			     "lea 1f(%%rip), %%rax;"
 			     "vmwrite %%rax, %[host_rip];"
+			     VMX_SWITCH_GPRS_ASM
 			     "vmlaunch;"

[Severity: Medium]
Does this change similarly break vmlaunch() for multi-vCPU tests?

Just like evmcs_vmlaunch(), replacing the previously thread-safe stack pushes here with VMX_SWITCH_GPRS_ASM will cause register data corruption when multiple threads execute vmlaunch() concurrently.

Quoted 10 lines
tools/testing/selftests/kvm/include/x86/vmx.h +3 -6
 			     "incq (%%rsp);"
-			     "1: pop %%rax;"
-			     "pop %%rdi;"
-			     "pop %%rsi;"
-			     "pop %%rdx;"
-			     "pop %%rcx;"
-			     "pop %%rbp;"
+			     "1: ;"
+			     VMX_SWITCH_GPRS_ASM
+			     "pop %%rax;"
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#9 lore raw

Re: [PATCH v4 05/12] KVM: selftests: Reuse GPR switching logic for nVMX

Quoted 3 lines · On Mon, Jul 27, 2026 at 5:05 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The commit introduces a severe data race by switching VMX nested tests to use a global guest_regs structure for GPR switching, intentionally breaking multi-vCPU tests.

Yes, this is known and documented in the changelog.

#10 lore raw

PATCH v4 6/12 KVM: selftests: Drop HORRIFIC_L2_UCALL_CLOBBER_HACK

In reply to Yosry Ahmed

Now that nVMX test codes preserves GPRs across nested VM-Exits (specifically RBP, RDX, and RDI among others), drop the ucall-specific hack to avoid clobbering these registers.

Assisted-by Gemini:gemini-3.1-pro
---
 tools/testing/selftests/kvm/lib/x86/ucall.c | 32 ++-------------------
 1 file changed, 2 insertions(+), 30 deletions(-)
tools/testing/selftests/kvm/lib/x86/ucall.c +2 -30
index e7dd5791959ba..38050c60a0670 100644
@@ -10,36 +10,8 @@
 
 void ucall_arch_do_ucall(gva_t uc)
 {
-	/*
-	 * FIXME: Revert this hack (the entire commit that added it) once nVMX
-	 * preserves L2 GPRs across a nested VM-Exit.  If a ucall from L2, e.g.
-	 * to do a GUEST_SYNC(), lands the vCPU in L1, any and all GPRs can be
-	 * clobbered by L1.  Save and restore non-volatile GPRs (clobbering RBP
-	 * in particular is problematic) along with RDX and RDI (which are
-	 * inputs), and clobber volatile GPRs. *sigh*
-	 */
-#define HORRIFIC_L2_UCALL_CLOBBER_HACK	\
-	"rcx", "rsi", "r8", "r9", "r10", "r11"
-
-	asm volatile("push %%rbp\n\t"
-		     "push %%r15\n\t"
-		     "push %%r14\n\t"
-		     "push %%r13\n\t"
-		     "push %%r12\n\t"
-		     "push %%rbx\n\t"
-		     "push %%rdx\n\t"
-		     "push %%rdi\n\t"
-		     "in %[port], %%al\n\t"
-		     "pop %%rdi\n\t"
-		     "pop %%rdx\n\t"
-		     "pop %%rbx\n\t"
-		     "pop %%r12\n\t"
-		     "pop %%r13\n\t"
-		     "pop %%r14\n\t"
-		     "pop %%r15\n\t"
-		     "pop %%rbp\n\t"
-		: : [port] "d" (UCALL_PIO_PORT), "D" (uc) : "rax", "memory",
-		     HORRIFIC_L2_UCALL_CLOBBER_HACK);
+	asm volatile("in %[port], %%al"
+		: : [port] "d" (UCALL_PIO_PORT), "D" (uc) : "rax", "memory");
 }
 
 void *ucall_arch_get_ucall(struct kvm_vcpu *vcpu)
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#11 lore raw

PATCH v4 7/12 KVM: selftests: Add a blank line before logging assertion failures

In reply to Yosry Ahmed

Add a blank line for visual separation, which is especially useful for tests that use carriage returns for same-line printing, in case a failure occurs before a blank line is ever logged by the test.

---
 tools/testing/selftests/kvm/lib/assert.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/kvm/lib/assert.c +1 -1
index 1d72dcdfce3b6..3e353ac39eeb7 100644
@@ -74,7 +74,7 @@ test_assert(bool exp, const char *exp_str,
 	if (!(exp)) {
 		va_start(ap, fmt);
 
-		fprintf(stderr, "==== Test Assertion Failure ====\n"
+		fprintf(stderr, "\n==== Test Assertion Failure ====\n"
 			"  %s:%u: %s\n"
 			"  pid=%d tid=%d errno=%d - %s\n",
 			file, line, exp_str, getpid(), kvm_gettid(),
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#12 lore raw

PATCH v4 8/12 KVM: selftests: Expose PTE masks to guests as part of an MMU

In reply to Yosry Ahmed

Expose a guest_mmu to the guest to allow guest code to use the PTE masks for page table manipulation. Since guest page tables are not mapped in the guest by default, zero the PGD in guest_mmu in an attempt to make it more difficult for new tests to shoot themselves in the foot and assume that page tables can be immediately used by guest code.

Ultimately, guest code can read CR3 any way, so guest_mmu.pgd doesn't add a lot of value.

---
 tools/testing/selftests/kvm/include/x86/processor.h |  1 +
 tools/testing/selftests/kvm/lib/x86/processor.c     | 12 ++++++++++++
 2 files changed, 13 insertions(+)
tools/testing/selftests/kvm/include/x86/processor.h +1 -0
index dab64688e8eae..06d9ba1c4df33 100644
@@ -24,6 +24,7 @@ extern bool host_cpu_is_amd;
 extern bool host_cpu_is_hygon;
 extern bool host_cpu_is_amd_compatible;
 extern u64 guest_tsc_khz;
+extern struct kvm_mmu guest_mmu;
 
 #ifndef MAX_NR_CPUID_ENTRIES
 #define MAX_NR_CPUID_ENTRIES 100
tools/testing/selftests/kvm/lib/x86/processor.c +12 -0
index 1f9201590f5b3..d31fa81ea0756 100644
@@ -28,6 +28,7 @@ bool host_cpu_is_hygon;
 bool host_cpu_is_amd_compatible;
 bool is_forced_emulation_enabled;
 u64 guest_tsc_khz;
+struct kvm_mmu guest_mmu;
 
 struct guest_regs guest_regs;
 
@@ -831,6 +832,17 @@ void kvm_arch_vm_post_create(struct kvm_vm *vm, unsigned int nr_vcpus)
 	TEST_ASSERT(r > 0, "KVM_GET_TSC_KHZ did not provide a valid TSC frequency.");
 	guest_tsc_khz = r;
 	sync_global_to_guest(vm, guest_tsc_khz);
+
+	/*
+	 * The guest MMU is just a placeholder to provide access to PTE masks
+	 * (for now). The guest does not have mappings for its own page tables
+	 * by default, so any meaningful use of guest page tables requires
+	 * explicit setup by the test. Zero the PGD to make it obvious the guest
+	 * page tables are not immediately usable by guest code.
+	 */
+	guest_mmu = vm->mmu;
+	guest_mmu.pgd = 0;
+	sync_global_to_guest(vm, guest_mmu);
 }
 
 void vcpu_arch_set_entry_point(struct kvm_vcpu *vcpu, void *guest_code)
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#13 lore raw

PATCH v4 9/12 KVM: selftests: Add basic stress test for save+restore and #PF handling

In reply to Yosry Ahmed

Add a basic stress test for handling #PFs in a guest while the host is doing save+restore cycles. The guest periodically accesses non-present memory causing a #PF, and the #PF handler walks the page tables and updates the PTE to be present, like a proper #PF handler.

After every access (and #PF), the guest triggers a sync and the test performs save+restore of the VM. This is not very meaningful as save+restore are performed after the access and #PF handling complete, but following changes will change that.

Assisted-by Gemini:gemini-3.1-pro
---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../selftests/kvm/include/x86/processor.h     |  14 ++
 .../kvm/x86/save_restore_pf_stress_test.c     | 160 ++++++++++++++++++
 3 files changed, 175 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 88c6c8046ddec..e67b1e9893f68 100644
@@ -112,6 +112,7 @@ TEST_GEN_PROGS_x86 += x86/set_sregs_test
 TEST_GEN_PROGS_x86 += x86/smaller_maxphyaddr_emulation_test
 TEST_GEN_PROGS_x86 += x86/smm_test
 TEST_GEN_PROGS_x86 += x86/state_test
+TEST_GEN_PROGS_x86 += x86/save_restore_pf_stress_test
 TEST_GEN_PROGS_x86 += x86/vmx_preemption_timer_test
 TEST_GEN_PROGS_x86 += x86/svm_vmcall_test
 TEST_GEN_PROGS_x86 += x86/svm_int_ctl_test
tools/testing/selftests/kvm/include/x86/processor.h +14 -0
index 06d9ba1c4df33..2889782b0016b 100644
@@ -614,6 +614,15 @@ static inline void set_cr0(u64 val)
 	__asm__ __volatile__("mov %0, %%cr0" : : "r" (val) : "memory");
 }
 
+static inline u64 get_cr2(void)
+{
+	u64 cr2;
+
+	__asm__ __volatile__("mov %%cr2, %[cr2]"
+			     : /* output */ [cr2]"=r"(cr2));
+	return cr2;
+}
+
 static inline u64 get_cr3(void)
 {
 	u64 cr3;
@@ -909,6 +918,11 @@ static inline void write_sse_reg(int reg, const sse128_t *data)
 	}
 }
 
+static inline void invlpg(u64 addr)
+{
+	__asm__ __volatile__("invlpg (%0)" : : "r"(addr) : "memory");
+}
+
 static inline void cpu_relax(void)
 {
 	asm volatile("rep; nop" ::: "memory");
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c new file +160 -0

160 lines not on this page · raw message

Signature · 1 line
2.55.0.229.g6434b31f56-goog
#14 lore raw

Re: [PATCH v4 09/12] KVM: selftests: Add basic stress test for save+restore and #PF handling

tools/testing/selftests/kvm/Makefile.kvm TEST_GEN_PROGS_x86 += x86/set_sregs_test · line 115

Quoted 9 lines · Yosry Ahmed
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 88c6c8046ddec..e67b1e9893f68 100644
@@ -112,6 +112,7 @@ TEST_GEN_PROGS_x86 += x86/set_sregs_test
 TEST_GEN_PROGS_x86 += x86/smaller_maxphyaddr_emulation_test
 TEST_GEN_PROGS_x86 += x86/smm_test
 TEST_GEN_PROGS_x86 += x86/state_test
+TEST_GEN_PROGS_x86 += x86/save_restore_pf_stress_test

Sort alphabetically (I'm guessing you forgot to move this when renaming from stress_xxx to save_xxx).

Quoted 8 lines
tools/testing/selftests/kvm/Makefile.kvm +0 -0
 TEST_GEN_PROGS_x86 += x86/vmx_preemption_timer_test
 TEST_GEN_PROGS_x86 += x86/svm_vmcall_test
 TEST_GEN_PROGS_x86 += x86/svm_int_ctl_test
tools/testing/selftests/kvm/include/x86/processor.h +0 -0
index 06d9ba1c4df33..2889782b0016b 100644

tools/testing/selftests/kvm/include/x86/processor.h static inline void set_cr0(u64 val) · line 622

Quoted 9 lines
tools/testing/selftests/kvm/include/x86/processor.h +6 -0
@@ -614,6 +614,15 @@ static inline void set_cr0(u64 val)
 	__asm__ __volatile__("mov %0, %%cr0" : : "r" (val) : "memory");
 }
 
+static inline u64 get_cr2(void)
+{
+	u64 cr2;
+
+	__asm__ __volatile__("mov %%cr2, %[cr2]"
+			     : /* output */ [cr2]"=r"(cr2));

Drop the "/* output */" comment, if the reader doesn't know how asm constraints work *and* can't deduce that it's an output given the function name and return value, then they probably shouldn't be reading this code.

Oh, yeesh, all of these getters have that silly comment. Drop it here, I'll send a patch to remove those bad examples.

Quoted 3 lines
tools/testing/selftests/kvm/include/x86/processor.h +3 -0
+	return cr2;
+}
+
#15 lore raw

PATCH v4 10/12 KVM: selftests: Trigger save+restore randomly in the #PF stress test

In reply to Yosry Ahmed

Instead of an explicit GUEST_SYNC() after each access+#PF, run another thread that keeps sending SIGUSR to the vCPU thread, essentially triggering exits to userspace and save+restore on random points in guest execution. This makes the test a lot more meaningful as it opens the door to exercising race conditions between #PF handling in the guest and save+restore in the host.

The signals are ignored using SIG_IGN outside of __vcpu_run() to avoid interrupting other ioctls/sysctls performed by the test.

Assisted-by Gemini:gemini-3.1-pro
---
 .../kvm/x86/save_restore_pf_stress_test.c     | 59 ++++++++++++++++---
 1 file changed, 51 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +51 -8
index 1f7e142e5cfec..664ed280b2e76 100644
@@ -5,6 +5,8 @@
 #include <errno.h>
 #include <sys/types.h>
 #include <time.h>
+#include <pthread.h>
+#include <signal.h>
 #include <unistd.h>
 
 #include "test_util.h"
@@ -76,15 +78,41 @@ static void guest_access_memory(void *arg)
 		/* Clear the present bit again so it faults next time */
 		*guest_get_pte(vaddr) &= ~PTE_PRESENT_MASK(&guest_mmu);
 		invlpg(vaddr);
+	}
+}
+
+static void *sigusr_thread_fn(void *arg)
+{
+	pthread_t vcpu_thread = (pthread_t)arg;
 
-		GUEST_SYNC(guest_faults);
+	for (;;) {
+		pthread_testcancel();
+		pthread_kill(vcpu_thread, SIGUSR1);
+		usleep(msecs_to_usecs(1));
 	}
+	return NULL;
+}
+
+static void dummy_signal_handler(int signo) {}
+static struct sigaction sa;
+
+static void vcpu_sigusr_listen(void)
+{
+	sa.sa_handler = dummy_signal_handler;
+	sigaction(SIGUSR1, &sa, NULL);
+}
+
+static void vcpu_sigusr_ignore(void)
+{
+	sa.sa_handler = SIG_IGN;
+	sigaction(SIGUSR1, &sa, NULL);
 }
 
 int main(int argc, char *argv[])
 {
 	struct kvm_x86_state *state;
 	int r, i, level;
+	pthread_t sigusr_thread;
 	gpa_t gpa, pgtable_gpa;
 	struct kvm_vcpu *vcpu;
 	struct kvm_vm *vm;
@@ -128,18 +156,30 @@ int main(int argc, char *argv[])
 		pgtable_gpa = PTE_GET_PA(pte);
 	}
 
+	/* Initialize the thread sending SIGUSR and install the handler */
+	vcpu_sigusr_ignore();
+	r = pthread_create(&sigusr_thread, NULL, sigusr_thread_fn,
+			   (void *)pthread_self());
+	TEST_ASSERT(!r, "pthread_create() failed: %d", r);
+
 	for (i = 1; i <= NR_ITERATIONS; i++) {
+		/*
+		 * Only handle SIGUSR while the vCPU is running, otherwise
+		 * ignore it to avoid interrupting other ioctls/syscalls.
+		 */
+		vcpu_sigusr_listen();
 		r = __vcpu_run(vcpu);
-		TEST_ASSERT(!r, "vcpu_run failed");
-		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
-
-		get_ucall(vcpu, &uc);
-		if (uc.cmd == UCALL_ABORT) {
+		if (r == -1)
+			TEST_ASSERT_EQ(errno, EINTR);
+		vcpu_sigusr_ignore();
+
+		/* The guest only exits due to a signal or failed assertion */
+		if (!r) {
+			TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+			TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_ABORT);
 			REPORT_GUEST_ASSERT(uc);
 			break;
 		}
-		TEST_ASSERT_EQ(uc.cmd, UCALL_SYNC);
-		TEST_ASSERT_EQ(uc.args[1], i);
 
 		state = vcpu_save_state(vcpu);
 
@@ -153,8 +193,11 @@ int main(int argc, char *argv[])
 	pr_info("\n");
 
 	sync_global_from_guest(vm, guest_faults);
+	TEST_ASSERT(guest_faults > 0, "No guest page faults triggered");
 	pr_info("Guest page faults: %lu\n", guest_faults);
 
+	pthread_cancel(sigusr_thread);
+	pthread_join(sigusr_thread, NULL);
 	kvm_vm_free(vm);
 	return 0;
 }
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#16 lore raw

Re: [PATCH v4 10/12] KVM: selftests: Trigger save+restore randomly in the #PF stress test

Quoted 22 lines · Yosry Ahmed

int main(int argc, char *argv[])
{

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +10 -0
 	struct kvm_x86_state *state;
 	int r, i, level;
+	pthread_t sigusr_thread;
 	gpa_t gpa, pgtable_gpa;
 	struct kvm_vcpu *vcpu;
 	struct kvm_vm *vm;
@@ -128,18 +156,30 @@ int main(int argc, char *argv[])
 		pgtable_gpa = PTE_GET_PA(pte);
 	}
 
+	/* Initialize the thread sending SIGUSR and install the handler */
+	vcpu_sigusr_ignore();
+	r = pthread_create(&sigusr_thread, NULL, sigusr_thread_fn,
+			   (void *)pthread_self());
+	TEST_ASSERT(!r, "pthread_create() failed: %d", r);
+
 	for (i = 1; i <= NR_ITERATIONS; i++) {
+		/*
+		 * Only handle SIGUSR while the vCPU is running, otherwise
+		 * ignore it to avoid interrupting other ioctls/syscalls.

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c int main(int argc, char *argv[]) · line 173

Quoted 10 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +4 -5
+		 */
+		vcpu_sigusr_listen();
 		r = __vcpu_run(vcpu);
-		TEST_ASSERT(!r, "vcpu_run failed");
-		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
-
-		get_ucall(vcpu, &uc);
-		if (uc.cmd == UCALL_ABORT) {
+		if (r == -1)
+			TEST_ASSERT_EQ(errno, EINTR);
		TEST_ASSERT(!r || errno == EINTR, "Expected success or SIGUSR1");
Quoted 15 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +6 -2
+		vcpu_sigusr_ignore();
+
+		/* The guest only exits due to a signal or failed assertion */
+		if (!r) {
+			TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+			TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_ABORT);
 			REPORT_GUEST_ASSERT(uc);
 			break;
 		}
-		TEST_ASSERT_EQ(uc.cmd, UCALL_SYNC);
-		TEST_ASSERT_EQ(uc.args[1], i);
 
 		state = vcpu_save_state(vcpu);
 

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c int main(int argc, char *argv[]) · line 196

Quoted 4 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +1 -0
@@ -153,8 +193,11 @@ int main(int argc, char *argv[])
 	pr_info("\n");
 
 	sync_global_from_guest(vm, guest_faults);
+	TEST_ASSERT(guest_faults > 0, "No guest page faults triggered");

Since guest_faults is an unsigned value, the kernel's preferred style is:

	TEST_ASSERT(guest_faults, "No guest page faults triggered");
Quoted 10 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +2 -0
 	pr_info("Guest page faults: %lu\n", guest_faults);
 
+	pthread_cancel(sigusr_thread);
+	pthread_join(sigusr_thread, NULL);
 	kvm_vm_free(vm);
 	return 0;
 }
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#17 lore raw

PATCH v4 11/12 KVM: selftests: Support running stress save+restore and #PF test in L2

In reply to Yosry Ahmed

Extend the stress test to allow running the access+#PF code in L2 instead of L1 by adding proper L1 guest code to bootstrap L2. By default, the test runs in L2 after running in L1 if nested is supported.

Assisted-by Gemini:gemini-3.1-pro
---
 .../kvm/x86/save_restore_pf_stress_test.c     | 61 ++++++++++++++++++-
 1 file changed, 58 insertions(+), 3 deletions(-)
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +58 -3
index 664ed280b2e76..0e5ddeb5af444 100644
@@ -8,10 +8,13 @@
 #include <pthread.h>
 #include <signal.h>
 #include <unistd.h>
+#include <getopt.h>
 
 #include "test_util.h"
 #include "kvm_util.h"
 #include "processor.h"
+#include "svm_util.h"
+#include "vmx.h"
 
 #define NR_ITERATIONS		500
 
@@ -81,6 +84,36 @@ static void guest_access_memory(void *arg)
 	}
 }
 
+static void l1_svm_code(struct svm_test_data *svm)
+{
+	generic_svm_setup(svm, guest_access_memory);
+	run_guest(svm->vmcb, svm->vmcb_gpa);
+	GUEST_ASSERT(false);
+}
+
+static void l1_vmx_code(struct vmx_pages *vmx)
+{
+	GUEST_ASSERT(prepare_for_vmx_operation(vmx));
+	GUEST_ASSERT(load_vmcs(vmx));
+	prepare_vmcs(vmx, guest_access_memory);
+
+	/* Ignore any #PF */
+	GUEST_ASSERT(!vmwrite(EXCEPTION_BITMAP, BIT(PF_VECTOR)));
+	GUEST_ASSERT(!vmwrite(PAGE_FAULT_ERROR_CODE_MASK, 0));
+	GUEST_ASSERT(!vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, -1));
+
+	GUEST_ASSERT(!vmlaunch());
+	GUEST_ASSERT(false);
+}
+
+static void l1_guest_code(void *test_data)
+{
+	if (this_cpu_has(X86_FEATURE_SVM))
+		l1_svm_code(test_data);
+	else
+		l1_vmx_code(test_data);
+}
+
 static void *sigusr_thread_fn(void *arg)
 {
 	pthread_t vcpu_thread = (pthread_t)arg;
@@ -108,7 +141,7 @@ static void vcpu_sigusr_ignore(void)
 	sigaction(SIGUSR1, &sa, NULL);
 }
 
-int main(int argc, char *argv[])
+static void run_test(bool nested)
 {
 	struct kvm_x86_state *state;
 	int r, i, level;
@@ -121,9 +154,17 @@ int main(int argc, char *argv[])
 	gva_t gva;
 	u64 pte;
 
-	vm = vm_create_with_one_vcpu(&vcpu, guest_access_memory);
+	vm = vm_create_with_one_vcpu(&vcpu, nested ? l1_guest_code : guest_access_memory);
 	vm_install_exception_handler(vm, PF_VECTOR, guest_pf_handler);
 
+	if (nested) {
+		if (kvm_cpu_has(X86_FEATURE_SVM))
+			vcpu_alloc_svm(vm, &gva);
+		else
+			vcpu_alloc_vmx(vm, &gva);
+		vcpu_args_set(vcpu, 1, gva);
+	}
+
 	/* Allocate a page and write the pattern to it */
 	gva = vm_alloc_page(vm);
 	*(u64 *)addr_gva2hva(vm, gva) = PATTERN;
@@ -194,10 +235,24 @@ int main(int argc, char *argv[])
 
 	sync_global_from_guest(vm, guest_faults);
 	TEST_ASSERT(guest_faults > 0, "No guest page faults triggered");
-	pr_info("Guest page faults: %lu\n", guest_faults);
+	pr_info("Guest page faults%s: %lu\n", nested ? " (in L2)" : "", guest_faults);
 
 	pthread_cancel(sigusr_thread);
 	pthread_join(sigusr_thread, NULL);
 	kvm_vm_free(vm);
+}
+
+int main(int argc, char *argv[])
+{
+	pr_info("Running save+restore stress test...\n");
+	run_test(/*nested=*/false);
+
+	if (!kvm_cpu_has(X86_FEATURE_SVM) && !kvm_cpu_has(X86_FEATURE_VMX)) {
+		pr_info("Nested virtualization not supported, skipping nested test\n");
+		return 0;
+	}
+
+	pr_info("Running save+restore stress test with a nested guest...\n");
+	run_test(/*nested=*/true);
 	return 0;
 }
Signature · 1 line
2.55.0.229.g6434b31f56-goog
#18 lore raw

Re: [PATCH v4 11/12] KVM: selftests: Support running stress save+restore and #PF test in L2

Quoted 36 lines · Yosry Ahmed

Extend the stress test to allow running the access+#PF code in L2 instead of L1 by adding proper L1 guest code to bootstrap L2. By default, the test runs in L2 after running in L1 if nested is supported.

Assisted-by Gemini:gemini-3.1-pro
---
 .../kvm/x86/save_restore_pf_stress_test.c     | 61 ++++++++++++++++++-
 1 file changed, 58 insertions(+), 3 deletions(-)
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +7 -0
index 664ed280b2e76..0e5ddeb5af444 100644
@@ -8,10 +8,13 @@
 #include <pthread.h>
 #include <signal.h>
 #include <unistd.h>
+#include <getopt.h>
 
 #include "test_util.h"
 #include "kvm_util.h"
 #include "processor.h"
+#include "svm_util.h"
+#include "vmx.h"
 
 #define NR_ITERATIONS		500
 
@@ -81,6 +84,36 @@ static void guest_access_memory(void *arg)
 	}
 }
 
+static void l1_svm_code(struct svm_test_data *svm)
+{
+	generic_svm_setup(svm, guest_access_memory);
+	run_guest(svm->vmcb, svm->vmcb_gpa);

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c static void guest_access_memory(void *arg) · line 100

Quoted 10 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +10 -0
+	GUEST_ASSERT(false);
+}
+
+static void l1_vmx_code(struct vmx_pages *vmx)
+{
+	GUEST_ASSERT(prepare_for_vmx_operation(vmx));
+	GUEST_ASSERT(load_vmcs(vmx));
+	prepare_vmcs(vmx, guest_access_memory);
+
+	/* Ignore any #PF */

This comment is rather ambiguous, especially when the #UD interception comes along, because unless the reader is reading carefully and sees the PFEC_MASK and PFEC_MATCH logic below, it's quite easy to read this as "intercept #PF to ignore them".

I don't see any reason to write the code this way. Yeah yeah, it's the SDM's suggested way to ignore #PFs, but IMO that's unnecessarily convoluted. The more obvious way is to leave all fields '0'.

In other words, just delete this entire block of code and rely on the default VMX allocation logic to disable interception of all exceptions.

Oh, damnit. Argh. I see why you need this. init_vmcs_control_fields() is buggy and actually configures #PF for interception. Apparently Paolo didn't read the "If there is inequality, the meaning of that bit is reversed (for example, a VM exit occurs if that bit is clear)." part :-D

So, let's fix that in a prep patch (AFAICT, no existing tests cares about #PF interception) so that this test doesn't have to carry confusing code, and because intercpeting #PF but nothing else by default is bound to cause problems.

testing/selftests/kvm/lib/x86/vmx.c +1 -1
index cd09c9de4485..089e1a8af53f 100644
@@ -232,7 +232,7 @@ static inline void init_vmcs_control_fields(struct vmx_pages *vmx)
 
        vmwrite(EXCEPTION_BITMAP, 0);
        vmwrite(PAGE_FAULT_ERROR_CODE_MASK, 0);
-       vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, -1); /* Never match */
+       vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, 0);
        vmwrite(CR3_TARGET_COUNT, 0);
        vmwrite(VM_EXIT_CONTROLS, rdmsr(MSR_IA32_VMX_EXIT_CTLS) |
                VM_EXIT_HOST_ADDR_SPACE_SIZE);    /* 64-bit host */
Quoted 7 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +7 -0
+	GUEST_ASSERT(!vmwrite(EXCEPTION_BITMAP, BIT(PF_VECTOR)));
+	GUEST_ASSERT(!vmwrite(PAGE_FAULT_ERROR_CODE_MASK, 0));
+	GUEST_ASSERT(!vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, -1));
+
+	GUEST_ASSERT(!vmlaunch());
+	GUEST_ASSERT(false);
+}
#19 lore raw

Re: [PATCH v4 11/12] KVM: selftests: Support running stress save+restore and #PF test in L2

Quoted 61 lines · Sean Christopherson
Quoted 36 lines · Yosry Ahmed

Extend the stress test to allow running the access+#PF code in L2 instead of L1 by adding proper L1 guest code to bootstrap L2. By default, the test runs in L2 after running in L1 if nested is supported.

Assisted-by Gemini:gemini-3.1-pro
---
 .../kvm/x86/save_restore_pf_stress_test.c     | 61 ++++++++++++++++++-
 1 file changed, 58 insertions(+), 3 deletions(-)
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +7 -0
index 664ed280b2e76..0e5ddeb5af444 100644
@@ -8,10 +8,13 @@
 #include <pthread.h>
 #include <signal.h>
 #include <unistd.h>
+#include <getopt.h>
 
 #include "test_util.h"
 #include "kvm_util.h"
 #include "processor.h"
+#include "svm_util.h"
+#include "vmx.h"
 
 #define NR_ITERATIONS                500
 
@@ -81,6 +84,36 @@ static void guest_access_memory(void *arg)
      }
 }
 
+static void l1_svm_code(struct svm_test_data *svm)
+{
+     generic_svm_setup(svm, guest_access_memory);
+     run_guest(svm->vmcb, svm->vmcb_gpa);

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c static void guest_access_memory(void *arg) · line 100

Quoted 10 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +10 -0
+     GUEST_ASSERT(false);
+}
+
+static void l1_vmx_code(struct vmx_pages *vmx)
+{
+     GUEST_ASSERT(prepare_for_vmx_operation(vmx));
+     GUEST_ASSERT(load_vmcs(vmx));
+     prepare_vmcs(vmx, guest_access_memory);
+
+     /* Ignore any #PF */

This comment is rather ambiguous, especially when the #UD interception comes along, because unless the reader is reading carefully and sees the PFEC_MASK and PFEC_MATCH logic below, it's quite easy to read this as "intercept #PF to ignore them".

I don't see any reason to write the code this way. Yeah yeah, it's the SDM's suggested way to ignore #PFs, but IMO that's unnecessarily convoluted. The more obvious way is to leave all fields '0'.

In other words, just delete this entire block of code and rely on the default VMX allocation logic to disable interception of all exceptions.

Quoted 8 lines

Oh, damnit. Argh. I see why you need this. init_vmcs_control_fields() is buggy and actually configures #PF for interception. Apparently Paolo didn't read the "If there is inequality, the meaning of that bit is reversed (for example, a VM exit occurs if that bit is clear)." part :-D

So, let's fix that in a prep patch (AFAICT, no existing tests cares about #PF interception) so that this test doesn't have to carry confusing code, and because intercpeting #PF but nothing else by default is bound to cause problems.

Yeah that felt weird, but the comment "Never match" made it feel like it was intentional. Anyway, I just sent v5 with your diff below as a patch, thanks!

Quoted 22 lines
testing/selftests/kvm/lib/x86/vmx.c +1 -1
index cd09c9de4485..089e1a8af53f 100644
@@ -232,7 +232,7 @@ static inline void init_vmcs_control_fields(struct vmx_pages *vmx)
 
        vmwrite(EXCEPTION_BITMAP, 0);
        vmwrite(PAGE_FAULT_ERROR_CODE_MASK, 0);
-       vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, -1); /* Never match */
+       vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, 0);
        vmwrite(CR3_TARGET_COUNT, 0);
        vmwrite(VM_EXIT_CONTROLS, rdmsr(MSR_IA32_VMX_EXIT_CTLS) |
                VM_EXIT_HOST_ADDR_SPACE_SIZE);    /* 64-bit host */
Quoted 8 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +7 -0
+     GUEST_ASSERT(!vmwrite(EXCEPTION_BITMAP, BIT(PF_VECTOR)));
+     GUEST_ASSERT(!vmwrite(PAGE_FAULT_ERROR_CODE_MASK, 0));
+     GUEST_ASSERT(!vmwrite(PAGE_FAULT_ERROR_CODE_MATCH, -1));
+
+     GUEST_ASSERT(!vmlaunch());
+     GUEST_ASSERT(false);
+}
#20 lore raw

PATCH v4 12/12 KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test

In reply to Yosry Ahmed

Extend the testing coverage in L2 by forcing a nested VM-Exit from L2 to L1 right after restore on every other iteration. Forcing a nested VM-Exit while L0 has control (e.g. without explicitly running L2 and making a hypercall) is valuable, as it often happens during live migration (e.g. L1 timer interrupt fires by the time the VM lands on the destination).

To force the nested VM-Exit inject a #UD in to the saved vCPU state, and intercept #UD from L1.

With this change, the test reliably reproduces the CR2 bug fixed by commit 5c247d08bc81 ("KVM: nSVM: Use vcpu->arch.cr2 when updating vmcb12 on nested #VMEXIT") -- at least on Milan, Genoa, and Turin CPUs.

Assisted-by Gemini:gemini-3.1-pro
---
 .../selftests/kvm/include/x86/processor.h     |  5 +++
 .../kvm/x86/save_restore_pf_stress_test.c     | 45 ++++++++++++++++---
 2 files changed, 44 insertions(+), 6 deletions(-)
tools/testing/selftests/kvm/include/x86/processor.h +5 -0
index 2889782b0016b..461c8aef7d37b 100644
@@ -959,6 +959,11 @@ struct kvm_x86_state *vcpu_save_state(struct kvm_vcpu *vcpu);
 void vcpu_load_state(struct kvm_vcpu *vcpu, struct kvm_x86_state *state);
 void kvm_x86_state_cleanup(struct kvm_x86_state *state);
 
+static inline bool kvm_x86_state_is_guest_mode(struct kvm_x86_state *state)
+{
+	return state->nested.size && (state->nested.flags & KVM_STATE_NESTED_GUEST_MODE);
+}
+
 const struct kvm_msr_list *kvm_get_msr_index_list(void);
 const struct kvm_msr_list *kvm_get_feature_msr_index_list(void);
 bool kvm_msr_is_in_save_restore_list(u32 msr_index);
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +39 -6

87 lines not on this page · raw message

Signature · 1 line
2.55.0.229.g6434b31f56-goog
#21 lore raw

Re: [PATCH v4 12/12] KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The test unconditionally enables `KVM_CAP_EXCEPTION_PAYLOAD` in `run_test()`, causing the test…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The test unconditionally enables KVM_CAP_EXCEPTION_PAYLOAD in run_test(), causing the test to crash on older kernels before reaching the capability check in main(). --

--- Patch [12]: [PATCH v4 12/12] KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test --- commit 30592840747b18628e46af30e613a95b722da3cc
Author: Yosry Ahmed <[email protected]>

KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test

This commit extends the testing coverage in L2 by forcing a nested VM-Exit from L2 to L1 right after restore on every other iteration. To force the nested VM-Exit, it injects a #UD into the saved vCPU state and intercepts #UD from L1.

Quoted 4 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +0 -0
index 0e5ddeb5af444..ba1d723001e94 100644

[ ... ]

Quoted 8 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +1 -0
@@ -156,6 +178,7 @@ static void run_test(bool nested)
 
 	vm = vm_create_with_one_vcpu(&vcpu, nested ? l1_guest_code : guest_access_memory);
 	vm_install_exception_handler(vm, PF_VECTOR, guest_pf_handler);
+	vm_enable_cap(vm, KVM_CAP_EXCEPTION_PAYLOAD, -2ul);
 
 	if (nested) {
 		if (kvm_cpu_has(X86_FEATURE_SVM))

[ ... ]

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c int main(int argc, char *argv[]) · line 283

Quoted 8 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +3 -1
@@ -247,7 +278,9 @@ int main(int argc, char *argv[])
 	pr_info("Running save+restore stress test...\n");
 	run_test(/*nested=*/false);
 
-	if (!kvm_cpu_has(X86_FEATURE_SVM) && !kvm_cpu_has(X86_FEATURE_VMX)) {
+	if (!kvm_has_cap(KVM_CAP_EXCEPTION_PAYLOAD) ||
+	    !kvm_has_cap(KVM_CAP_NESTED_STATE) ||
+	    (!kvm_cpu_has(X86_FEATURE_SVM) && !kvm_cpu_has(X86_FEATURE_VMX))) {

[Severity: Medium]
Will this test crash on older kernels that lack KVM_CAP_EXCEPTION_PAYLOAD?

Because run_test(false) is called before this capability check in main(), run_test() will unconditionally call vm_enable_cap() for KVM_CAP_EXCEPTION_PAYLOAD.

Could this prevent the test from gracefully skipping on environments without this capability?

Quoted 3 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +0 -0
 		pr_info("Nested virtualization not supported, skipping nested test\n");
 		return 0;
 	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#22 lore raw

Re: [PATCH v4 12/12] KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test

Quoted 42 lines · On Mon, Jul 27, 2026 at 5:09 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The test unconditionally enables KVM_CAP_EXCEPTION_PAYLOAD in run_test(), causing the test to crash on older kernels before reaching the capability check in main(). --

--- Patch [12]: [PATCH v4 12/12] KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test --- commit 30592840747b18628e46af30e613a95b722da3cc
Author: Yosry Ahmed <[email protected]>

KVM: selftests: Trigger L2->L1 exits stress save+restore and #PF test

This commit extends the testing coverage in L2 by forcing a nested VM-Exit from L2 to L1 right after restore on every other iteration. To force the nested VM-Exit, it injects a #UD into the saved vCPU state and intercepts #UD from L1.

Quoted 4 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +0 -0
index 0e5ddeb5af444..ba1d723001e94 100644

[ ... ]

Quoted 8 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +1 -0
@@ -156,6 +178,7 @@ static void run_test(bool nested)
 
      vm = vm_create_with_one_vcpu(&vcpu, nested ? l1_guest_code : guest_access_memory);
      vm_install_exception_handler(vm, PF_VECTOR, guest_pf_handler);
+     vm_enable_cap(vm, KVM_CAP_EXCEPTION_PAYLOAD, -2ul);
 
      if (nested) {
              if (kvm_cpu_has(X86_FEATURE_SVM))

[ ... ]

tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c int main(int argc, char *argv[]) · line 283

Quoted 8 lines
tools/testing/selftests/kvm/x86/save_restore_pf_stress_test.c +3 -1
@@ -247,7 +278,9 @@ int main(int argc, char *argv[])
      pr_info("Running save+restore stress test...\n");
      run_test(/*nested=*/false);
 
-     if (!kvm_cpu_has(X86_FEATURE_SVM) && !kvm_cpu_has(X86_FEATURE_VMX)) {
+     if (!kvm_has_cap(KVM_CAP_EXCEPTION_PAYLOAD) ||
+         !kvm_has_cap(KVM_CAP_NESTED_STATE) ||
+         (!kvm_cpu_has(X86_FEATURE_SVM) && !kvm_cpu_has(X86_FEATURE_VMX))) {

[Severity: Medium]
Will this test crash on older kernels that lack KVM_CAP_EXCEPTION_PAYLOAD?

Quoted 6 lines

Because run_test(false) is called before this capability check in main(), run_test() will unconditionally call vm_enable_cap() for KVM_CAP_EXCEPTION_PAYLOAD.

Could this prevent the test from gracefully skipping on environments without this capability?

Oh I missed this. Yeah we need to make enabling the CAP conditional on nested=true.

#23 lore raw
In reply to Yosry Ahmed
Quoted 6 lines · Yosry Ahmed

Add a stress test for save+restore while the guest is triggering and handling #PFs, in both L1 and L2. The goal was to create a generic selftest that would catch bugs like the one fixed by commit 5c247d08bc81 ("KVM: nSVM: Use vcpu->arch.cr2 when updating vmcb12 on nested #VMEXIT"), instead of relying on high-level testing (e.g. building GCC in L2) to catch it.

LGTM, but there are juuuust enough nits that it'd be easier for me if you send a v5.

Thanks!