git: 919ec3e939db - main - vmm: Avoid redundant AMD DEBUGCTL writes

From: Hayzam Sherif <hayzam_at_FreeBSD.org>
Date: Tue, 17 Nov 2026 21:38:50 UTC
The branch main has been updated by hayzam:

URL: https://cgit.FreeBSD.org/src/commit/?id=919ec3e939db71a6fc0d4ef5d72a9c3007a5c929

commit 919ec3e939db71a6fc0d4ef5d72a9c3007a5c929
Author:     Hayzam Sherif <hayzam@FreeBSD.org>
AuthorDate: 2026-11-17 21:36:40 +0000
Commit:     Hayzam Sherif <hayzam@FreeBSD.org>
CommitDate: 2026-11-17 21:36:40 +0000

    vmm: Avoid redundant AMD DEBUGCTL writes
    
    Skip clearing and restoring DEBUGCTL when the saved host value is
    zero. The entry path leaves DEBUGCTL zero, and LBR virtualization
    restores that host value on VM exit. A rejected guest entry also
    returns with the pre-VMRUN DEBUGCTL value. Guest accesses to DEBUGCTL
    remain intercepted.
    
    Preserve the existing writes for nonzero host state. Avoiding the
    redundant writes can also avoid intercepted MSR accesses when bhyve
    runs under another hypervisor.
    
    Reviewed by:    markj, bnovkov
    Approved by:    markj (mentor)
    Sponsored by:   Alchemilla Ventures Private Limited
    MFC after:      2 weeks
    Differential Revision:  https://reviews.freebsd.org/D61218
---
 sys/amd64/vmm/amd/svm.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/sys/amd64/vmm/amd/svm.c b/sys/amd64/vmm/amd/svm.c
index 37c950cfbc5f..2ac84e36aa5a 100644
--- a/sys/amd64/vmm/amd/svm.c
+++ b/sys/amd64/vmm/amd/svm.c
@@ -2079,7 +2079,8 @@ svm_dr_enter_guest(struct svm_regctx *gctx)
 	 * VMCB.
 	 */
 	load_dr7(0);
-	wrmsr(MSR_DEBUGCTLMSR, 0);
+	if (gctx->host_debugctl != 0)
+		wrmsr(MSR_DEBUGCTLMSR, 0);
 
 	/* Save host debug registers. */
 	gctx->host_dr0 = rdr0();
@@ -2114,7 +2115,12 @@ svm_dr_leave_guest(struct svm_regctx *gctx)
 	load_dr2(gctx->host_dr2);
 	load_dr3(gctx->host_dr3);
 	load_dr6(gctx->host_dr6);
-	wrmsr(MSR_DEBUGCTLMSR, gctx->host_debugctl);
+	/*
+	 * LBR virtualization restores the zero DEBUGCTL value used at VMRUN.
+	 * Only a nonzero original host value needs restoring here.
+	 */
+	if (gctx->host_debugctl != 0)
+		wrmsr(MSR_DEBUGCTLMSR, gctx->host_debugctl);
 	load_dr7(gctx->host_dr7);
 }