[Devel] [PATCH hci-8.1 02/14] ms/KVM: x86: Conditionally resched when restarting REP string emulation

Konstantin Khorenko khorenko at virtuozzo.com
Thu Nov 26 17:30:15 MSK 2026


From: Sean Christopherson <seanjc at google.com>

[ Upstream commit ae85ac25eb671d174811cc3101549448671fd505 ]

When restarting emulation, e.g. of a REP-prefixed string instruction,
conditionally reschedule as emulating guest writes can be deceptively slow
and expensive, e.g. when shadow paging is in use and each write can trigger
write tracking.

In a perfect world, restarting emulation (or not) would be less arbitrary,
e.g. would honor not only host events (NEED_RESCHED, signals, etc.) but
also guest events (e.g. by checking kvm_vcpu_has_events()).  Unfortunately,
as pointed out by Sashiko, pio_in_emulated()'s read-ahead logic is baked
into the restart logic, as KVM relies on restarting emulation to drain the
cache and avoid duplicate reads from the I/O port.  I.e. re-entering the
guest on kvm_vcpu_has_events() or __xfer_to_guest_mode_work_pending() would
introduce architecturally-incorrect, guest-visible changes.

Fixes: 5cd21917da24 ("KVM: x86 emulator: restart string instruction without going back to a guest.")
Cc: stable at vger.kernel.org
Cc: David Woodhouse <dwmw2 at infradead.org>
Reported-by: Stefan Teodorescu <fane at google.com>
Suggested-by: Stefan Teodorescu <fane at google.com>
Signed-off-by: Sean Christopherson <seanjc at google.com>
Message-ID: <20261028173638.1765329-1-seanjc at google.com>
Signed-off-by: Paolo Bonzini <pbonzini at redhat.com>
Signed-off-by: Sasha Levin <sashal at kernel.org>
(cherry picked from commit c1293d2134c2d63741b197a1e5a6363894ed4bce)

https://virtuozzo.atlassian.net/browse/VSTOR-157287
Feature: fix ms/kvm
Signed-off-by: Konstantin Khorenko <khorenko at virtuozzo.com>
---
 arch/x86/kvm/x86.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index de38b59d90161..e0f575bc67f47 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -9252,10 +9252,12 @@ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 	} else if (vcpu->arch.complete_userspace_io) {
 		writeback = false;
 		r = 0;
-	} else if (r == EMULATION_RESTART)
+	} else if (r == EMULATION_RESTART) {
+		cond_resched();
 		goto restart;
-	else
+	} else {
 		r = 1;
+	}
 
 writeback:
 	if (writeback) {

-- 
2.43.0



More information about the Devel mailing list