* [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept
@ 2026-11-27 15:27 David Woodhouse
2026-11-27 15:27 ` [PATCH v3 01/15] KVM: selftests: Make the x86 SSE register helpers volatile David Woodhouse
` (14 more replies)
0 siblings, 15 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Add KVM_CAP_HYPERV_FORWARD_HCALL. As with KVM_CAP_XEN_HVM and
KVM_CAP_EXIT_HYPERCALL, KVM_CHECK_EXTENSION returns a bitmask of
features and KVM_ENABLE_CAP takes the subset to enable. The first
feature, KVM_HYPERV_HCALL_FORWARD_UNKNOWN, surfaces unknown hypercalls
to userspace through the existing KVM_EXIT_HYPERV_HCALL exit.
A second feature, KVM_HYPERV_HCALL_RET, allows userspace to choose
whether/how the kernel should complete the hypercall, populating a
'ret' field with one of:
KVM_INSN_COMPLETE finish the instruction, as now
KVM_INSN_GP inject #GP(0) at it
KVM_INSN_UD inject #UD at it
KVM_INSN_RESUME do nothing; resume the guest as userspace left it
Hyper-V needs to do this in some cases, for example HvCallVtlCall and
HvCallVtlReturn are supposed to raise #UD when they are refused.
Further features will follow for HvCallVtlCall and HvCallVtlReturn on
VMs with planes, so that KVM can handle VTL transitions in the kernel.
Also add KVM_CAP_X86_REG_WRITE_FILTER for trapping control register
writes (CR0, CR4, XCR0, IDTR, LDTR, etc.).
Add KVM_CAP_X86_MSR_EXIT_INSN to allow MSR exits to gain the same
ability to COMPLETE/GP/UD/RESUME so that they can be handled by
another plane too. The existing 'error' field was already a u8 there,
so userspace can just opt in to using the new KVM_INSN_xxx values in
place of the existing 'non-zero means #GP' behaviour.
The VMware hypercall series¹ needs to fault its instruction too, and
with more than #GP. As posted, it has its exit carry a vector, an
error code and a fault address for KVM to inject. It can use the same
model, and the complex faults can be injected with KVM_SET_VCPU_EVENTS
followed by a ret of KVM_INSN_RESUME.
The completion result code deliberately does not cover:
- PIO and MMIO. Those completions carry state which can't just be
dropped, and VSM has no use for it: what a higher VTL intercepts
there is the memory access, which faults before the instruction has
done anything.
- Guests with protected state. There is no instruction for KVM to
leave alone, so MSR exits keep today's meaning (any non-zero value
fails the access), a Hyper-V hypercall always completes, and a
register write filter cannot be armed. Nor can one be armed for a
plain SEV guest, whose instructions KVM cannot decode.
- KVM_EXIT_HYPERCALL, KVM_EXIT_XEN and KVM_EXIT_TDX, which are
untouched.
On an Intel Xeon 6 (itself a KVM guest, so VMX there is nested), on the
series as posted, the three new tests and hyperv_forward_hcall pass, as
do userspace_msr_exit_test, msrs_test, hyperv_features,
hyperv_extended_hypercalls, set_sregs_test, cr4_cpuid_sync_test,
xcr0_cpuid_test, smm_test and state_test: 13 of 13. The three with
emulator legs (msr_exit_insn_test, userspace_msr_exit_test and
reg_write_filter_test) pass again with kvm.force_emulation_prefix=1, as
do hyperv_forward_hcall and nested_reg_write_filter_test.
On a bare-metal AMD EPYC 9R14 (Zen 4), also on the series as posted,
the same 13 pass, and the same five again with
kvm.force_emulation_prefix=1. The three new tests also pass with
kvm_amd nrips=0, with and without forced emulation; there the
instruction lengths come from the emulator.
An earlier revision of these patches is at the base of the full VSM
tree², on which Windows Server 2025 boots with VBS and Credential
Guard, through the hypercall and register write exits.
One open question, on patch 7. It reports
HV_X64_HYPERCALL_XMM_OUTPUT_AVAILABLE unconditionally, as it did in
v2, although only a VMM which handles forwarded hypercalls can honour
it. I wonder if it should only be reported once the VMM has opted in,
perhaps just tied to KVM_HYPERV_HCALL_FORWARD_UNKNOWN. I've left it as
it is for now.
Based on v7.4-rc2. Also at:
https://git.infradead.org/users/dwmw2/linux.git/shortlog/refs/heads/exit-insn
Changes since v2³ of the hypercall forwarding series, which is patches
5-8 here. Everything else is new.
- Drop KVM_VCPUEVENT_CANCEL_HCALL and the KVM_CAP_VCPU_EVENTS feature
mask; the exit takes KVM_INSN_* in a 'ret' field instead (Sean⁴)
- Drop vcpu_events_cancel_test; hyperv_forward_hcall covers 'ret'
- Document that the feature mask only uses bits 0 to 30, and enforce
it at build time
- No allowlist of forwarded hypercalls. As discussed in the v2 thread⁵
the capability is needed either way, and anything KVM learns to
handle later has to be a new bit in its mask, so that a VMM which
forwards that hypercall today keeps receiving it
- The fix to the XMM helpers which Sashiko's review of the selftest
led to⁶ is patch 1 here, now with a Fixes: tag
¹ https://lore.kernel.org/kvm/cover.1794374897.git.zack.rusin@broadcom.com/
² https://git.infradead.org/users/dwmw2/linux.git/shortlog/refs/heads/vsm3w/p4-startup
³ https://lore.kernel.org/kvm/20261113170535.79246-1-dwmw2@infradead.org/
⁴ https://lore.kernel.org/kvm/avuDUNAU_a933zvp@seanjc-mac.roam.internal/
⁵ https://lore.kernel.org/kvm/awCNTITOOiS1JEod@seanjc-mac.roam.internal/
⁶ https://lore.kernel.org/kvm/20261113181053.81779-1-dwmw2@infradead.org/
David Woodhouse (15):
KVM: selftests: Make the x86 SSE register helpers volatile
KVM: Define what completing an exit does with its instruction
KVM: x86: Let userspace leave an MSR access alone
KVM: selftests: Test MSR accesses which userspace leaves alone
KVM: x86: hyper-v: Add KVM_CAP_HYPERV_FORWARD_HCALL
KVM: x86: hyper-v: Let userspace leave a hypercall uncompleted
KVM: x86: hyper-v: Advertise XMM fast hypercall output
KVM: selftests: Add Hyper-V hypercall forwarding test
KVM: x86: Add a per-vCPU register write filter
KVM: x86: Filter emulated CR0 and CR4 writes
KVM: VMX: Support CR0 and CR4 write filters
KVM: SVM: Support CR0 and CR4 write filters
KVM: x86: Add descriptor-table registers to the write filter
KVM: selftests: Add x86 register write filter test
KVM: selftests: Test the register write filter with a nested guest
Documentation/virt/kvm/api.rst | 302 ++++-
arch/x86/include/asm/kvm-x86-ops.h | 1 +
arch/x86/include/asm/kvm_host.h | 23 +
arch/x86/include/uapi/asm/kvm.h | 17 +
arch/x86/kvm/emulate.c | 54 +-
arch/x86/kvm/hyperv.c | 28 +-
arch/x86/kvm/hyperv.h | 9 +
arch/x86/kvm/kvm_emulate.h | 28 +
arch/x86/kvm/msrs.c | 75 +-
arch/x86/kvm/regs.h | 43 +
arch/x86/kvm/svm/nested.c | 16 +
arch/x86/kvm/svm/sev.c | 22 +
arch/x86/kvm/svm/svm.c | 138 ++-
arch/x86/kvm/vmx/main.c | 13 +
arch/x86/kvm/vmx/nested.c | 27 +-
arch/x86/kvm/vmx/vmx.c | 167 ++-
arch/x86/kvm/vmx/vmx.h | 14 +-
arch/x86/kvm/vmx/x86_ops.h | 1 +
arch/x86/kvm/x86.c | 343 +++++-
arch/x86/kvm/x86.h | 34 +-
include/uapi/linux/kvm.h | 35 +-
tools/testing/selftests/kvm/Makefile.kvm | 4 +
.../selftests/kvm/include/x86/processor.h | 33 +-
tools/testing/selftests/kvm/lib/kvm_util.c | 1 +
.../selftests/kvm/x86/hyperv_forward_hcall.c | 395 +++++++
.../selftests/kvm/x86/msr_exit_insn_test.c | 308 +++++
.../kvm/x86/nested_reg_write_filter_test.c | 362 ++++++
.../selftests/kvm/x86/reg_write_filter_test.c | 1004 +++++++++++++++++
28 files changed, 3437 insertions(+), 60 deletions(-)
create mode 100644 tools/testing/selftests/kvm/x86/hyperv_forward_hcall.c
create mode 100644 tools/testing/selftests/kvm/x86/msr_exit_insn_test.c
create mode 100644 tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c
create mode 100644 tools/testing/selftests/kvm/x86/reg_write_filter_test.c
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
--
2.50.1
^ permalink raw reply [flat|nested] 21+ messages in thread
* [PATCH v3 01/15] KVM: selftests: Make the x86 SSE register helpers volatile
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 02/15] KVM: Define what completing an exit does with its instruction David Woodhouse
` (13 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
read_sse_reg() and write_sse_reg() were borrowed from KVM's
_kvm_read_sse_reg() and _kvm_write_sse_reg(). The kernel is built
without SSE, so the compiler never uses the XMM registers itself and a
plain asm() is enough there. Selftest guest code is built with SSE, and
there the asm statements have to tell the compiler what they do.
read_sse_reg() has an output and is not volatile, so the compiler may
treat it as a pure computation and move it, for example ahead of the
hypercall whose XMM output it is meant to read. write_sse_reg() has no
outputs and is therefore implicitly volatile, but it doesn't declare the
register it overwrites, so a value the compiler was keeping there does
not survive.
Mark both volatile, and declare the register each write_sse_reg() case
writes as clobbered. A read_sse_reg() after __hyperv_hypercall() now
stays after it.
That still leaves the compiler free to use an XMM register for its own
code between a write_sse_reg() and the asm which consumes it.
hyperv_write_xmm_input() in the hyperv_ipi and hyperv_tlb_flush tests
relies on that not happening; GCC 11.5 at -O2 emits nothing there.
Closing that window entirely would mean passing the XMM values as
operands of the hypercall asm itself.
Fixes: 676a863ce605 ("KVM: selftests: Better XMM read/write helpers")
Reported-by: Sashiko <sashiko-bot@kernel.org>
Closes: https://lore.kernel.org/all/sashiko-outbox-209724@kernel.org/
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
.../selftests/kvm/include/x86/processor.h | 32 +++++++++----------
1 file changed, 16 insertions(+), 16 deletions(-)
diff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/testing/selftests/kvm/include/x86/processor.h
index 5898a277a2e0..571f8a602edd 100644
--- a/tools/testing/selftests/kvm/include/x86/processor.h
+++ b/tools/testing/selftests/kvm/include/x86/processor.h
@@ -866,28 +866,28 @@ static inline void read_sse_reg(int reg, sse128_t *data)
{
switch (reg) {
case 0:
- asm("movdqa %%xmm0, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm0, %0" : "=m"(*data));
break;
case 1:
- asm("movdqa %%xmm1, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm1, %0" : "=m"(*data));
break;
case 2:
- asm("movdqa %%xmm2, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm2, %0" : "=m"(*data));
break;
case 3:
- asm("movdqa %%xmm3, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm3, %0" : "=m"(*data));
break;
case 4:
- asm("movdqa %%xmm4, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm4, %0" : "=m"(*data));
break;
case 5:
- asm("movdqa %%xmm5, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm5, %0" : "=m"(*data));
break;
case 6:
- asm("movdqa %%xmm6, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm6, %0" : "=m"(*data));
break;
case 7:
- asm("movdqa %%xmm7, %0" : "=m"(*data));
+ asm volatile("movdqa %%xmm7, %0" : "=m"(*data));
break;
default:
BUG();
@@ -898,28 +898,28 @@ static inline void write_sse_reg(int reg, const sse128_t *data)
{
switch (reg) {
case 0:
- asm("movdqa %0, %%xmm0" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm0" : : "m"(*data) : "xmm0");
break;
case 1:
- asm("movdqa %0, %%xmm1" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm1" : : "m"(*data) : "xmm1");
break;
case 2:
- asm("movdqa %0, %%xmm2" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm2" : : "m"(*data) : "xmm2");
break;
case 3:
- asm("movdqa %0, %%xmm3" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm3" : : "m"(*data) : "xmm3");
break;
case 4:
- asm("movdqa %0, %%xmm4" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm4" : : "m"(*data) : "xmm4");
break;
case 5:
- asm("movdqa %0, %%xmm5" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm5" : : "m"(*data) : "xmm5");
break;
case 6:
- asm("movdqa %0, %%xmm6" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm6" : : "m"(*data) : "xmm6");
break;
case 7:
- asm("movdqa %0, %%xmm7" : : "m"(*data));
+ asm volatile("movdqa %0, %%xmm7" : : "m"(*data) : "xmm7");
break;
default:
BUG();
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 02/15] KVM: Define what completing an exit does with its instruction
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
2026-11-27 15:27 ` [PATCH v3 01/15] KVM: selftests: Make the x86 SSE register helpers volatile David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:55 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 03/15] KVM: x86: Let userspace leave an MSR access alone David Woodhouse
` (12 subsequent siblings)
14 siblings, 1 reply; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
The KVM_RUN after an exit which left an instruction to complete retires
that instruction. Only MSR exits offer anything else: their 'error'
byte asks for #GP instead.
Define one set of values for such exits: complete the instruction,
inject #GP or #UD at it, or do nothing and resume the guest as
userspace left it. Add the x86 helper which acts on them; a guest with
protected state can only have the instruction completed. No exit takes
them yet.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 50 ++++++++++++++++++++++++++++++++++
arch/x86/kvm/x86.h | 32 ++++++++++++++++++++++
include/uapi/linux/kvm.h | 9 ++++++
3 files changed, 91 insertions(+)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index e95c9cda085d..d15dddd79e5b 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -6976,6 +6976,56 @@ to the byte array.
to complete pending operations without allowing any further instructions
to be executed.
+.. _kvm_insn_action:
+
+Some exits which need completion let userspace choose what the
+completion does with the guest instruction that caused the exit. Their
+descriptions say which field takes the choice, and when. The values are
+the same for all of them::
+
+ #define KVM_INSN_COMPLETE 0
+ #define KVM_INSN_GP 1
+ #define KVM_INSN_UD 2
+ #define KVM_INSN_RESUME 3
+
+KVM_INSN_COMPLETE
+ The instruction completes: KVM writes its result, if it has one, and
+ retires it, i.e. moves RIP past it, clears RFLAGS.RF and the interrupt
+ shadow, and honours single-stepping. KVM sets the field to this. RIP
+ must still point at the instruction, and RFLAGS be as the exit left
+ it: userspace which changes either retires the instruction itself,
+ with KVM_INSN_RESUME.
+
+KVM_INSN_GP, KVM_INSN_UD
+ The instruction faults: KVM injects #GP with a zero error code, or
+ #UD, and RIP stays at the instruction. Every exit which takes these
+ values takes both; userspace chooses the one which the CPU would raise
+ for the instruction.
+
+KVM_INSN_RESUME
+ KVM does nothing for the instruction. It writes no result and injects
+ nothing, and the guest resumes from its state as userspace left it.
+ The instruction has not retired, so the interrupt shadow and RFLAGS.RF
+ stay as they are and no single-step trap is raised, neither a #DB for
+ the guest nor KVM_EXIT_DEBUG. What the guest sees is up to userspace:
+
+ - with an exception queued by KVM_SET_VCPU_EVENTS, the guest takes the
+ exception at the instruction;
+ - with RIP moved, the guest continues from there: userspace has
+ retired the instruction itself and owns everything that goes with
+ that;
+ - with nothing changed, the guest executes the instruction again and
+ KVM_RUN returns with the same exit.
+
+Any other value is reserved: KVM_RUN fails with -EINVAL, and the guest
+is left as for KVM_INSN_RESUME.
+
+A guest whose register state is protected (SEV-ES, SEV-SNP, TDX) does
+not execute the instruction again, and KVM cannot inject #UD into it.
+KVM can only complete the exit there, with whatever outcome the exit
+itself has, and the description of each exit says what it makes of
+another value.
+
::
/* KVM_EXIT_HYPERCALL */
diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h
index 436e2fb1396c..7e5ccbce9114 100644
--- a/arch/x86/kvm/x86.h
+++ b/arch/x86/kvm/x86.h
@@ -526,6 +526,38 @@ static inline void kvm_inject_gp(struct kvm_vcpu *vcpu, u32 error_code)
kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
}
+/*
+ * Act on the KVM_INSN_* answer which userspace gave to an exit that left an
+ * instruction to complete. Returns 0 if the caller is to complete the
+ * instruction, 1 if there is nothing more to do for it, or -EINVAL.
+ *
+ * A guest whose state is protected does not execute the instruction again,
+ * and KVM cannot inject #UD into it: all that can be done there is to
+ * complete the exit, with an outcome which is the caller's to choose from
+ * the answer, or to ignore it.
+ */
+static inline int kvm_insn_uncompleted(struct kvm_vcpu *vcpu, u8 answer)
+{
+ if (vcpu->kvm->arch.has_protected_state ||
+ vcpu->arch.guest_state_protected)
+ return 0;
+
+ switch (answer) {
+ case KVM_INSN_COMPLETE:
+ return 0;
+ case KVM_INSN_GP:
+ kvm_inject_gp(vcpu, 0);
+ return 1;
+ case KVM_INSN_UD:
+ kvm_queue_exception(vcpu, UD_VECTOR);
+ return 1;
+ case KVM_INSN_RESUME:
+ return 1;
+ default:
+ return -EINVAL;
+ }
+}
+
void kvm_inject_nmi(struct kvm_vcpu *vcpu);
int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu);
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 8dff2fc1972e..0a4c548cb329 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -220,6 +220,15 @@ struct kvm_exit_snp_req_certs {
#define HINT_UNSAFE_IN_KVM(_symbol) _symbol
#endif
+/*
+ * What the next KVM_RUN does with the instruction which an exit left to be
+ * completed, for the exits whose description says that they take one.
+ */
+#define KVM_INSN_COMPLETE 0 /* retire it, with its result if any */
+#define KVM_INSN_GP 1 /* inject #GP(0) at it */
+#define KVM_INSN_UD 2 /* inject #UD at it */
+#define KVM_INSN_RESUME 3 /* nothing: resume the guest as it is */
+
/* for KVM_RUN, returned by mmap(vcpu_fd, offset=0) */
struct kvm_run {
/* in */
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 03/15] KVM: x86: Let userspace leave an MSR access alone
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
2026-11-27 15:27 ` [PATCH v3 01/15] KVM: selftests: Make the x86 SSE register helpers volatile David Woodhouse
2026-11-27 15:27 ` [PATCH v3 02/15] KVM: Define what completing an exit does with its instruction David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 04/15] KVM: selftests: Test MSR accesses which userspace leaves alone David Woodhouse
` (11 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
A VMM completing KVM_EXIT_X86_RDMSR or KVM_EXIT_X86_WRMSR can only have
KVM retire the instruction or inject #GP. It cannot raise another
exception, or hand the access to something which retires it later.
With KVM_CAP_X86_MSR_EXIT_INSN, 'error' takes KVM_INSN_*: zero and one
mean what they did, KVM_INSN_UD injects #UD and KVM_INSN_RESUME makes
KVM do nothing. Other values fail KVM_RUN.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 34 ++++++++++++++-
arch/x86/include/asm/kvm_host.h | 2 +
arch/x86/kvm/msrs.c | 75 ++++++++++++++++++++++++++-------
arch/x86/kvm/x86.c | 8 ++++
include/uapi/linux/kvm.h | 3 +-
5 files changed, 105 insertions(+), 17 deletions(-)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index d15dddd79e5b..6d4a11ce368c 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -7441,7 +7441,7 @@ non-zero value, indicating that FEAT_LS64* is enabled.
/* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
struct {
- __u8 error; /* user -> kernel */
+ __u8 error; /* in: KVM_INSN_* */
__u8 pad[7];
__u32 reason; /* kernel -> user */
__u32 index; /* kernel -> user */
@@ -7477,6 +7477,17 @@ wants to write. Once finished processing the event, userspace must continue
vCPU execution. If the MSR write was unsuccessful, userspace also sets the
"error" field to "1".
+Any non-zero "error" injects the #GP, unless KVM_CAP_X86_MSR_EXIT_INSN
+is enabled. "error" then takes one of the KVM_INSN_* values (see
+:ref:`the description of completion <kvm_insn_action>`), of which zero
+and one are the success and the #GP described above. KVM_INSN_UD
+injects #UD instead, and KVM_INSN_RESUME tells KVM to do nothing for the
+access: "data" is ignored, no register is written, nothing is injected
+and RIP is left alone. For a guest whose register state is protected
+(SEV-ES, SEV-SNP and TDX, a debuggable TD included) KVM can neither
+leave the access unanswered nor inject #UD, and every non-zero value
+fails the access like KVM_INSN_GP, with or without the capability.
+
See KVM_X86_SET_MSR_FILTER for details on the interaction with MSR filtering.
::
@@ -9231,6 +9242,27 @@ enabled, cmma can't be enabled anymore and pfmfi and the storage key
interpretation are disabled. If cmma has already been enabled or the
hpage_2g module parameter is not set to 1, -EINVAL is returned.
+7.48 KVM_CAP_X86_MSR_EXIT_INSN
+------------------------------
+
+:Architectures: x86
+:Target: VM
+:Parameters: args[0] is 1 to enable, 0 to disable
+:Returns: 0 on success, -EINVAL if args[0] is any other value
+
+With this capability enabled, the "error" field of every
+KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR exit takes a KVM_INSN_* value,
+whichever of the KVM_MSR_EXIT_REASON_* reasons caused the exit.
+KVM_INSN_UD, and KVM_INSN_RESUME, which leaves the access for userspace
+to resolve, become available, and other values fail KVM_RUN with -EINVAL
+instead of injecting #GP. It is disabled by default because existing
+VMMs may pass any non-zero value for a failed access. The capability
+has no effect on which accesses exit; that is still selected with
+KVM_CAP_X86_USER_SPACE_MSR and KVM_X86_SET_MSR_FILTER.
+
+A guest whose register state is protected is the exception: see the
+description of those exits.
+
8. Other capabilities.
======================
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 1ee4b127004d..0e8150116e20 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1297,6 +1297,8 @@ struct kvm_arch {
* the opportunity to look at it.
*/
bool exit_on_emulation_error;
+ /* msr.error takes KVM_INSN_*, see KVM_CAP_X86_MSR_EXIT_INSN */
+ bool user_space_msr_insn;
/* Deflect RDMSR and WRMSR to user space when they trigger a #GP */
u32 user_space_msr_mask;
diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c
index e91650af44c2..6b1b93592c2e 100644
--- a/arch/x86/kvm/msrs.c
+++ b/arch/x86/kvm/msrs.c
@@ -952,12 +952,40 @@ fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg)
}
EXPORT_SYMBOL_FOR_KVM_INTERNAL(handle_fastpath_wrmsr_imm);
+/*
+ * Act on what userspace answered in msr.error. Returns 1 if nothing is left
+ * to do for the access, or -EINVAL; otherwise 0, with @fail set for the
+ * common completion, which retires the instruction or injects #GP by
+ * whatever means the guest needs.
+ *
+ * Without KVM_CAP_X86_MSR_EXIT_INSN any error is a #GP. So it is for a
+ * guest with protected state, which kvm_insn_uncompleted() only completes.
+ */
+static int kvm_msr_exit_answer(struct kvm_vcpu *vcpu, bool *fail)
+{
+ u8 error = READ_ONCE(vcpu->run->msr.error);
+
+ *fail = error;
+
+ if (!vcpu->kvm->arch.user_space_msr_insn ||
+ error == KVM_INSN_COMPLETE || error == KVM_INSN_GP)
+ return 0;
+
+ return kvm_insn_uncompleted(vcpu, error);
+}
+
static void complete_userspace_rdmsr(struct kvm_vcpu *vcpu)
{
- if (!vcpu->run->msr.error) {
- kvm_eax_write(vcpu, vcpu->run->msr.data);
- kvm_edx_write(vcpu, vcpu->run->msr.data >> 32);
- }
+ u64 data = READ_ONCE(vcpu->run->msr.data);
+
+ kvm_eax_write(vcpu, data);
+ kvm_edx_write(vcpu, data >> 32);
+}
+
+static void complete_userspace_rdmsr_imm(struct kvm_vcpu *vcpu)
+{
+ kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
+ READ_ONCE(vcpu->run->msr.data));
}
static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
@@ -971,35 +999,52 @@ static int complete_emulated_insn_gp(struct kvm_vcpu *vcpu, int err)
EMULTYPE_COMPLETE_USER_EXIT);
}
+/*
+ * The one completion of an MSR exit: @emulated says whether the emulator or
+ * an intercept raised it, and @result writes what a successful read returned.
+ */
+static int complete_msr_access(struct kvm_vcpu *vcpu, bool emulated,
+ void (*result)(struct kvm_vcpu *vcpu))
+{
+ bool fail;
+ int r;
+
+ r = kvm_msr_exit_answer(vcpu, &fail);
+ if (r)
+ return r;
+
+ if (!fail && result)
+ result(vcpu);
+
+ if (emulated)
+ return complete_emulated_insn_gp(vcpu, fail);
+
+ return kvm_x86_call(complete_emulated_msr)(vcpu, fail);
+}
+
static int complete_emulated_msr_access(struct kvm_vcpu *vcpu)
{
- return complete_emulated_insn_gp(vcpu, vcpu->run->msr.error);
+ return complete_msr_access(vcpu, true, NULL);
}
static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
{
- complete_userspace_rdmsr(vcpu);
- return complete_emulated_msr_access(vcpu);
+ return complete_msr_access(vcpu, true, complete_userspace_rdmsr);
}
static int complete_fast_msr_access(struct kvm_vcpu *vcpu)
{
- return kvm_x86_call(complete_emulated_msr)(vcpu, vcpu->run->msr.error);
+ return complete_msr_access(vcpu, false, NULL);
}
static int complete_fast_rdmsr(struct kvm_vcpu *vcpu)
{
- complete_userspace_rdmsr(vcpu);
- return complete_fast_msr_access(vcpu);
+ return complete_msr_access(vcpu, false, complete_userspace_rdmsr);
}
static int complete_fast_rdmsr_imm(struct kvm_vcpu *vcpu)
{
- if (!vcpu->run->msr.error)
- kvm_register_write(vcpu, vcpu->arch.cui_rdmsr_imm_reg,
- vcpu->run->msr.data);
-
- return complete_fast_msr_access(vcpu);
+ return complete_msr_access(vcpu, false, complete_userspace_rdmsr_imm);
}
static u64 kvm_msr_reason(int r)
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 26e7beaff8a0..31c6759f38b9 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -2276,6 +2276,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
case KVM_CAP_SET_GUEST_DEBUG:
case KVM_CAP_LAST_CPU:
case KVM_CAP_X86_USER_SPACE_MSR:
+ case KVM_CAP_X86_MSR_EXIT_INSN:
case KVM_CAP_X86_MSR_FILTER:
case KVM_CAP_ENFORCE_PV_FEATURE_CPUID:
#ifdef CONFIG_X86_SGX_KVM
@@ -4091,6 +4092,13 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
kvm->arch.user_space_msr_mask = cap->args[0];
r = 0;
break;
+ case KVM_CAP_X86_MSR_EXIT_INSN:
+ r = -EINVAL;
+ if (cap->args[0] > 1)
+ break;
+ kvm->arch.user_space_msr_insn = cap->args[0];
+ r = 0;
+ break;
case KVM_CAP_X86_BUS_LOCK_EXIT:
r = -EINVAL;
if (cap->args[0] & ~KVM_BUS_LOCK_DETECTION_VALID_MODE)
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 0a4c548cb329..a146c0487960 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -431,7 +431,7 @@ struct kvm_run {
} arm_nisv;
/* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
struct {
- __u8 error; /* user -> kernel */
+ __u8 error; /* in: KVM_INSN_* */
__u8 pad[7];
#define KVM_MSR_EXIT_REASON_INVAL (1 << 0)
#define KVM_MSR_EXIT_REASON_UNKNOWN (1 << 1)
@@ -1009,6 +1009,7 @@ struct kvm_enable_cap {
#define KVM_CAP_PPC_COMPAT_CAPS 250
#define KVM_CAP_ARM_PMU_V3_STRICT 251
#define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252
+#define KVM_CAP_X86_MSR_EXIT_INSN 253
struct kvm_irq_routing_irqchip {
__u32 irqchip;
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 04/15] KVM: selftests: Test MSR accesses which userspace leaves alone
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (2 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 03/15] KVM: x86: Let userspace leave an MSR access alone David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 05/15] KVM: x86: hyper-v: Add KVM_CAP_HYPERV_FORWARD_HCALL David Woodhouse
` (10 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Cover intercepted and force-emulated RDMSR and WRMSR: without
KVM_CAP_X86_MSR_EXIT_INSN any error is a #GP; with it, each KVM_INSN_*
value, undefined ones, and KVM_INSN_RESUME with nothing changed, with a
queued #NM, with RIP moved, and across a single-step.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
tools/testing/selftests/kvm/Makefile.kvm | 1 +
.../selftests/kvm/x86/msr_exit_insn_test.c | 308 ++++++++++++++++++
2 files changed, 309 insertions(+)
create mode 100644 tools/testing/selftests/kvm/x86/msr_exit_insn_test.c
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 17a4256e9081..f0cb8cf748dd 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -96,6 +96,7 @@ TEST_GEN_PROGS_x86 += x86/kvm_clock_test
TEST_GEN_PROGS_x86 += x86/kvm_pv_test
TEST_GEN_PROGS_x86 += x86/kvm_buslock_test
TEST_GEN_PROGS_x86 += x86/monitor_mwait_test
+TEST_GEN_PROGS_x86 += x86/msr_exit_insn_test
TEST_GEN_PROGS_x86 += x86/msrs_test
TEST_GEN_PROGS_x86 += x86/nested_close_kvm_test
TEST_GEN_PROGS_x86 += x86/nested_dirty_log_test
diff --git a/tools/testing/selftests/kvm/x86/msr_exit_insn_test.c b/tools/testing/selftests/kvm/x86/msr_exit_insn_test.c
new file mode 100644
index 000000000000..9ff6c88de38a
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/msr_exit_insn_test.c
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Test KVM_CAP_X86_MSR_EXIT_INSN: without it, any non-zero 'error' of
+ * KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR is a #GP. With it, 'error'
+ * takes KVM_INSN_*: the #GP is KVM_INSN_GP, KVM_INSN_UD injects #UD,
+ * undefined values fail KVM_RUN, and KVM_INSN_RESUME leaves the
+ * instruction unretired: RIP and the registers stay as they were and no
+ * #GP is injected, so the guest runs the instruction again, or takes the
+ * exception userspace queued, or resumes where userspace moved RIP. Both
+ * intercepted and, with kvm.force_emulation_prefix, emulated accesses are
+ * covered. KVM steps over the prefix before it emulates, so an emulated
+ * access which is left alone is intercepted when the guest executes it
+ * again.
+ *
+ * Copyright © 2026 Amazon.com, Inc. or its affiliates.
+ */
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+
+#define TEST_MSR 0x474f4f00 /* Not implemented by KVM. */
+
+#define MSR_INSN_LEN 2
+
+#define WRITE_VAL 0x1122334455667788ULL
+#define DATA_IGNORED 0xa1a2a3a4a5a6a7a8ULL
+#define DATA_RET0 0xb1b2b3b4b5b6b7b8ULL
+#define DATA_RETRY 0xc1c2c3c4c5c6c7c8ULL
+#define DATA_MOVED 0xd1d2d3d4d5d6d7d8ULL
+#define DATA_STEP 0xe1e2e3e4e5e6e7e8ULL
+#define DATA_BAD 0xbad0bad1bad2bad3ULL
+
+static u8 guest_rdmsr(bool fep, u64 *val)
+{
+ *val = 0;
+ return fep ? rdmsr_safe_fep(TEST_MSR, val) : rdmsr_safe(TEST_MSR, val);
+}
+
+static u8 guest_wrmsr(bool fep)
+{
+ if (fep)
+ return kvm_asm_safe_fep("wrmsr", "a"(WRITE_VAL & -1u),
+ "d"(WRITE_VAL >> 32), "c"(TEST_MSR));
+
+ return wrmsr_safe(TEST_MSR, WRITE_VAL);
+}
+
+/* One read, then one write, which must end as userspace decided. */
+static void guest_access(bool fep, u8 vector, u64 data)
+{
+ u64 val;
+
+ GUEST_ASSERT_EQ(guest_rdmsr(fep, &val), vector);
+ if (!vector)
+ GUEST_ASSERT_EQ(val, data);
+ GUEST_ASSERT_EQ(guest_wrmsr(fep), vector);
+}
+
+static void guest_accesses(bool fep)
+{
+ /* Not enabled: zero completes, and anything else is a #GP. */
+ guest_access(fep, 0, DATA_IGNORED);
+ guest_access(fep, GP_VECTOR, 0);
+ guest_access(fep, GP_VECTOR, 0);
+ guest_access(fep, GP_VECTOR, 0);
+ GUEST_SYNC(fep);
+
+ /* Enabled: completed, then failed with #GP, then with #UD. */
+ guest_access(fep, 0, DATA_RET0);
+ guest_access(fep, GP_VECTOR, 0);
+ guest_access(fep, UD_VECTOR, 0);
+
+ /* Left alone, or refused by KVM_RUN: the instruction runs again. */
+ guest_access(fep, 0, DATA_RETRY);
+
+ /* Left alone with #NM queued by userspace. */
+ guest_access(fep, NM_VECTOR, 0);
+
+ /* Left alone and retired by userspace. */
+ guest_access(fep, 0, DATA_MOVED);
+
+ /* Left alone and then completed while single-stepping. */
+ guest_access(fep, 0, DATA_STEP);
+ GUEST_SYNC(fep);
+}
+
+static void guest_code(void)
+{
+ guest_accesses(false);
+ if (is_forced_emulation_enabled)
+ guest_accesses(true);
+ GUEST_DONE();
+}
+
+static void expect_msr_exit(struct kvm_vcpu *vcpu, bool write)
+{
+ struct kvm_run *run = vcpu->run;
+ struct ucall uc;
+
+ vcpu_run(vcpu);
+ if (run->exit_reason == KVM_EXIT_IO && get_ucall(vcpu, &uc) == UCALL_ABORT)
+ REPORT_GUEST_ASSERT(uc);
+
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, write ? KVM_EXIT_X86_WRMSR :
+ KVM_EXIT_X86_RDMSR);
+ TEST_ASSERT_EQ(run->msr.index, TEST_MSR);
+ TEST_ASSERT_EQ(run->msr.reason, KVM_MSR_EXIT_REASON_UNKNOWN);
+ TEST_ASSERT_EQ(run->msr.error, KVM_INSN_COMPLETE);
+ if (write)
+ TEST_ASSERT_EQ(run->msr.data, WRITE_VAL);
+}
+
+static void expect_sync(struct kvm_vcpu *vcpu, bool fep)
+{
+ struct ucall uc;
+
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ switch (get_ucall(vcpu, &uc)) {
+ case UCALL_SYNC:
+ TEST_ASSERT_EQ(uc.args[1], fep);
+ break;
+ case UCALL_ABORT:
+ REPORT_GUEST_ASSERT(uc);
+ default:
+ TEST_FAIL("Unexpected ucall %lu", uc.cmd);
+ }
+}
+
+/*
+ * Leave the access alone, with 'data' set to what must not reach the guest,
+ * or give KVM_RUN a value it refuses, and check that the access comes back
+ * exactly as it was.
+ */
+static void leave_and_retake(struct kvm_vcpu *vcpu, bool write, u8 error)
+{
+ struct kvm_run *run = vcpu->run;
+ struct kvm_regs before, after;
+
+ /* The #UD exit of a forced emulation sets RF; an intercept does not. */
+ vcpu_regs_get(vcpu, &before);
+ before.rflags &= ~X86_EFLAGS_RF;
+ run->msr.error = error;
+ if (!write)
+ run->msr.data = DATA_BAD;
+
+ if (error > KVM_INSN_RESUME) {
+ TEST_ASSERT(__vcpu_run(vcpu) == -1 && errno == EINVAL,
+ "KVM_RUN accepted 'error' %u", error);
+ vcpu_regs_get(vcpu, &after);
+ after.rflags &= ~X86_EFLAGS_RF;
+ TEST_ASSERT(!memcmp(&before, &after, sizeof(before)),
+ "Registers changed by a failed KVM_RUN");
+ }
+
+ expect_msr_exit(vcpu, write);
+ vcpu_regs_get(vcpu, &after);
+ after.rflags &= ~X86_EFLAGS_RF;
+ TEST_ASSERT(!memcmp(&before, &after, sizeof(before)),
+ "Registers changed over a %s left alone: RIP 0x%llx -> 0x%llx, RAX 0x%llx -> 0x%llx, RDX 0x%llx -> 0x%llx, RFLAGS 0x%llx -> 0x%llx",
+ write ? "WRMSR" : "RDMSR", before.rip, after.rip,
+ before.rax, after.rax, before.rdx, after.rdx,
+ before.rflags, after.rflags);
+}
+
+static void complete(struct kvm_vcpu *vcpu, bool write, u8 error, u64 data)
+{
+ vcpu->run->msr.error = error;
+ if (!write)
+ vcpu->run->msr.data = data;
+}
+
+static void run_accesses(struct kvm_vcpu *vcpu, bool fep)
+{
+ struct kvm_guest_debug debug = {};
+ struct kvm_run *run = vcpu->run;
+ struct kvm_vcpu_events events;
+ struct kvm_regs regs;
+ int write;
+
+ /* Not enabled: any non-zero 'error' is a #GP. */
+ vm_enable_cap(vcpu->vm, KVM_CAP_X86_MSR_EXIT_INSN, 0);
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, 0, DATA_IGNORED);
+ }
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, KVM_INSN_RESUME, DATA_BAD);
+ }
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, KVM_INSN_UD, DATA_BAD);
+ }
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, 0x80, DATA_BAD);
+ }
+ expect_sync(vcpu, fep);
+ vm_enable_cap(vcpu->vm, KVM_CAP_X86_MSR_EXIT_INSN, 1);
+
+ /* Complete and #GP: as before. And #UD. */
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, KVM_INSN_COMPLETE, DATA_RET0);
+ }
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, KVM_INSN_GP, DATA_BAD);
+ }
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, KVM_INSN_UD, DATA_BAD);
+ }
+
+ /*
+ * Resume: no #GP, nothing written, the same exit again. A reserved
+ * value fails KVM_RUN and leaves the guest the same way.
+ */
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ leave_and_retake(vcpu, write, KVM_INSN_RESUME);
+ leave_and_retake(vcpu, write, KVM_INSN_RESUME + 1);
+ leave_and_retake(vcpu, write, KVM_INSN_RESUME);
+ leave_and_retake(vcpu, write, 0xff);
+ complete(vcpu, write, KVM_INSN_COMPLETE, DATA_RETRY);
+ }
+
+ /* Resume with an exception queued: taken at the instruction. */
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ run->msr.error = KVM_INSN_RESUME;
+ vcpu_events_get(vcpu, &events);
+ TEST_ASSERT(!events.exception.pending && !events.exception.injected,
+ "Exception queued at an MSR exit");
+ events.exception.injected = 1;
+ events.exception.nr = NM_VECTOR;
+ events.exception.has_error_code = 0;
+ vcpu_events_set(vcpu, &events);
+ }
+
+ /* Resume with RIP moved: userspace performed the access. */
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ complete(vcpu, write, KVM_INSN_RESUME, DATA_BAD);
+ vcpu_regs_get(vcpu, ®s);
+ regs.rip += MSR_INSN_LEN;
+ if (!write) {
+ regs.rax = DATA_MOVED & -1u;
+ regs.rdx = DATA_MOVED >> 32;
+ }
+ vcpu_regs_set(vcpu, ®s);
+ }
+
+ /*
+ * Single-step: an access which is left alone has not retired, so
+ * there is no debug exit until it is completed.
+ */
+ for (write = 0; write <= 1; write++) {
+ expect_msr_exit(vcpu, write);
+ vcpu_regs_get(vcpu, ®s);
+ debug.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
+ vcpu_guest_debug_set(vcpu, &debug);
+ leave_and_retake(vcpu, write, KVM_INSN_RESUME);
+ complete(vcpu, write, KVM_INSN_COMPLETE, DATA_STEP);
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_DEBUG);
+ TEST_ASSERT_EQ(run->debug.arch.pc, regs.rip + MSR_INSN_LEN);
+ debug.control = 0;
+ vcpu_guest_debug_set(vcpu, &debug);
+ }
+ expect_sync(vcpu, fep);
+}
+
+int main(int argc, char *argv[])
+{
+ struct kvm_vcpu *vcpu;
+ struct kvm_vm *vm;
+ struct ucall uc;
+
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_X86_USER_SPACE_MSR));
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_X86_MSR_EXIT_INSN));
+ /* With kvm.ignore_msrs the access to TEST_MSR never exits. */
+ TEST_REQUIRE(!kvm_is_ignore_msrs());
+ TEST_ASSERT_EQ(kvm_check_cap(KVM_CAP_X86_MSR_EXIT_INSN), 1);
+
+ vm = vm_create_with_one_vcpu(&vcpu, guest_code);
+
+ TEST_ASSERT(__vm_enable_cap(vm, KVM_CAP_X86_MSR_EXIT_INSN, 2) == -1 &&
+ errno == EINVAL,
+ "KVM_CAP_X86_MSR_EXIT_INSN accepted an unknown argument");
+ vm_enable_cap(vm, KVM_CAP_X86_USER_SPACE_MSR, KVM_MSR_EXIT_REASON_UNKNOWN);
+
+ run_accesses(vcpu, false);
+ if (is_forced_emulation_enabled)
+ run_accesses(vcpu, true);
+ else
+ pr_info("Set kvm.force_emulation_prefix=1 to test emulated MSR accesses\n");
+
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ if (get_ucall(vcpu, &uc) == UCALL_ABORT)
+ REPORT_GUEST_ASSERT(uc);
+ TEST_ASSERT_EQ(uc.cmd, UCALL_DONE);
+
+ kvm_vm_free(vm);
+ return 0;
+}
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 05/15] KVM: x86: hyper-v: Add KVM_CAP_HYPERV_FORWARD_HCALL
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (3 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 04/15] KVM: selftests: Test MSR accesses which userspace leaves alone David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 06/15] KVM: x86: hyper-v: Let userspace leave a hypercall uncompleted David Woodhouse
` (9 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
KVM fails every Hyper-V hypercall which it does not implement with
HV_STATUS_INVALID_HYPERCALL_CODE, so a VMM which implements more of the
TLFS never sees them.
Add a VM capability whose value is a mask of hypercall handling
features, as KVM_CAP_XEN_HVM and KVM_CAP_EXIT_HYPERCALL have;
KVM_ENABLE_CAP takes the subset to enable. The first feature,
KVM_HYPERV_HCALL_FORWARD_UNKNOWN, sends those hypercalls, and extended
hypercalls in fast form, out through the existing KVM_EXIT_HYPERV_HCALL.
XMM state is reachable through the vCPU state ioctls.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 50 +++++++++++++++++++++++++++++++++
arch/x86/include/asm/kvm_host.h | 2 ++
arch/x86/kvm/hyperv.c | 7 ++++-
arch/x86/kvm/hyperv.h | 8 ++++++
arch/x86/kvm/x86.c | 16 +++++++++++
include/uapi/linux/kvm.h | 4 +++
6 files changed, 86 insertions(+), 1 deletion(-)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index 6d4a11ce368c..782c010a08a0 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -7362,6 +7362,16 @@ Hyper-V SynIC state change. Notification is used to remap SynIC
event/message pages and to enable/disable SynIC messages/events processing
in userspace.
+ - KVM_EXIT_HYPERV_HCALL -- a hypercall for userspace to handle.
+
+'input' holds the hypercall control value and 'params' the two parameter
+registers. Userspace sets 'result' to the hypercall result value before
+resuming the vCPU; KVM then writes it to the guest and advances past the
+hypercall instruction. KVM leaves some hypercalls to userspace this
+way, HvCallPostMessage in some cases among them;
+KVM_CAP_HYPERV_FORWARD_HCALL (see section 7.49) adds the hypercalls KVM
+does not implement.
+
- KVM_EXIT_HYPERV_SYNDBG -- synchronously notify user-space about
Hyper-V Synthetic debugger state change. Notification is used to either update
@@ -9263,6 +9273,46 @@ KVM_CAP_X86_USER_SPACE_MSR and KVM_X86_SET_MSR_FILTER.
A guest whose register state is protected is the exception: see the
description of those exits.
+7.49 KVM_CAP_HYPERV_FORWARD_HCALL
+---------------------------------
+
+:Architectures: x86
+:Target: VM
+:Parameters: args[0] is a bitmask of KVM_HYPERV_HCALL_* features to enable
+:Returns: 0 on success, -EINVAL if args[0] contains an unsupported bit
+
+KVM_CHECK_EXTENSION for this capability returns a bitmask of the Hyper-V
+hypercall handling features that KVM implements. KVM_ENABLE_CAP takes
+the subset that userspace wants active and replaces the previously
+enabled set; it can be called at any time. A bit that
+KVM_CHECK_EXTENSION does not report is rejected with -EINVAL, so a VMM
+can enable exactly the features it was written for and learn which ones
+the kernel lacks. The mask is reported in the int which
+KVM_CHECK_EXTENSION returns, so features only ever use bits 0 to 30.
+
+The defined bits are::
+
+ #define KVM_HYPERV_HCALL_FORWARD_UNKNOWN (1ULL << 0)
+
+KVM_HYPERV_HCALL_FORWARD_UNKNOWN: a hypercall that KVM would otherwise
+fail with HV_STATUS_INVALID_HYPERCALL_CODE exits to userspace with
+KVM_EXIT_HYPERV_HCALL instead, and an extended hypercall in fast form
+exits the same way instead of failing with HV_STATUS_INVALID_PARAMETER.
+The VMM can then implement hypercalls that KVM does not. The synthetic
+debugger hypercalls (HvCallResetDebugSession, HvCallPostDebugData,
+HvCallRetrieveDebugData) are an exception: while the synthetic debugger
+is not enabled they still fail in KVM, with HV_STATUS_INVALID_PARAMETER
+for the fast form of HvCallPostDebugData and HvCallRetrieveDebugData and
+with HV_STATUS_INVALID_HYPERCALL_CODE otherwise.
+
+For a fast hypercall, 'params' carries RDX and R8 from a 64-bit caller,
+or the EBX:ECX and EDI:ESI pairs from a 32-bit caller. XMM input and
+output registers of a fast hypercall are read and written with the
+ordinary vCPU state ioctls (KVM_GET_XSAVE/KVM_SET_XSAVE or
+KVM_GET_FPU/KVM_SET_FPU) before the vCPU is resumed. Hypercalls that
+KVM implements itself, and the CPUID-enforcement checks KVM applies
+before dispatching a hypercall, are unaffected.
+
8. Other capabilities.
======================
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 0e8150116e20..dcb0ce584f02 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1072,6 +1072,8 @@ struct kvm_hv {
struct mutex hv_lock;
u64 hv_guest_os_id;
u64 hv_hypercall;
+ /* KVM_HYPERV_HCALL_* features enabled by KVM_CAP_HYPERV_FORWARD_HCALL */
+ u64 hcall_features;
u64 hv_tsc_page;
enum hv_tsc_page_status hv_tsc_page_status;
diff --git a/arch/x86/kvm/hyperv.c b/arch/x86/kvm/hyperv.c
index 5d2e3617c952..e72539f9acc9 100644
--- a/arch/x86/kvm/hyperv.c
+++ b/arch/x86/kvm/hyperv.c
@@ -2692,12 +2692,17 @@ int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
goto hypercall_userspace_exit;
}
case HV_EXT_CALL_QUERY_CAPABILITIES ... HV_EXT_CALL_MAX:
- if (unlikely(hc.fast)) {
+ if (unlikely(hc.fast) &&
+ !kvm_hv_hcall_feature(vcpu->kvm,
+ KVM_HYPERV_HCALL_FORWARD_UNKNOWN)) {
ret = HV_STATUS_INVALID_PARAMETER;
break;
}
goto hypercall_userspace_exit;
default:
+ if (kvm_hv_hcall_feature(vcpu->kvm,
+ KVM_HYPERV_HCALL_FORWARD_UNKNOWN))
+ goto hypercall_userspace_exit;
ret = HV_STATUS_INVALID_HYPERCALL_CODE;
break;
}
diff --git a/arch/x86/kvm/hyperv.h b/arch/x86/kvm/hyperv.h
index 622a6553e9ac..20d40261c75b 100644
--- a/arch/x86/kvm/hyperv.h
+++ b/arch/x86/kvm/hyperv.h
@@ -205,6 +205,14 @@ static inline bool kvm_hv_hypercall_enabled(struct kvm_vcpu *vcpu)
return vcpu->arch.hyperv_enabled && to_kvm_hv(vcpu->kvm)->hv_guest_os_id;
}
+/* Features reported and accepted by KVM_CAP_HYPERV_FORWARD_HCALL. */
+#define KVM_HYPERV_HCALL_SUPPORTED KVM_HYPERV_HCALL_FORWARD_UNKNOWN
+
+static inline bool kvm_hv_hcall_feature(struct kvm *kvm, u64 feature)
+{
+ return READ_ONCE(to_kvm_hv(kvm)->hcall_features) & feature;
+}
+
int kvm_hv_hypercall(struct kvm_vcpu *vcpu);
void kvm_hv_irq_routing_update(struct kvm *kvm);
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 31c6759f38b9..da22e7d9cacd 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -2306,6 +2306,13 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
case KVM_CAP_EXIT_HYPERCALL:
r = KVM_EXIT_HYPERCALL_VALID_MASK;
break;
+#ifdef CONFIG_KVM_HYPERV
+ case KVM_CAP_HYPERV_FORWARD_HCALL:
+ /* KVM_CHECK_EXTENSION returns an int: only bits 0-30 report. */
+ BUILD_BUG_ON(KVM_HYPERV_HCALL_SUPPORTED > INT_MAX);
+ r = KVM_HYPERV_HCALL_SUPPORTED;
+ break;
+#endif
case KVM_CAP_SET_GUEST_DEBUG2:
return KVM_GUESTDBG_VALID_MASK;
#ifdef CONFIG_KVM_XEN
@@ -4152,6 +4159,15 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
kvm->arch.hypercall_exit_enabled = cap->args[0];
r = 0;
break;
+#ifdef CONFIG_KVM_HYPERV
+ case KVM_CAP_HYPERV_FORWARD_HCALL:
+ r = -EINVAL;
+ if (cap->args[0] & ~KVM_HYPERV_HCALL_SUPPORTED)
+ break;
+ WRITE_ONCE(to_kvm_hv(kvm)->hcall_features, cap->args[0]);
+ r = 0;
+ break;
+#endif
case KVM_CAP_EXIT_ON_EMULATION_FAILURE:
r = -EINVAL;
if (cap->args[0] & ~1)
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index a146c0487960..5803c84cf8f8 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -126,6 +126,9 @@ struct kvm_hyperv_exit {
} u;
};
+/* KVM_CAP_HYPERV_FORWARD_HCALL feature bits */
+#define KVM_HYPERV_HCALL_FORWARD_UNKNOWN (1ULL << 0)
+
struct kvm_xen_exit {
#define KVM_EXIT_XEN_HCALL 1
__u32 type;
@@ -1010,6 +1013,7 @@ struct kvm_enable_cap {
#define KVM_CAP_ARM_PMU_V3_STRICT 251
#define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252
#define KVM_CAP_X86_MSR_EXIT_INSN 253
+#define KVM_CAP_HYPERV_FORWARD_HCALL 254
struct kvm_irq_routing_irqchip {
__u32 irqchip;
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 06/15] KVM: x86: hyper-v: Let userspace leave a hypercall uncompleted
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (4 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 05/15] KVM: x86: hyper-v: Add KVM_CAP_HYPERV_FORWARD_HCALL David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 07/15] KVM: x86: hyper-v: Advertise XMM fast hypercall output David Woodhouse
` (8 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
A VMM handling KVM_EXIT_HYPERV_HCALL can only complete the hypercall:
KVM writes the result and advances RIP. The TLFS has some raise #UD
at the instruction instead: a VTL return from the lowest VTL, for one.
Add a 'ret' field to the exit, which takes KVM_INSN_*: zero completes
as before, KVM_INSN_UD and KVM_INSN_GP inject the exception, and
KVM_INSN_RESUME does nothing, so an exception which userspace queued
is taken at the hypercall. It is opt-in (KVM_HYPERV_HCALL_RET):
existing VMMs never zeroed the union.
Link: https://lore.kernel.org/kvm/avuDUNAU_a933zvp@seanjc-mac.roam.internal/
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 25 +++++++++++++++++++++++++
arch/x86/kvm/hyperv.c | 20 +++++++++++++++++++-
arch/x86/kvm/hyperv.h | 3 ++-
include/uapi/linux/kvm.h | 3 +++
4 files changed, 49 insertions(+), 2 deletions(-)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index 782c010a08a0..ea48247c2976 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -7336,6 +7336,8 @@ EOI was received.
__u64 input;
__u64 result;
__u64 params[2];
+ __u8 ret;
+ __u8 pad3[7];
} hcall;
struct {
__u32 msr;
@@ -7372,6 +7374,23 @@ way, HvCallPostMessage in some cases among them;
KVM_CAP_HYPERV_FORWARD_HCALL (see section 7.49) adds the hypercalls KVM
does not implement.
+KVM sets 'ret' to zero, KVM_INSN_COMPLETE, which means that the
+hypercall completes as described above. With KVM_HYPERV_HCALL_RET
+enabled, userspace may set 'ret' to another of the KVM_INSN_* values
+instead (see :ref:`the description of completion <kvm_insn_action>`),
+and the hypercall does not complete: KVM writes no result and leaves RIP
+at the hypercall instruction. KVM_INSN_UD and KVM_INSN_GP inject #UD
+and #GP(0), the exceptions which Hyper-V raises when it refuses a
+hypercall itself. KVM_INSN_RESUME injects nothing: a VMM which wants
+another exception (e.g. #PF with the address in exception_payload)
+queues it with KVM_SET_VCPU_EVENTS before it resumes the vCPU, and the
+guest takes it at the hypercall instruction. 'pad3' is reserved and is
+zero.
+
+For a guest whose register state is protected (SEV-ES, SEV-SNP, TDX)
+'ret' is ignored, with or without KVM_HYPERV_HCALL_RET: the hypercall
+completes.
+
- KVM_EXIT_HYPERV_SYNDBG -- synchronously notify user-space about
Hyper-V Synthetic debugger state change. Notification is used to either update
@@ -9293,6 +9312,7 @@ KVM_CHECK_EXTENSION returns, so features only ever use bits 0 to 30.
The defined bits are::
#define KVM_HYPERV_HCALL_FORWARD_UNKNOWN (1ULL << 0)
+ #define KVM_HYPERV_HCALL_RET (1ULL << 1)
KVM_HYPERV_HCALL_FORWARD_UNKNOWN: a hypercall that KVM would otherwise
fail with HV_STATUS_INVALID_HYPERCALL_CODE exits to userspace with
@@ -9313,6 +9333,11 @@ KVM_GET_FPU/KVM_SET_FPU) before the vCPU is resumed. Hypercalls that
KVM implements itself, and the CPUID-enforcement checks KVM applies
before dispatching a hypercall, are unaffected.
+KVM_HYPERV_HCALL_RET: KVM honours the 'ret' field of every
+KVM_EXIT_HYPERV_HCALL exit, whichever hypercall caused it, and fails
+KVM_RUN with -EINVAL for a value it does not define. Without it the
+field is ignored and every such exit completes.
+
8. Other capabilities.
======================
diff --git a/arch/x86/kvm/hyperv.c b/arch/x86/kvm/hyperv.c
index e72539f9acc9..67c9d20547d8 100644
--- a/arch/x86/kvm/hyperv.c
+++ b/arch/x86/kvm/hyperv.c
@@ -2430,7 +2430,22 @@ static int kvm_hv_hypercall_complete(struct kvm_vcpu *vcpu, u64 result)
static int kvm_hv_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
{
- return kvm_hv_hypercall_complete(vcpu, vcpu->run->hyperv.u.hcall.result);
+ /*
+ * Userspace may say that the hypercall does not complete: the result
+ * stays unwritten and RIP at the instruction, where the guest takes
+ * the exception that userspace asked for, or queued itself. Not so
+ * for a guest with protected state, whose hypercall can only complete.
+ */
+ if (kvm_hv_hcall_feature(vcpu->kvm, KVM_HYPERV_HCALL_RET)) {
+ u8 ret = READ_ONCE(vcpu->run->hyperv.u.hcall.ret);
+ int r = kvm_insn_uncompleted(vcpu, ret);
+
+ if (r)
+ return r;
+ }
+
+ return kvm_hv_hypercall_complete(vcpu,
+ READ_ONCE(vcpu->run->hyperv.u.hcall.result));
}
static u16 kvm_hvcall_signal_event(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc)
@@ -2716,6 +2731,9 @@ int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
vcpu->run->hyperv.u.hcall.input = hc.param;
vcpu->run->hyperv.u.hcall.params[0] = hc.ingpa;
vcpu->run->hyperv.u.hcall.params[1] = hc.outgpa;
+ vcpu->run->hyperv.u.hcall.ret = 0;
+ memset(vcpu->run->hyperv.u.hcall.pad3, 0,
+ sizeof(vcpu->run->hyperv.u.hcall.pad3));
vcpu->arch.complete_userspace_io = kvm_hv_hypercall_complete_userspace;
return 0;
}
diff --git a/arch/x86/kvm/hyperv.h b/arch/x86/kvm/hyperv.h
index 20d40261c75b..5b6220b17e77 100644
--- a/arch/x86/kvm/hyperv.h
+++ b/arch/x86/kvm/hyperv.h
@@ -206,7 +206,8 @@ static inline bool kvm_hv_hypercall_enabled(struct kvm_vcpu *vcpu)
}
/* Features reported and accepted by KVM_CAP_HYPERV_FORWARD_HCALL. */
-#define KVM_HYPERV_HCALL_SUPPORTED KVM_HYPERV_HCALL_FORWARD_UNKNOWN
+#define KVM_HYPERV_HCALL_SUPPORTED (KVM_HYPERV_HCALL_FORWARD_UNKNOWN | \
+ KVM_HYPERV_HCALL_RET)
static inline bool kvm_hv_hcall_feature(struct kvm *kvm, u64 feature)
{
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 5803c84cf8f8..e480544a3746 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -113,6 +113,8 @@ struct kvm_hyperv_exit {
__u64 input;
__u64 result;
__u64 params[2];
+ __u8 ret; /* in: KVM_INSN_* */
+ __u8 pad3[7];
} hcall;
struct {
__u32 msr;
@@ -128,6 +130,7 @@ struct kvm_hyperv_exit {
/* KVM_CAP_HYPERV_FORWARD_HCALL feature bits */
#define KVM_HYPERV_HCALL_FORWARD_UNKNOWN (1ULL << 0)
+#define KVM_HYPERV_HCALL_RET (1ULL << 1)
struct kvm_xen_exit {
#define KVM_EXIT_XEN_HCALL 1
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 07/15] KVM: x86: hyper-v: Advertise XMM fast hypercall output
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (5 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 06/15] KVM: x86: hyper-v: Let userspace leave a hypercall uncompleted David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 08/15] KVM: selftests: Add Hyper-V hypercall forwarding test David Woodhouse
` (7 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
A fast hypercall may return its output in XMM registers when the
hypervisor reports HV_X64_HYPERCALL_XMM_OUTPUT_AVAILABLE, and Windows
only uses those forms when the bit is set. KVM does not report it,
although a VMM handling a forwarded fast hypercall can write the output
through the vCPU FPU state.
Report the bit. None of the hypercalls KVM implements itself returns
output, so it only matters for those which the VMM handles.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
arch/x86/kvm/hyperv.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/arch/x86/kvm/hyperv.c b/arch/x86/kvm/hyperv.c
index 67c9d20547d8..bf0e37d026c0 100644
--- a/arch/x86/kvm/hyperv.c
+++ b/arch/x86/kvm/hyperv.c
@@ -2882,6 +2882,7 @@ int kvm_get_hv_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid2 *cpuid,
ent->ebx |= HV_ENABLE_EXTENDED_HYPERCALLS;
ent->edx |= HV_X64_HYPERCALL_XMM_INPUT_AVAILABLE;
+ ent->edx |= HV_X64_HYPERCALL_XMM_OUTPUT_AVAILABLE;
ent->edx |= HV_FEATURE_FREQUENCY_MSRS_AVAILABLE;
ent->edx |= HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE;
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 08/15] KVM: selftests: Add Hyper-V hypercall forwarding test
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (6 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 07/15] KVM: x86: hyper-v: Advertise XMM fast hypercall output David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 09/15] KVM: x86: Add a per-vCPU register write filter David Woodhouse
` (6 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Cover KVM_CAP_HYPERV_FORWARD_HCALL: the feature mask; an unknown
hypercall forwarded in memory-based and fast form, and an extended one
in fast form, with the full 64-bit result and the XMM output from
userspace; and 'ret', which is ignored until enabled, raises #UD or #GP,
lets a queued #NM be taken at the hypercall, re-executes it with nothing
queued, and fails KVM_RUN when reserved, leaving RAX alone each time.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
tools/testing/selftests/kvm/Makefile.kvm | 1 +
.../selftests/kvm/x86/hyperv_forward_hcall.c | 395 ++++++++++++++++++
2 files changed, 396 insertions(+)
create mode 100644 tools/testing/selftests/kvm/x86/hyperv_forward_hcall.c
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index f0cb8cf748dd..2f67399ddd68 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -89,6 +89,7 @@ TEST_GEN_PROGS_x86 += x86/hyperv_cpuid
TEST_GEN_PROGS_x86 += x86/hyperv_evmcs
TEST_GEN_PROGS_x86 += x86/hyperv_extended_hypercalls
TEST_GEN_PROGS_x86 += x86/hyperv_features
+TEST_GEN_PROGS_x86 += x86/hyperv_forward_hcall
TEST_GEN_PROGS_x86 += x86/hyperv_ipi
TEST_GEN_PROGS_x86 += x86/hyperv_svm_test
TEST_GEN_PROGS_x86 += x86/hyperv_tlb_flush
diff --git a/tools/testing/selftests/kvm/x86/hyperv_forward_hcall.c b/tools/testing/selftests/kvm/x86/hyperv_forward_hcall.c
new file mode 100644
index 000000000000..739cdc4c9cf4
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/hyperv_forward_hcall.c
@@ -0,0 +1,395 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Test KVM_CAP_HYPERV_FORWARD_HCALL: the feature mask KVM reports and
+ * accepts, Hyper-V hypercalls that KVM does not implement exiting to
+ * userspace in memory-based and fast form, with userspace supplying the
+ * result and the XMM output, an extended hypercall exiting in fast form,
+ * and userspace leaving a hypercall uncompleted through the exit's 'ret'
+ * field: with KVM_INSN_UD and KVM_INSN_GP, so that KVM raises the
+ * exception; with KVM_INSN_RESUME alone, so that the guest re-executes the
+ * hypercall; with KVM_INSN_RESUME and a #NM queued through
+ * KVM_SET_VCPU_EVENTS, so that the hypercall takes that instead; and with
+ * a reserved value, which KVM_RUN refuses. A hypercall which is left
+ * uncompleted leaves RAX alone.
+ *
+ * Copyright © 2026 Amazon.com, Inc. or its affiliates.
+ */
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+#include "hyperv.h"
+
+/* A hypercall code KVM does not implement (HvCallGetVpRegisters). */
+#define HVCALL_TEST_CODE HVCALL_GET_VP_REGISTERS
+
+#define FAST_PARAM0 0x1122334455667788ULL
+#define FAST_PARAM1 0x99aabbccddeeff00ULL
+#define XMM_IN_MARKER 0x5157ca11c0ffee00ULL
+#define XMM_OUT_MARKER 0x0de1ba5eba5eba11ULL
+#define USERSPACE_STATUS 0x55AA
+/* Written with a hypercall which is left uncompleted: must never arrive. */
+#define POISON_STATUS 0xDEAD
+/* What __hyperv_hypercall() loads into EAX, where the result would go. */
+#define UNWRITTEN_STATUS ((u32)-EFAULT)
+#define FULL_RESULT (BIT_ULL(63) | USERSPACE_STATUS)
+
+enum {
+ STAGE_DISABLED = 1,
+ STAGE_MEMORY,
+ STAGE_FAST,
+ STAGE_EXT_FAST,
+ STAGE_RESULT_FULL,
+ STAGE_RET_UD,
+ STAGE_RET_GP,
+ STAGE_RET_QUEUED,
+ STAGE_RET_RETRY,
+ STAGE_AFTER_RET,
+ STAGE_REDISABLED,
+};
+
+static void guest_code(gpa_t pgs_gpa)
+{
+ __sse128_u in, out;
+ u64 status;
+ u8 vector;
+
+ wrmsr(HV_X64_MSR_GUEST_OS_ID, HYPERV_LINUX_OS_ID);
+ wrmsr(HV_X64_MSR_HYPERCALL, pgs_gpa);
+
+ /* Nothing enabled: KVM fails the call itself. */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status & 0xffff, HV_STATUS_INVALID_HYPERCALL_CODE);
+
+ /* As it does an extended hypercall in fast form. */
+ vector = __hyperv_hypercall(HV_EXT_CALL_QUERY_CAPABILITIES |
+ HV_HYPERCALL_FAST_BIT,
+ FAST_PARAM0, FAST_PARAM1, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status & 0xffff, HV_STATUS_INVALID_PARAMETER);
+ GUEST_SYNC(STAGE_DISABLED);
+
+ /*
+ * Forwarding enabled: userspace supplies the status. It also sets
+ * 'ret', which KVM ignores until KVM_HYPERV_HCALL_RET is enabled.
+ */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status, USERSPACE_STATUS);
+ GUEST_SYNC(STAGE_MEMORY);
+
+ /*
+ * Fast form: the register parameters and XMM0 reach userspace, and
+ * the XMM1 value userspace writes reaches the guest.
+ */
+ in.as_u64[0] = XMM_IN_MARKER;
+ in.as_u64[1] = XMM_IN_MARKER + 1;
+ out.as_u64[0] = 0;
+ out.as_u64[1] = 0;
+ write_sse_reg(0, &in.vec);
+ write_sse_reg(1, &out.vec);
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE | HV_HYPERCALL_FAST_BIT,
+ FAST_PARAM0, FAST_PARAM1, &status);
+ read_sse_reg(1, &out.vec);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status, USERSPACE_STATUS);
+ GUEST_ASSERT_EQ(out.as_u64[0], XMM_OUT_MARKER);
+ GUEST_ASSERT_EQ(out.as_u64[1], XMM_OUT_MARKER + 1);
+ GUEST_SYNC(STAGE_FAST);
+
+ /* An extended hypercall in fast form reaches userspace too. */
+ vector = __hyperv_hypercall(HV_EXT_CALL_QUERY_CAPABILITIES |
+ HV_HYPERCALL_FAST_BIT,
+ FAST_PARAM0, FAST_PARAM1, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status, USERSPACE_STATUS);
+ GUEST_SYNC(STAGE_EXT_FAST);
+
+ /* The result reaches the guest as all 64 bits userspace wrote. */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status, FULL_RESULT);
+ GUEST_SYNC(STAGE_RESULT_FULL);
+
+ /* Userspace asks for #UD, then for #GP: KVM raises it at the call. */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT_EQ(vector, UD_VECTOR);
+ GUEST_ASSERT_EQ((u32)status, UNWRITTEN_STATUS);
+ GUEST_SYNC(STAGE_RET_UD);
+
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT_EQ(vector, GP_VECTOR);
+ GUEST_ASSERT_EQ((u32)status, UNWRITTEN_STATUS);
+ GUEST_SYNC(STAGE_RET_GP);
+
+ /* Userspace leaves the call alone and queues #NM: taken there. */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT_EQ(vector, NM_VECTOR);
+ GUEST_ASSERT_EQ((u32)status, UNWRITTEN_STATUS);
+ GUEST_SYNC(STAGE_RET_QUEUED);
+
+ /*
+ * Userspace leaves the call alone without queueing anything, and
+ * then has KVM_RUN refuse a reserved value: this one hypercall
+ * re-executes and exits to userspace each time, until userspace
+ * completes it.
+ */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status, USERSPACE_STATUS);
+ GUEST_SYNC(STAGE_RET_RETRY);
+
+ /* An ordinary completion still works after those. */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status, USERSPACE_STATUS);
+ GUEST_SYNC(STAGE_AFTER_RET);
+
+ /* Everything disabled again. */
+ vector = __hyperv_hypercall(HVCALL_TEST_CODE, pgs_gpa + PAGE_SIZE,
+ pgs_gpa + 2 * PAGE_SIZE, &status);
+ GUEST_ASSERT(!vector);
+ GUEST_ASSERT_EQ(status & 0xffff, HV_STATUS_INVALID_HYPERCALL_CODE);
+ GUEST_SYNC(STAGE_REDISABLED);
+
+ GUEST_DONE();
+}
+
+static void check_hcall_exit(struct kvm_vcpu *vcpu, u64 expect_control,
+ u64 expect_in, u64 expect_out)
+{
+ struct kvm_run *run = vcpu->run;
+
+ TEST_ASSERT_EQ(run->exit_reason, KVM_EXIT_HYPERV);
+ TEST_ASSERT_EQ(run->hyperv.type, KVM_EXIT_HYPERV_HCALL);
+ TEST_ASSERT_EQ(run->hyperv.u.hcall.input, expect_control);
+ TEST_ASSERT_EQ(run->hyperv.u.hcall.params[0], expect_in);
+ TEST_ASSERT_EQ(run->hyperv.u.hcall.params[1], expect_out);
+ /* KVM hands over every exit as one which completes. */
+ TEST_ASSERT_EQ(run->hyperv.u.hcall.ret, KVM_INSN_COMPLETE);
+}
+
+/*
+ * Leave the hypercall uncompleted with @ret, optionally queueing a #NM to
+ * be delivered at the (unadvanced) hypercall instruction. The result
+ * which userspace wrote must never reach the guest.
+ */
+static void leave_hcall(struct kvm_vcpu *vcpu, u8 ret, bool queue_nm)
+{
+ struct kvm_vcpu_events events;
+
+ vcpu->run->hyperv.u.hcall.ret = ret;
+ vcpu->run->hyperv.u.hcall.result = POISON_STATUS;
+ if (!queue_nm)
+ return;
+
+ vcpu_events_get(vcpu, &events);
+ events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
+ events.exception.pending = 1;
+ events.exception.injected = 0;
+ events.exception.nr = NM_VECTOR;
+ events.exception.has_error_code = 0;
+ events.exception_has_payload = 0;
+ vcpu_events_set(vcpu, &events);
+}
+
+static void handle_fast_hcall(struct kvm_vcpu *vcpu)
+{
+ struct kvm_fpu fpu;
+
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE | HV_HYPERCALL_FAST_BIT,
+ FAST_PARAM0, FAST_PARAM1);
+
+ vcpu_fpu_get(vcpu, &fpu);
+ TEST_ASSERT_EQ(*(u64 *)&fpu.xmm[0][0], XMM_IN_MARKER);
+ TEST_ASSERT_EQ(*(u64 *)&fpu.xmm[0][8], XMM_IN_MARKER + 1);
+ *(u64 *)&fpu.xmm[1][0] = XMM_OUT_MARKER;
+ *(u64 *)&fpu.xmm[1][8] = XMM_OUT_MARKER + 1;
+ vcpu_fpu_set(vcpu, &fpu);
+
+ vcpu->run->hyperv.u.hcall.result = USERSPACE_STATUS;
+}
+
+static void test_feature_mask(struct kvm_vm *vm)
+{
+ u64 supported = kvm_check_cap(KVM_CAP_HYPERV_FORWARD_HCALL);
+ int r;
+
+ TEST_ASSERT(supported & KVM_HYPERV_HCALL_FORWARD_UNKNOWN,
+ "KVM_HYPERV_HCALL_FORWARD_UNKNOWN not reported");
+ TEST_ASSERT(supported & KVM_HYPERV_HCALL_RET,
+ "KVM_HYPERV_HCALL_RET not reported");
+ r = __vm_enable_cap(vm, KVM_CAP_HYPERV_FORWARD_HCALL, BIT_ULL(63));
+ TEST_ASSERT(r && errno == EINVAL,
+ "Enabling an undefined feature should fail with EINVAL");
+
+ /* Enabling nothing is allowed. */
+ vm_enable_cap(vm, KVM_CAP_HYPERV_FORWARD_HCALL, 0);
+}
+
+int main(int argc, char *argv[])
+{
+ struct kvm_vcpu *vcpu;
+ struct kvm_vm *vm;
+ gva_t hcall_page;
+ gpa_t hcall_gpa;
+ struct ucall uc;
+ int stage = STAGE_DISABLED;
+ int retries = 0;
+ struct kvm_regs regs;
+ u64 rip = 0, rax = 0;
+
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_HYPERV_FORWARD_HCALL));
+ TEST_REQUIRE(kvm_check_cap(KVM_CAP_HYPERV_FORWARD_HCALL) &
+ KVM_HYPERV_HCALL_RET);
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_EXCEPTION_PAYLOAD));
+
+ vm = vm_create_with_one_vcpu(&vcpu, guest_code);
+ vcpu_set_hv_cpuid(vcpu);
+ vm_enable_cap(vm, KVM_CAP_EXCEPTION_PAYLOAD, 1);
+
+ test_feature_mask(vm);
+
+ /* Hypercall page plus an input and an output page. */
+ hcall_page = vm_alloc_pages(vm, 3);
+ memset(addr_gva2hva(vm, hcall_page), 0x0, 3 * getpagesize());
+ hcall_gpa = addr_gva2gpa(vm, hcall_page);
+
+ vcpu_args_set(vcpu, 1, hcall_gpa);
+
+ for (;;) {
+ vcpu_run(vcpu);
+
+ if (vcpu->run->exit_reason == KVM_EXIT_HYPERV) {
+ switch (stage) {
+ case STAGE_MEMORY:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ vcpu->run->hyperv.u.hcall.result = USERSPACE_STATUS;
+ /* Not enabled yet: this must change nothing. */
+ vcpu->run->hyperv.u.hcall.ret = KVM_INSN_RESUME;
+ break;
+ case STAGE_FAST:
+ handle_fast_hcall(vcpu);
+ break;
+ case STAGE_EXT_FAST:
+ check_hcall_exit(vcpu,
+ HV_EXT_CALL_QUERY_CAPABILITIES |
+ HV_HYPERCALL_FAST_BIT,
+ FAST_PARAM0, FAST_PARAM1);
+ vcpu->run->hyperv.u.hcall.result = USERSPACE_STATUS;
+ break;
+ case STAGE_RESULT_FULL:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ vcpu->run->hyperv.u.hcall.result = FULL_RESULT;
+ break;
+ case STAGE_RET_UD:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ leave_hcall(vcpu, KVM_INSN_UD, false);
+ break;
+ case STAGE_RET_GP:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ leave_hcall(vcpu, KVM_INSN_GP, false);
+ break;
+ case STAGE_RET_QUEUED:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ leave_hcall(vcpu, KVM_INSN_RESUME, true);
+ break;
+ case STAGE_RET_RETRY:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ vcpu_regs_get(vcpu, ®s);
+ switch (retries++) {
+ case 0:
+ /*
+ * Nothing queued: the same hypercall
+ * must exit again, from the same RIP
+ * and with RAX as it was.
+ */
+ rip = regs.rip;
+ rax = regs.rax;
+ leave_hcall(vcpu, KVM_INSN_RESUME, false);
+ break;
+ case 1:
+ /* Refused, and the same again. */
+ TEST_ASSERT_EQ(regs.rip, rip);
+ TEST_ASSERT_EQ(regs.rax, rax);
+ leave_hcall(vcpu, KVM_INSN_RESUME + 1, false);
+ TEST_ASSERT(__vcpu_run(vcpu) == -1 &&
+ errno == EINVAL,
+ "KVM_RUN accepted a reserved 'ret'");
+ break;
+ default:
+ TEST_ASSERT_EQ(regs.rip, rip);
+ TEST_ASSERT_EQ(regs.rax, rax);
+ vcpu->run->hyperv.u.hcall.result = USERSPACE_STATUS;
+ break;
+ }
+ break;
+ case STAGE_AFTER_RET:
+ check_hcall_exit(vcpu, HVCALL_TEST_CODE,
+ hcall_gpa + getpagesize(),
+ hcall_gpa + 2 * getpagesize());
+ vcpu->run->hyperv.u.hcall.result = USERSPACE_STATUS;
+ break;
+ default:
+ TEST_FAIL("Unexpected hypercall exit in stage %d", stage);
+ }
+ continue;
+ }
+
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+ switch (get_ucall(vcpu, &uc)) {
+ case UCALL_SYNC:
+ TEST_ASSERT_EQ(uc.args[1], stage);
+ switch (stage) {
+ case STAGE_DISABLED:
+ vm_enable_cap(vm, KVM_CAP_HYPERV_FORWARD_HCALL,
+ KVM_HYPERV_HCALL_FORWARD_UNKNOWN);
+ break;
+ case STAGE_MEMORY:
+ vm_enable_cap(vm, KVM_CAP_HYPERV_FORWARD_HCALL,
+ KVM_HYPERV_HCALL_FORWARD_UNKNOWN |
+ KVM_HYPERV_HCALL_RET);
+ break;
+ case STAGE_AFTER_RET:
+ vm_enable_cap(vm, KVM_CAP_HYPERV_FORWARD_HCALL, 0);
+ break;
+ }
+ stage++;
+ break;
+ case UCALL_ABORT:
+ REPORT_GUEST_ASSERT(uc);
+ case UCALL_DONE:
+ goto done;
+ default:
+ TEST_FAIL("Unhandled ucall: %ld", uc.cmd);
+ }
+ }
+
+done:
+ TEST_ASSERT_EQ(stage, STAGE_REDISABLED + 1);
+ /* The call left alone came back twice: left, refused, completed. */
+ TEST_ASSERT_EQ(retries, 3);
+ kvm_vm_free(vm);
+ return 0;
+}
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 09/15] KVM: x86: Add a per-vCPU register write filter
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (7 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 08/15] KVM: selftests: Add Hyper-V hypercall forwarding test David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 10/15] KVM: x86: Filter emulated CR0 and CR4 writes David Woodhouse
` (5 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Let userspace veto guest register writes.
KVM_X86_SET_REG_WRITE_FILTER arms a mask on one register, and a write
which changes a masked bit exits with KVM_EXIT_X86_REG_WRITE first.
KVM_RUN means userspace performed it, and retires the instruction,
unless 'ret' says otherwise.
Only XCR0, which L2 shares, so KVM's XSETBV for L2 is filtered
too. Without NextRIP the emulator raises the exit.
VMs with encrypted memory or protected state are refused, as is moving
an SEV context into a VM with filters armed.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 103 ++++++++++++++-
arch/x86/include/asm/kvm_host.h | 12 ++
arch/x86/include/uapi/asm/kvm.h | 13 ++
arch/x86/kvm/emulate.c | 5 +
arch/x86/kvm/kvm_emulate.h | 8 ++
arch/x86/kvm/regs.h | 21 +++
arch/x86/kvm/svm/sev.c | 22 +++
arch/x86/kvm/svm/svm.c | 21 ++-
arch/x86/kvm/vmx/vmx.c | 8 +-
arch/x86/kvm/x86.c | 228 +++++++++++++++++++++++++++++++-
arch/x86/kvm/x86.h | 2 +-
include/uapi/linux/kvm.h | 14 ++
12 files changed, 449 insertions(+), 8 deletions(-)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index ea48247c2976..561d90c3b2d8 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -6788,6 +6788,67 @@ if the guest_memfd memory was pinned in IOMMU page tables.
See also: :ref:`KVM_SET_MEMORY_ATTRIBUTES`.
+4.147 KVM_X86_SET_REG_WRITE_FILTER
+----------------------------------
+
+:Capability: KVM_CAP_X86_REG_WRITE_FILTER
+:Architectures: x86
+:Type: vcpu ioctl
+:Parameters: struct kvm_x86_reg_write_filter
+:Returns: 0 on success, < 0 on error
+
+::
+
+ struct kvm_x86_reg_write_filter {
+ __u32 reg; /* KVM_X86_REG_FILTER_* */
+ __u32 flags; /* must be zero */
+ __u64 mask; /* trigger bits; zero disarms the filter */
+ __u64 reserved[5];
+ };
+
+Arms (or, with a zero mask, disarms) a write filter on one register of
+the vCPU. While a filter is armed, a write executed by the guest that
+changes any register bit set in ``mask`` does not take effect; the vCPU
+takes a KVM_EXIT_X86_REG_WRITE exit carrying the old and new values, and
+userspace decides what happens instead. See the KVM_EXIT_X86_REG_WRITE
+documentation for the exit protocol.
+
+KVM_CHECK_EXTENSION on KVM_CAP_X86_REG_WRITE_FILTER returns a bitmask of
+the register classes the host can filter, ``BIT(KVM_X86_REG_FILTER_*)``,
+and zero on the fd of a VM on which no filter can be armed (see below).
+The classes are:
+
+ ========================== ============================================
+ KVM_X86_REG_FILTER_XCR0 XCR0, written by XSETBV
+ ========================== ============================================
+
+Only writes executed by the guest are filtered. Writes from userspace
+(KVM_SET_SREGS, KVM_SET_XCRS and similar) and state loaded by RSM, INIT
+or SIPI do not trigger the filter. Writes executed by a nested guest do
+not trigger the filter, whether or not L1 intercepts them: they change
+the nested guest's register. XCR0 is the exception, because L1 and its
+nested guest share it: an XSETBV which L1 lets the nested guest execute
+is filtered like L1's own, and the exit is then taken with
+KVM_RUN_X86_GUEST_MODE set in kvm_run.flags.
+
+Writes executed in System Management Mode do not trigger the filter
+either: SMM code is platform firmware, above the filter's protection
+scope. That holds only as far as the guest cannot run code of its own
+in SMM. KVM delivers an SMI which the guest sends itself through its
+local APIC, and RSM loads control registers from the SMM state-save
+area, so a VMM which arms a filter against the guest's kernel has to
+keep that kernel out of SMRAM, with the SMM address space
+(KVM_CAP_MULTI_ADDRESS_SPACE) and firmware which locks it.
+
+The ioctl fails with -EINVAL if ``reg`` or any ``mask`` bit is not
+supported, or if ``flags`` or ``reserved`` are not zero.
+
+No filter can be armed on a VM whose guest memory is encrypted or whose
+register state is protected (SEV, SEV-ES, SEV-SNP, TDX): KVM cannot
+decode the instructions of such a guest. The ioctl fails with -EINVAL
+there, and KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM fails with -EINVAL while a
+vCPU of the destination VM has a filter armed.
+
.. _kvm_run:
5. The kvm_run structure
@@ -6963,8 +7024,8 @@ to the byte array.
.. note::
For KVM_EXIT_IO, KVM_EXIT_MMIO, KVM_EXIT_OSI, KVM_EXIT_PAPR, KVM_EXIT_XEN,
- KVM_EXIT_EPR, KVM_EXIT_HYPERCALL, KVM_EXIT_TDX,
- KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR the corresponding
+ KVM_EXIT_EPR, KVM_EXIT_HYPERCALL, KVM_EXIT_TDX, KVM_EXIT_X86_RDMSR,
+ KVM_EXIT_X86_WRMSR and KVM_EXIT_X86_REG_WRITE the corresponding
operations are complete (and guest state is consistent) only after userspace
has re-entered the kernel with KVM_RUN. The kernel side will first finish
incomplete operations and then check for pending signals.
@@ -7785,6 +7846,44 @@ The supported 'ret' values and their respective SW_EXITINFO2 encodings:
a KVM-defined hypervisor value, as allowed by the GHCB)
====== =============================================================
+::
+
+ /* KVM_EXIT_X86_REG_WRITE */
+ struct {
+ __u8 insn_len; /* of the instruction which wrote */
+ __u8 ret; /* in: KVM_INSN_* */
+ __u8 pad[2];
+ __u32 reg; /* KVM_X86_REG_FILTER_* */
+ __u64 old_value;
+ __u64 new_value;
+ } reg_write;
+
+Used on x86 systems. The guest executed a write, to a register with a
+write filter armed by KVM_X86_SET_REG_WRITE_FILTER, that changes at
+least one of the filtered bits. The write has not taken effect and the
+instruction has not retired: RIP still points at it. ``reg`` identifies
+the register, ``old_value`` its current contents, ``new_value`` the
+value the guest tried to write and ``insn_len`` the length in bytes of
+the instruction, which is always valid and never zero. The exit is
+taken before KVM validates the write: ``new_value`` may be one for which
+the instruction would have faulted. ``pad`` is reserved and is zero.
+Userspace writes nothing to the structure but ``ret``.
+
+The exit needs completion. KVM does not perform the write, ever, and
+sets ``ret`` to zero, KVM_INSN_COMPLETE. Re-entering the vCPU with
+``ret`` still zero tells KVM that userspace has performed the write, or
+as much of it as the guest is to see, with KVM_SET_SREGS2, KVM_SET_XCRS
+or whatever sets the register: KVM retires the instruction as if it had
+executed and does not touch the register.
+
+For anything else, userspace sets ``ret`` to another of the KVM_INSN_*
+values (see :ref:`the description of completion <kvm_insn_action>`)
+before it re-enters the vCPU, and the instruction does not complete.
+KVM_INSN_GP refuses the write: KVM injects #GP(0), as the CPU does for a
+value it does not accept. KVM_INSN_UD injects #UD, as the CPU does for
+an instruction it does not have. With KVM_INSN_RESUME KVM does nothing,
+for a VMM which queues another exception, moves RIP itself, or hands the
+write to something else to decide.
.. _cap_enable:
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index dcb0ce584f02..437e89ca93e1 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -220,6 +220,9 @@ enum x86_intercept_stage;
#define KVM_NR_DB_REGS 4
+/* Register classes KVM_X86_SET_REG_WRITE_FILTER knows about */
+#define KVM_X86_NR_REG_WRITE_FILTERS (KVM_X86_REG_FILTER_XCR0 + 1)
+
#define PFERR_PRESENT_MASK BIT(0)
#define PFERR_WRITE_MASK BIT(1)
#define PFERR_USER_MASK BIT(2)
@@ -264,6 +267,8 @@ struct kvm_caps {
u32 max_guest_tsc_khz;
/* number of bits of the fractional part of the TSC scaling ratio */
u8 tsc_scaling_ratio_frac_bits;
+ /* bit mask of KVM_X86_REG_FILTER_* register classes */
+ u32 supported_reg_write_filter;
/* maximum allowed value of TSC scaling ratio */
u64 max_tsc_scaling_ratio;
/* 1ull << kvm_caps.tsc_scaling_ratio_frac_bits */
@@ -860,6 +865,13 @@ struct kvm_vcpu_arch {
unsigned long cui_linear_rip;
int cui_rdmsr_imm_reg;
+ /*
+ * KVM_X86_SET_REG_WRITE_FILTER state: a bitmask of armed register
+ * classes and the per-register trigger masks.
+ */
+ u32 reg_write_filter_armed;
+ u64 reg_write_filter[KVM_X86_NR_REG_WRITE_FILTERS];
+
gpa_t time;
s8 pvclock_tsc_shift;
u32 pvclock_tsc_mul;
diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kvm.h
index 00ce265391e1..5a16a2ce4399 100644
--- a/arch/x86/include/uapi/asm/kvm.h
+++ b/arch/x86/include/uapi/asm/kvm.h
@@ -230,6 +230,19 @@ struct kvm_msr_filter {
struct kvm_msr_filter_range ranges[KVM_MSR_FILTER_MAX_RANGES];
};
+/* Register classes for KVM_X86_SET_REG_WRITE_FILTER */
+#define KVM_X86_REG_FILTER_CR0 0
+#define KVM_X86_REG_FILTER_CR4 1
+#define KVM_X86_REG_FILTER_XCR0 2
+
+/* for KVM_X86_SET_REG_WRITE_FILTER */
+struct kvm_x86_reg_write_filter {
+ __u32 reg; /* KVM_X86_REG_FILTER_* */
+ __u32 flags; /* must be zero */
+ __u64 mask; /* trigger bits; zero disarms the filter */
+ __u64 reserved[5];
+};
+
struct kvm_cpuid_entry {
__u32 function;
__u32 eax;
diff --git a/arch/x86/kvm/emulate.c b/arch/x86/kvm/emulate.c
index c1b21282187f..465b7d402f75 100644
--- a/arch/x86/kvm/emulate.c
+++ b/arch/x86/kvm/emulate.c
@@ -3784,6 +3784,7 @@ static int em_fxrstor(struct x86_emulate_ctxt *ctxt)
static int em_xsetbv(struct x86_emulate_ctxt *ctxt)
{
u32 eax, ecx, edx;
+ int rc;
if (!(ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSXSAVE))
return emulate_ud(ctxt);
@@ -3792,6 +3793,10 @@ static int em_xsetbv(struct x86_emulate_ctxt *ctxt)
edx = reg_read(ctxt, VCPU_REGS_RDX);
ecx = reg_read(ctxt, VCPU_REGS_RCX);
+ rc = ctxt->ops->filter_xcr_write(ctxt, ecx, ((u64)edx << 32) | eax);
+ if (rc != X86EMUL_CONTINUE)
+ return rc;
+
if (ctxt->ops->set_xcr(ctxt, ecx, ((u64)edx << 32) | eax))
return emulate_gp(ctxt, 0);
diff --git a/arch/x86/kvm/kvm_emulate.h b/arch/x86/kvm/kvm_emulate.h
index 10886bea82c9..5e18c0cc7f60 100644
--- a/arch/x86/kvm/kvm_emulate.h
+++ b/arch/x86/kvm/kvm_emulate.h
@@ -246,6 +246,14 @@ struct x86_emulate_ops {
int (*get_xcr)(struct x86_emulate_ctxt *ctxt, u32 index, u64 *xcr);
int (*set_xcr)(struct x86_emulate_ctxt *ctxt, u32 index, u64 xcr);
+ /*
+ * Called by XSETBV before ->set_xcr(). Anything but
+ * X86EMUL_CONTINUE means that a register write filter took the
+ * write: the handler returns it and makes no change.
+ */
+ int (*filter_xcr_write)(struct x86_emulate_ctxt *ctxt, u32 index,
+ u64 xcr);
+
gva_t (*get_untagged_addr)(struct x86_emulate_ctxt *ctxt, gva_t addr,
unsigned int flags);
diff --git a/arch/x86/kvm/regs.h b/arch/x86/kvm/regs.h
index 97c17b120a57..9fbd6c37bf68 100644
--- a/arch/x86/kvm/regs.h
+++ b/arch/x86/kvm/regs.h
@@ -65,6 +65,27 @@ unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu);
void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw);
int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);
+int kvm_vcpu_ioctl_set_reg_write_filter(struct kvm_vcpu *vcpu,
+ struct kvm_x86_reg_write_filter *filter);
+bool __kvm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg, u64 changed_bits);
+void kvm_reg_write_user_space(struct kvm_vcpu *vcpu, u32 reg, u64 old_value,
+ u64 new_value, u8 insn_len);
+
+/*
+ * Does a guest write of @new_value to @reg take a KVM_EXIT_X86_REG_WRITE
+ * exit? Must be called before the write is performed, from a path that
+ * handles a write the guest itself executed; host-initiated writes are
+ * never filtered.
+ */
+static inline bool kvm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg,
+ u64 old_value, u64 new_value)
+{
+ if (likely(!(vcpu->arch.reg_write_filter_armed & BIT(reg))))
+ return false;
+
+ return __kvm_reg_write_filtered(vcpu, reg, old_value ^ new_value);
+}
+
static inline bool is_long_mode(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_X86_64
diff --git a/arch/x86/kvm/svm/sev.c b/arch/x86/kvm/svm/sev.c
index b90c5f14c1ac..62c66e0f6448 100644
--- a/arch/x86/kvm/svm/sev.c
+++ b/arch/x86/kvm/svm/sev.c
@@ -2149,6 +2149,24 @@ static int sev_check_source_vcpus(struct kvm *dst, struct kvm *src)
return 0;
}
+/*
+ * The destination becomes an SEV guest, which cannot have register write
+ * filters (KVM_X86_SET_REG_WRITE_FILTER refuses to arm them). Refuse the
+ * move while any destination vCPU has one armed; the VMM can disarm first.
+ */
+static int sev_check_dest_reg_write_filters(struct kvm *dst)
+{
+ struct kvm_vcpu *vcpu;
+ unsigned long i;
+
+ kvm_for_each_vcpu(i, vcpu, dst) {
+ if (vcpu->arch.reg_write_filter_armed)
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
{
struct kvm_sev_info *dst_sev = to_kvm_sev_info(kvm);
@@ -2198,6 +2216,10 @@ int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
if (ret)
goto out_source_vcpu;
+ ret = sev_check_dest_reg_write_filters(kvm);
+ if (ret)
+ goto out_source_vcpu;
+
/*
* Allocate a new have_run_cpus for the destination, i.e. don't copy
* the set of CPUs from the source. If a CPU was used to run a vCPU in
diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index e30ee80624b7..4ffb41234dc2 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -2604,6 +2604,25 @@ static int rsm_interception(struct kvm_vcpu *vcpu)
return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
}
+/*
+ * The length of the instruction whose intercept is being handled, or zero
+ * where the CPU does not tell (no NextRIP).
+ */
+static u8 svm_exit_insn_len(struct kvm_vcpu *vcpu)
+{
+ struct vcpu_svm *svm = to_svm(vcpu);
+
+ if (!nrips || !svm->vmcb->control.next_rip)
+ return 0;
+
+ return svm->vmcb->control.next_rip - kvm_rip_read(vcpu);
+}
+
+static int xsetbv_interception(struct kvm_vcpu *vcpu)
+{
+ return kvm_emulate_xsetbv(vcpu, svm_exit_insn_len(vcpu));
+}
+
static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
unsigned long val)
{
@@ -3496,7 +3515,7 @@ static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
[SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
[SVM_EXIT_MONITOR] = kvm_emulate_monitor,
[SVM_EXIT_MWAIT] = kvm_emulate_mwait,
- [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
+ [SVM_EXIT_XSETBV] = xsetbv_interception,
[SVM_EXIT_ICEBP] = icebp_interception,
[SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
[SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c
index 82eb891f684c..aeae8eedd19f 100644
--- a/arch/x86/kvm/vmx/vmx.c
+++ b/arch/x86/kvm/vmx/vmx.c
@@ -6143,6 +6143,12 @@ static int handle_monitor_trap(struct kvm_vcpu *vcpu)
return 1;
}
+static int handle_xsetbv(struct kvm_vcpu *vcpu)
+{
+ /* The length is for the exit which a register write filter takes. */
+ return kvm_emulate_xsetbv(vcpu, vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
+}
+
static int handle_invpcid(struct kvm_vcpu *vcpu)
{
u32 vmx_instruction_info;
@@ -6339,7 +6345,7 @@ static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
[EXIT_REASON_APIC_WRITE] = handle_apic_write,
[EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
[EXIT_REASON_WBINVD] = kvm_emulate_wbinvd,
- [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv,
+ [EXIT_REASON_XSETBV] = handle_xsetbv,
[EXIT_REASON_TASK_SWITCH] = handle_task_switch,
[EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
[EXIT_REASON_GDTR_IDTR] = handle_desc,
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index da22e7d9cacd..b559c7880e54 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -742,11 +742,106 @@ int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
}
EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_set_xcr);
-int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
+bool __kvm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg, u64 changed_bits)
{
+ /*
+ * The filter covers the vCPU itself. A write performed by or on
+ * behalf of a nested guest is applied normally; whether it exits
+ * is L1's business. Not so for XCR0, which L1 and L2 share: an
+ * XSETBV which L1 lets L2 make changes L1's register too. Writes
+ * in SMM are platform firmware's, above the filter's protection
+ * scope; they are applied normally too.
+ */
+ if (is_smm(vcpu))
+ return false;
+
+ if (is_guest_mode(vcpu) && reg != KVM_X86_REG_FILTER_XCR0)
+ return false;
+
+ return changed_bits & vcpu->arch.reg_write_filter[reg];
+}
+
+/*
+ * KVM_RUN after KVM_EXIT_X86_REG_WRITE: userspace has performed the write,
+ * or as much of it as it wants the guest to see, so all that is left is to
+ * retire the instruction, as for an MSR access which userspace completed.
+ * Userspace which wants anything else says that the instruction does not
+ * complete: KVM refuses the write with #GP or #UD, or leaves it alone.
+ *
+ * Returns 1 if that was all, 0 if the instruction is to be retired, or
+ * -EINVAL.
+ */
+static int kvm_reg_write_uncompleted(struct kvm_vcpu *vcpu)
+{
+ return kvm_insn_uncompleted(vcpu, READ_ONCE(vcpu->run->reg_write.ret));
+}
+
+static int complete_fast_reg_write(struct kvm_vcpu *vcpu)
+{
+ int r = kvm_reg_write_uncompleted(vcpu);
+
+ if (r)
+ return r;
+
+ return kvm_skip_emulated_instruction(vcpu);
+}
+
+static void kvm_fill_reg_write_exit(struct kvm_vcpu *vcpu, u32 reg,
+ u64 old_value, u64 new_value, u8 insn_len)
+{
+ struct kvm_run *run = vcpu->run;
+
+ run->exit_reason = KVM_EXIT_X86_REG_WRITE;
+ memset(&run->reg_write, 0, sizeof(run->reg_write));
+ run->reg_write.insn_len = insn_len;
+ run->reg_write.reg = reg;
+ run->reg_write.old_value = old_value;
+ run->reg_write.new_value = new_value;
+}
+
+/*
+ * Exit to userspace with a write that passed kvm_reg_write_filtered(), made
+ * by an instruction of @insn_len bytes whose intercept is being handled.
+ * The write is not performed and the instruction does not retire: RIP is
+ * left pointing at it, and the completion retires it once userspace has
+ * performed the write.
+ */
+void kvm_reg_write_user_space(struct kvm_vcpu *vcpu, u32 reg, u64 old_value,
+ u64 new_value, u8 insn_len)
+{
+ kvm_fill_reg_write_exit(vcpu, reg, old_value, new_value, insn_len);
+ vcpu->arch.complete_userspace_io = complete_fast_reg_write;
+}
+
+int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu, u8 insn_len)
+{
+ u32 index = kvm_ecx_read(vcpu);
+ u64 xcr = kvm_read_edx_eax(vcpu);
+
/* Note, #UD due to CR4.OSXSAVE=0 has priority over the intercept. */
- if (kvm_x86_call(get_cpl)(vcpu) != 0 ||
- __kvm_set_xcr(vcpu, kvm_ecx_read(vcpu), kvm_read_edx_eax(vcpu))) {
+ if (kvm_x86_call(get_cpl)(vcpu) != 0) {
+ kvm_inject_gp(vcpu, 0);
+ return 1;
+ }
+
+ if (index == XCR_XFEATURE_ENABLED_MASK &&
+ kvm_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_XCR0,
+ vcpu->arch.xcr0, xcr)) {
+ /*
+ * The exit reports the length of the instruction. Where
+ * the intercept does not provide it, let the emulator
+ * raise the exit, as it does for an XSETBV which it meets
+ * by itself.
+ */
+ if (!insn_len)
+ return kvm_emulate_instruction(vcpu, 0);
+
+ kvm_reg_write_user_space(vcpu, KVM_X86_REG_FILTER_XCR0,
+ vcpu->arch.xcr0, xcr, insn_len);
+ return 0;
+ }
+
+ if (__kvm_set_xcr(vcpu, index, xcr)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
@@ -755,6 +850,65 @@ int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu)
}
EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_xsetbv);
+/*
+ * KVM cannot decode the instructions of a guest whose memory is encrypted
+ * (has_protected_page_tables: every SEV and TDX guest), for the length
+ * which the exit reports, and a guest whose register state is protected
+ * does not report its writes the way the filter needs.
+ */
+static bool kvm_reg_write_filter_possible(struct kvm *kvm)
+{
+ return !kvm->arch.has_protected_state &&
+ !kvm->arch.has_protected_page_tables;
+}
+
+int kvm_vcpu_ioctl_set_reg_write_filter(struct kvm_vcpu *vcpu,
+ struct kvm_x86_reg_write_filter *filter)
+{
+ u64 allowed;
+
+ if (filter->flags)
+ return -EINVAL;
+
+ if (memchr_inv(filter->reserved, 0, sizeof(filter->reserved)))
+ return -EINVAL;
+
+ if (filter->reg >= KVM_X86_NR_REG_WRITE_FILTERS ||
+ !(kvm_caps.supported_reg_write_filter & BIT(filter->reg)))
+ return -EINVAL;
+
+ filter->reg = array_index_nospec(filter->reg,
+ KVM_X86_NR_REG_WRITE_FILTERS);
+
+ if (!kvm_reg_write_filter_possible(vcpu->kvm))
+ return -EINVAL;
+
+ switch (filter->reg) {
+ case KVM_X86_REG_FILTER_CR0:
+ allowed = ~CR0_RESERVED_BITS;
+ break;
+ case KVM_X86_REG_FILTER_CR4:
+ allowed = ~CR4_RESERVED_BITS;
+ break;
+ case KVM_X86_REG_FILTER_XCR0:
+ allowed = kvm_caps.supported_xcr0 | XFEATURE_MASK_FP;
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ if (filter->mask & ~allowed)
+ return -EINVAL;
+
+ vcpu->arch.reg_write_filter[filter->reg] = filter->mask;
+ if (filter->mask)
+ vcpu->arch.reg_write_filter_armed |= BIT(filter->reg);
+ else
+ vcpu->arch.reg_write_filter_armed &= ~BIT(filter->reg);
+
+ return 0;
+}
+
void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid)
{
struct kvm_mmu *mmu = vcpu->arch.mmu;
@@ -2414,6 +2568,12 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
case KVM_CAP_PMU_CAPABILITY:
r = enable_pmu ? KVM_CAP_PMU_VALID_MASK : 0;
break;
+ case KVM_CAP_X86_REG_WRITE_FILTER:
+ if (kvm && !kvm_reg_write_filter_possible(kvm))
+ r = 0;
+ else
+ r = kvm_caps.supported_reg_write_filter;
+ break;
case KVM_CAP_DISABLE_QUIRKS2:
r = kvm_caps.supported_quirks;
break;
@@ -3889,6 +4049,15 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
case KVM_SET_DEVICE_ATTR:
r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
break;
+ case KVM_X86_SET_REG_WRITE_FILTER: {
+ struct kvm_x86_reg_write_filter filter;
+
+ r = -EFAULT;
+ if (copy_from_user(&filter, argp, sizeof(filter)))
+ goto out;
+ r = kvm_vcpu_ioctl_set_reg_write_filter(vcpu, &filter);
+ break;
+ }
case KVM_MEMORY_ENCRYPT_OP:
r = -ENOTTY;
if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
@@ -5628,6 +5797,55 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
return res;
}
+/*
+ * The emulator raised the exit, so the emulator retires the instruction it
+ * decoded, as it does for an emulated MSR access which userspace completed,
+ * unless userspace says that the instruction does not complete.
+ */
+static int complete_emulated_reg_write(struct kvm_vcpu *vcpu)
+{
+ int r = kvm_reg_write_uncompleted(vcpu);
+
+ if (r)
+ return r;
+
+ return kvm_emulate_instruction(vcpu, EMULTYPE_NO_DECODE | EMULTYPE_SKIP |
+ EMULTYPE_COMPLETE_USER_EXIT);
+}
+
+/*
+ * Exit to userspace with a filtered write which the emulator met, before
+ * it has any effect.
+ */
+static int emulator_reg_write_exit(struct x86_emulate_ctxt *ctxt, u32 reg,
+ u64 old_value, u64 new_value)
+{
+ struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
+
+ kvm_fill_reg_write_exit(vcpu, reg, old_value, new_value,
+ ctxt->_eip - ctxt->eip);
+ vcpu->arch.complete_userspace_io = complete_emulated_reg_write;
+ return X86EMUL_IO_NEEDED;
+}
+
+/*
+ * Divert an emulated XSETBV into a KVM_EXIT_X86_REG_WRITE exit when it hits
+ * a write filter, before it has any effect.
+ */
+static int emulator_filter_xcr_write(struct x86_emulate_ctxt *ctxt, u32 index,
+ u64 xcr)
+{
+ struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
+
+ if (index != XCR_XFEATURE_ENABLED_MASK ||
+ !kvm_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_XCR0,
+ vcpu->arch.xcr0, xcr))
+ return X86EMUL_CONTINUE;
+
+ return emulator_reg_write_exit(ctxt, KVM_X86_REG_FILTER_XCR0,
+ vcpu->arch.xcr0, xcr);
+}
+
static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
{
return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
@@ -5925,6 +6143,7 @@ static const struct x86_emulate_ops emulate_ops = {
.triple_fault = emulator_triple_fault,
.get_xcr = emulator_get_xcr,
.set_xcr = emulator_set_xcr,
+ .filter_xcr_write = emulator_filter_xcr_write,
.get_untagged_addr = emulator_get_untagged_addr,
.is_canonical_addr = emulator_is_canonical_addr,
.page_address_valid = emulator_page_address_valid,
@@ -7152,6 +7371,9 @@ int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
if (boot_cpu_has(X86_FEATURE_XSAVE)) {
kvm_host.xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
kvm_caps.supported_xcr0 = kvm_host.xcr0 & KVM_SUPPORTED_XCR0;
+ /* XSETBV exits unconditionally on both VMX and SVM. */
+ kvm_caps.supported_reg_write_filter |=
+ BIT(KVM_X86_REG_FILTER_XCR0);
}
if (boot_cpu_has(X86_FEATURE_XSAVES)) {
diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h
index 7e5ccbce9114..2e900788f707 100644
--- a/arch/x86/kvm/x86.h
+++ b/arch/x86/kvm/x86.h
@@ -496,7 +496,7 @@ int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
int reason, bool has_error_code, u32 error_code);
int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr);
-int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu);
+int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu, u8 insn_len);
int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu);
int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu);
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index e480544a3746..165fa36c2479 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -199,6 +199,7 @@ struct kvm_exit_snp_req_certs {
#define KVM_EXIT_ARM_SEA 41
#define KVM_EXIT_ARM_LDST64B 42
#define KVM_EXIT_SNP_REQ_CERTS 43
+#define KVM_EXIT_X86_REG_WRITE 44
/* For KVM_EXIT_INTERNAL_ERROR */
/* Emulate instruction failed. */
@@ -512,6 +513,15 @@ struct kvm_run {
} arm_sea;
/* KVM_EXIT_SNP_REQ_CERTS */
struct kvm_exit_snp_req_certs snp_req_certs;
+ /* KVM_EXIT_X86_REG_WRITE */
+ struct {
+ __u8 insn_len; /* of the instruction which wrote */
+ __u8 ret; /* in: KVM_INSN_* */
+ __u8 pad[2];
+ __u32 reg; /* KVM_X86_REG_FILTER_* */
+ __u64 old_value;
+ __u64 new_value;
+ } reg_write;
/* Fix the size of the union. */
char padding[256];
};
@@ -1017,6 +1027,7 @@ struct kvm_enable_cap {
#define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252
#define KVM_CAP_X86_MSR_EXIT_INSN 253
#define KVM_CAP_HYPERV_FORWARD_HCALL 254
+#define KVM_CAP_X86_REG_WRITE_FILTER 255
struct kvm_irq_routing_irqchip {
__u32 irqchip;
@@ -1707,4 +1718,7 @@ struct kvm_pre_fault_memory {
__u64 padding[5];
};
+/* Available with KVM_CAP_X86_REG_WRITE_FILTER */
+#define KVM_X86_SET_REG_WRITE_FILTER _IOW(KVMIO, 0xd6, struct kvm_x86_reg_write_filter)
+
#endif /* __LINUX_KVM_H */
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 10/15] KVM: x86: Filter emulated CR0 and CR4 writes
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (8 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 09/15] KVM: x86: Add a per-vCPU register write filter David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:48 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 11/15] KVM: VMX: Support CR0 and CR4 write filters David Woodhouse
` (4 subsequent siblings)
14 siblings, 1 reply; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
MOV to CR, CLTS and LMSW can reach the emulator instead of the vendor
fast paths. Check the filter in those three handlers, not in
->set_cr(), which RSM and task switches use too.
The emulator retires what it raised, as it does for XSETBV. Nothing
can arm a CR0 or CR4 filter yet: the vendor patches which follow
advertise them, and SVM leans on the emulator where it lacks decode
assists or NextRIP.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
arch/x86/kvm/emulate.c | 21 +++++++++++++++++++--
arch/x86/kvm/kvm_emulate.h | 10 ++++++++++
arch/x86/kvm/x86.c | 37 +++++++++++++++++++++++++++++++++++++
3 files changed, 66 insertions(+), 2 deletions(-)
diff --git a/arch/x86/kvm/emulate.c b/arch/x86/kvm/emulate.c
index 465b7d402f75..9a4aebcccc95 100644
--- a/arch/x86/kvm/emulate.c
+++ b/arch/x86/kvm/emulate.c
@@ -3252,6 +3252,10 @@ static int em_cr_write(struct x86_emulate_ctxt *ctxt)
int cr_num = ctxt->modrm_reg;
int r;
+ r = ctxt->ops->filter_cr_write(ctxt, cr_num, ctxt->src.val);
+ if (r != X86EMUL_CONTINUE)
+ return r;
+
if (ctxt->ops->set_cr(ctxt, cr_num, ctxt->src.val))
return emulate_gp(ctxt, 0);
@@ -3409,9 +3413,15 @@ static int em_invlpg(struct x86_emulate_ctxt *ctxt)
static int em_clts(struct x86_emulate_ctxt *ctxt)
{
ulong cr0;
+ int r;
cr0 = ctxt->ops->get_cr(ctxt, 0);
cr0 &= ~X86_CR0_TS;
+
+ r = ctxt->ops->filter_cr_write(ctxt, 0, cr0);
+ if (r != X86EMUL_CONTINUE)
+ return r;
+
ctxt->ops->set_cr(ctxt, 0, cr0);
return X86EMUL_CONTINUE;
}
@@ -3512,8 +3522,15 @@ static int em_smsw(struct x86_emulate_ctxt *ctxt)
static int em_lmsw(struct x86_emulate_ctxt *ctxt)
{
- ctxt->ops->set_cr(ctxt, 0, (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul)
- | (ctxt->src.val & 0x0f));
+ ulong cr0 = (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul) |
+ (ctxt->src.val & 0x0f);
+ int r;
+
+ r = ctxt->ops->filter_cr_write(ctxt, 0, cr0);
+ if (r != X86EMUL_CONTINUE)
+ return r;
+
+ ctxt->ops->set_cr(ctxt, 0, cr0);
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
diff --git a/arch/x86/kvm/kvm_emulate.h b/arch/x86/kvm/kvm_emulate.h
index 5e18c0cc7f60..311ff6a01079 100644
--- a/arch/x86/kvm/kvm_emulate.h
+++ b/arch/x86/kvm/kvm_emulate.h
@@ -214,6 +214,16 @@ struct x86_emulate_ops {
void (*set_idt)(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt);
ulong (*get_cr)(struct x86_emulate_ctxt *ctxt, int cr);
int (*set_cr)(struct x86_emulate_ctxt *ctxt, int cr, ulong val);
+ /*
+ * Check a guest control register write against the vCPU's write
+ * filters (KVM_X86_SET_REG_WRITE_FILTER) before performing it.
+ * Returns X86EMUL_CONTINUE when the write is to be applied, or
+ * X86EMUL_IO_NEEDED after setting up a KVM_EXIT_X86_REG_WRITE exit;
+ * the emulation is then abandoned with no architectural effect, and
+ * the exit's completion retires the instruction.
+ */
+ int (*filter_cr_write)(struct x86_emulate_ctxt *ctxt, int cr,
+ ulong val);
int (*cpl)(struct x86_emulate_ctxt *ctxt);
ulong (*get_effective_dr7)(struct x86_emulate_ctxt *ctxt);
ulong (*get_dr)(struct x86_emulate_ctxt *ctxt, int dr);
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index b559c7880e54..4e6f0cb80288 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -5846,6 +5846,42 @@ static int emulator_filter_xcr_write(struct x86_emulate_ctxt *ctxt, u32 index,
vcpu->arch.xcr0, xcr);
}
+/*
+ * Divert an emulated CR0/CR4 write into a KVM_EXIT_X86_REG_WRITE exit when
+ * it hits a write filter. Called by the instruction handlers (MOV to CR,
+ * CLTS, LMSW) before any architectural effect; state loads that reach
+ * ->set_cr() on other instructions' behalf (RSM, task switches) are not
+ * guest register writes and stay unfiltered.
+ */
+static int emulator_filter_cr_write(struct x86_emulate_ctxt *ctxt, int cr,
+ ulong val)
+{
+ struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
+ u64 old_value, new_value;
+ u32 reg;
+
+ switch (cr) {
+ case 0:
+ reg = KVM_X86_REG_FILTER_CR0;
+ old_value = kvm_read_cr0(vcpu);
+ break;
+ case 4:
+ reg = KVM_X86_REG_FILTER_CR4;
+ old_value = kvm_read_cr4(vcpu);
+ break;
+ default:
+ return X86EMUL_CONTINUE;
+ }
+
+ /* Match the merge emulator_set_cr() will do with the same value. */
+ new_value = mk_cr_64(old_value, val);
+
+ if (!kvm_reg_write_filtered(vcpu, reg, old_value, new_value))
+ return X86EMUL_CONTINUE;
+
+ return emulator_reg_write_exit(ctxt, reg, old_value, new_value);
+}
+
static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
{
return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
@@ -6118,6 +6154,7 @@ static const struct x86_emulate_ops emulate_ops = {
.set_idt = emulator_set_idt,
.get_cr = emulator_get_cr,
.set_cr = emulator_set_cr,
+ .filter_cr_write = emulator_filter_cr_write,
.cpl = emulator_get_cpl,
.get_effective_dr7 = emulator_get_effective_dr7,
.get_dr = emulator_get_dr,
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 11/15] KVM: VMX: Support CR0 and CR4 write filters
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (9 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 10/15] KVM: x86: Filter emulated CR0 and CR4 writes David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 12/15] KVM: SVM: " David Woodhouse
` (3 subsequent siblings)
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Add the vendor hook which applies a changed filter. VMX makes filtered
bits host-owned in vmcs01 so that writes to them exit, and checks the
filter in handle_cr(). CLTS can exit again, so it is only a KVM_BUG
when no filter explains it. When bits change owner, read them from the
guest first and refresh the read shadows.
L2 is not filtered. With a CR4 filter armed, nested entry recomputes
CR4 ownership for a clean vmcs12 too, which prepare_vmcs02_rare() skips.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 28 ++++++--
arch/x86/include/asm/kvm-x86-ops.h | 1 +
arch/x86/include/asm/kvm_host.h | 7 ++
arch/x86/kvm/vmx/main.c | 13 ++++
arch/x86/kvm/vmx/nested.c | 27 +++++--
arch/x86/kvm/vmx/vmx.c | 109 +++++++++++++++++++++++++++--
arch/x86/kvm/vmx/vmx.h | 14 +++-
arch/x86/kvm/vmx/x86_ops.h | 1 +
arch/x86/kvm/x86.c | 3 +
9 files changed, 187 insertions(+), 16 deletions(-)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index 561d90c3b2d8..a5192d1ca599 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -6819,16 +6819,19 @@ and zero on the fd of a VM on which no filter can be armed (see below).
The classes are:
========================== ============================================
+ KVM_X86_REG_FILTER_CR0 CR0, written by MOV to CR0, CLTS and LMSW
+ KVM_X86_REG_FILTER_CR4 CR4, written by MOV to CR4
KVM_X86_REG_FILTER_XCR0 XCR0, written by XSETBV
========================== ============================================
Only writes executed by the guest are filtered. Writes from userspace
-(KVM_SET_SREGS, KVM_SET_XCRS and similar) and state loaded by RSM, INIT
-or SIPI do not trigger the filter. Writes executed by a nested guest do
-not trigger the filter, whether or not L1 intercepts them: they change
-the nested guest's register. XCR0 is the exception, because L1 and its
-nested guest share it: an XSETBV which L1 lets the nested guest execute
-is filtered like L1's own, and the exit is then taken with
+(KVM_SET_SREGS, KVM_SET_XCRS and similar), CR0/CR4 loads performed as
+part of VM entry and VM exit of a nested guest, and state loaded by RSM,
+INIT or SIPI do not trigger the filter. Writes executed by a nested
+guest do not trigger the filter, whether or not L1 intercepts them: they
+change the nested guest's register. XCR0 is the exception, because L1
+and its nested guest share it: an XSETBV which L1 lets the nested guest
+execute is filtered like L1's own, and the exit is then taken with
KVM_RUN_X86_GUEST_MODE set in kvm_run.flags.
Writes executed in System Management Mode do not trigger the filter
@@ -6840,6 +6843,19 @@ area, so a VMM which arms a filter against the guest's kernel has to
keep that kernel out of SMRAM, with the SMM address space
(KVM_CAP_MULTI_ADDRESS_SPACE) and firmware which locks it.
+Nor does a control register load which the guest brings about without
+writing the register. A hardware task switch sets CR0.TS; it can only
+set that bit, and there is no task switch in 64-bit mode, so a filter on
+CR0.PG keeps it away from a 64-bit guest. With VMX exposed to the
+guest, a nested VM-exit loads CR0 and CR4 from the host-state fields of
+the VMCS, which the guest writes. A VMM which arms a CR0 or CR4 filter
+against the guest's kernel has to accept those, or not expose VMX.
+
+Filtering a CR0 or CR4 bit that KVM otherwise lets the guest own (for
+example CR0.TS) forces interception of writes to that register, with the
+attendant cost on write-heavy bits; the per-bit mask exists so that only
+the bits userspace actually cares about pay it.
+
The ioctl fails with -EINVAL if ``reg`` or any ``mask`` bit is not
supported, or if ``flags`` or ``reserved`` are not zero.
diff --git a/arch/x86/include/asm/kvm-x86-ops.h b/arch/x86/include/asm/kvm-x86-ops.h
index 4dde4e3e608a..1e98d1c98303 100644
--- a/arch/x86/include/asm/kvm-x86-ops.h
+++ b/arch/x86/include/asm/kvm-x86-ops.h
@@ -143,6 +143,7 @@ KVM_X86_OP(check_emulate_instruction)
KVM_X86_OP(apic_init_signal_blocked)
KVM_X86_OP_OPTIONAL(enable_l2_tlb_flush)
KVM_X86_OP_OPTIONAL(migrate_timers)
+KVM_X86_OP_OPTIONAL(update_reg_write_filter)
KVM_X86_OP(recalc_intercepts)
KVM_X86_OP(complete_emulated_msr)
KVM_X86_OP(vcpu_deliver_sipi_vector)
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 437e89ca93e1..3e0365f5557a 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1745,6 +1745,13 @@ struct kvm_x86_ops {
int (*enable_l2_tlb_flush)(struct kvm_vcpu *vcpu);
void (*migrate_timers)(struct kvm_vcpu *vcpu);
+
+ /*
+ * A register write filter changed: bring the interception which the
+ * armed filters need in line with vcpu->arch.reg_write_filter.
+ */
+ void (*update_reg_write_filter)(struct kvm_vcpu *vcpu);
+
void (*recalc_intercepts)(struct kvm_vcpu *vcpu);
int (*complete_emulated_msr)(struct kvm_vcpu *vcpu, int err);
diff --git a/arch/x86/kvm/vmx/main.c b/arch/x86/kvm/vmx/main.c
index d75170a6199e..f902b0afabc9 100644
--- a/arch/x86/kvm/vmx/main.c
+++ b/arch/x86/kvm/vmx/main.c
@@ -219,6 +219,18 @@ static int vt_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
return vmx_complete_emulated_msr(vcpu, err);
}
+static void vt_update_reg_write_filter(struct kvm_vcpu *vcpu)
+{
+ /*
+ * KVM_X86_SET_REG_WRITE_FILTER refuses to arm a filter on a VM with
+ * protected state, so there is never anything to apply for TDX.
+ */
+ if (is_td_vcpu(vcpu))
+ return;
+
+ vmx_update_reg_write_filter(vcpu);
+}
+
#ifdef CONFIG_KVM_SMM
static int vt_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
{
@@ -1137,6 +1149,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
.check_emulate_instruction = vt_op(check_emulate_instruction),
.apic_init_signal_blocked = vt_op(apic_init_signal_blocked),
.migrate_timers = vmx_migrate_timers,
+ .update_reg_write_filter = vt_op(update_reg_write_filter),
.recalc_intercepts = vt_op(recalc_intercepts),
.complete_emulated_msr = vt_op(complete_emulated_msr),
diff --git a/arch/x86/kvm/vmx/nested.c b/arch/x86/kvm/vmx/nested.c
index 879183c1bfa5..cd1083b2c344 100644
--- a/arch/x86/kvm/vmx/nested.c
+++ b/arch/x86/kvm/vmx/nested.c
@@ -2805,9 +2805,24 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
* trap. Note that CR0.TS also needs updating - we do this later.
*/
vmx_update_exception_bitmap(vcpu);
- vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
+ /*
+ * Recompute from scratch rather than narrowing the current (vmcs01)
+ * value: a register write filter (KVM_X86_SET_REG_WRITE_FILTER)
+ * forces its bits host-owned there, but covers only L1's writes.
+ */
+ vcpu->arch.cr0_guest_owned_bits = vmx_guest_owned_cr0_bits() &
+ ~vmcs12->cr0_guest_host_mask;
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
+ /*
+ * Likewise for CR4, which prepare_vmcs02_rare() computes only when
+ * vmcs12 is dirty: the nested VM-exit left L1's set behind, which
+ * with a filter armed has fewer bits than vmcs02 lets L2 own, and
+ * KVM would then not read such a bit back from GUEST_CR4.
+ */
+ if (vcpu->arch.reg_write_filter[KVM_X86_REG_FILTER_CR4])
+ set_cr4_guest_host_mask(vmx);
+
if (vcpu->arch.nested_run_pending &&
(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
@@ -4823,10 +4838,11 @@ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
* Note that calling vmx_set_cr0 is important, even if cr0 hasn't
* actually changed, because vmx_set_cr0 refers to efer set above.
*
- * CR0_GUEST_HOST_MASK is already set in the original vmcs01
- * (KVM doesn't change it);
+ * CR0_GUEST_HOST_MASK is already correct in vmcs01:
+ * __nested_vmx_vmexit() refreshed it after switching back, in case
+ * a register write filter changed while vmcs02 was loaded.
*/
- vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
+ vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits(vcpu);
vmx_set_cr0(vcpu, vmcs12->host_cr0);
/* Same as above - no reason to call set_cr4_guest_host_mask(). */
@@ -4992,7 +5008,7 @@ static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
*/
vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
- vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
+ vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits(vcpu);
vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
@@ -5172,6 +5188,7 @@ void __nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
* Update any VMCS fields that might have changed while vmcs02 was the
* active VMCS. The tracking is per-vCPU, not per-VMCS.
*/
+ vmx_refresh_reg_write_filter(vcpu);
vmcs_write32(VM_EXIT_MSR_STORE_COUNT, vmx->msr_autostore.nr);
vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c
index aeae8eedd19f..d785bcf52a3f 100644
--- a/arch/x86/kvm/vmx/vmx.c
+++ b/arch/x86/kvm/vmx/vmx.c
@@ -4563,12 +4563,69 @@ void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS;
vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS;
}
- if (is_guest_mode(&vmx->vcpu))
+ if (is_guest_mode(&vmx->vcpu)) {
vcpu->arch.cr4_guest_owned_bits &=
~get_vmcs12(vcpu)->cr4_guest_host_mask;
+ } else {
+ /*
+ * A write filter (KVM_X86_SET_REG_WRITE_FILTER) forces
+ * interception of L1's writes to the filtered bits. It
+ * covers only L1, so the vmcs02 mask is left alone.
+ */
+ vcpu->arch.cr4_guest_owned_bits &=
+ ~vcpu->arch.reg_write_filter[KVM_X86_REG_FILTER_CR4];
+ }
vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
}
+/*
+ * Refresh the interception that the register write filter needs: a
+ * filtered CR0/CR4 bit must be host-owned in the vmcs01 guest/host masks
+ * so that the guest's writes to it actually exit. For vmcs01, which must
+ * be loaded.
+ *
+ * This is all a nested VM-exit needs, for a filter which changed while
+ * vmcs02 was loaded: it loads L1's CR0 and CR4 afresh.
+ */
+void vmx_refresh_reg_write_filter(struct kvm_vcpu *vcpu)
+{
+ vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits(vcpu);
+ vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
+ set_cr4_guest_host_mask(to_vmx(vcpu));
+}
+
+/*
+ * A filter changed. While vmcs02 is loaded there is nothing to do yet:
+ * __nested_vmx_vmexit() refreshes vmcs01 after switching back.
+ */
+void vmx_update_reg_write_filter(struct kvm_vcpu *vcpu)
+{
+ struct vcpu_vmx *vmx = to_vmx(vcpu);
+ unsigned long cr0, cr4;
+
+ if (vmx->loaded_vmcs != &vmx->vmcs01)
+ return;
+
+ /*
+ * The guest changes the bits it owns without an exit, and KVM reads
+ * them back from GUEST_CR0/GUEST_CR4 only on demand, and only those
+ * it knows the guest to own. Read them all before any changes
+ * owner, or the cached value of such a bit stays stale for ever.
+ */
+ cr0 = kvm_read_cr0(vcpu);
+ cr4 = kvm_read_cr4(vcpu);
+
+ vmx_refresh_reg_write_filter(vcpu);
+
+ /*
+ * The guest reads a bit which the host owns from the read shadow,
+ * and CLTS and LMSW exit or not by it: it has to hold the current
+ * value of the bits which the host has just taken.
+ */
+ vmcs_writel(CR0_READ_SHADOW, cr0);
+ vmcs_writel(CR4_READ_SHADOW, cr4);
+}
+
static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
{
u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
@@ -4976,7 +5033,7 @@ static void init_vmcs(struct kvm_vcpu *vcpu)
/* 22.2.1, 20.8.1 */
vm_entry_controls_set(vmx, vmx_get_initial_vmentry_ctrl());
- vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits();
+ vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits(vcpu);
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
set_cr4_guest_host_mask(vmx);
@@ -5680,6 +5737,21 @@ static int handle_desc(struct kvm_vcpu *vcpu)
return kvm_emulate_instruction(vcpu, 0);
}
+/*
+ * Send an intercepted write which a register write filter catches to
+ * userspace instead of performing it.
+ */
+static bool vmx_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg,
+ unsigned long old, unsigned long val)
+{
+ if (!kvm_reg_write_filtered(vcpu, reg, old, val))
+ return false;
+
+ kvm_reg_write_user_space(vcpu, reg, old, val,
+ vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
+ return true;
+}
+
static int handle_cr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification, val;
@@ -5697,6 +5769,9 @@ static int handle_cr(struct kvm_vcpu *vcpu)
trace_kvm_cr_write(cr, val);
switch (cr) {
case 0:
+ if (vmx_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_CR0,
+ kvm_read_cr0(vcpu), val))
+ return 0;
err = handle_set_cr0(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 3:
@@ -5705,6 +5780,9 @@ static int handle_cr(struct kvm_vcpu *vcpu)
err = kvm_set_cr3(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 4:
+ if (vmx_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_CR4,
+ kvm_read_cr4(vcpu), val))
+ return 0;
err = handle_set_cr4(vcpu, val);
return kvm_complete_insn_gp(vcpu, err);
case 8: {
@@ -5727,8 +5805,23 @@ static int handle_cr(struct kvm_vcpu *vcpu)
}
break;
case 2: /* clts */
- KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS");
- return -EIO;
+ val = kvm_read_cr0(vcpu);
+ /* Trace the write whether or not it is filtered, as for MOV. */
+ trace_kvm_cr_write(0, val & ~X86_CR0_TS);
+ if (vmx_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_CR0,
+ val, val & ~X86_CR0_TS))
+ return 0;
+ /*
+ * The guest owns CR0.TS unless a write filter on it forced
+ * it host-owned, and the filter never reaches into vmcs02.
+ */
+ if (KVM_BUG(is_guest_mode(vcpu) ||
+ !(vcpu->arch.reg_write_filter[KVM_X86_REG_FILTER_CR0] &
+ X86_CR0_TS), vcpu->kvm, "Unexpected CLTS exit"))
+ return -EIO;
+
+ err = kvm_set_cr0(vcpu, val & ~X86_CR0_TS);
+ return kvm_complete_insn_gp(vcpu, err);
case 1: /*mov from cr*/
switch (cr) {
case 3:
@@ -5748,6 +5841,10 @@ static int handle_cr(struct kvm_vcpu *vcpu)
case 3: /* lmsw */
val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val));
+ if (vmx_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_CR0,
+ kvm_read_cr0(vcpu),
+ kvm_read_cr0_bits(vcpu, ~0x0eul) | val))
+ return 0;
kvm_lmsw(vcpu, val);
return kvm_skip_emulated_instruction(vcpu);
@@ -8648,6 +8745,10 @@ __init int vmx_hardware_setup(void)
kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
+ /* The guest/host masks can force any CR0/CR4 bit host-owned. */
+ kvm_caps.supported_reg_write_filter |= BIT(KVM_X86_REG_FILTER_CR0) |
+ BIT(KVM_X86_REG_FILTER_CR4);
+
set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
if (enable_ept)
diff --git a/arch/x86/kvm/vmx/vmx.h b/arch/x86/kvm/vmx/vmx.h
index 74cd50f29fa4..80b17d69f9c1 100644
--- a/arch/x86/kvm/vmx/vmx.h
+++ b/arch/x86/kvm/vmx/vmx.h
@@ -315,6 +315,7 @@ int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer);
void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
void set_cr4_guest_host_mask(struct vcpu_vmx *vmx);
+void vmx_refresh_reg_write_filter(struct kvm_vcpu *vcpu);
void ept_save_pdptrs(struct kvm_vcpu *vcpu);
void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
@@ -592,7 +593,7 @@ BUILD_CONTROLS_SHADOW(tertiary_exec, TERTIARY_VM_EXEC_CONTROL, 64)
BIT(VCPU_REG_EXIT_INFO_1) | \
BIT(VCPU_REG_EXIT_INFO_2))
-static inline unsigned long vmx_l1_guest_owned_cr0_bits(void)
+static inline unsigned long vmx_guest_owned_cr0_bits(void)
{
unsigned long bits = KVM_POSSIBLE_CR0_GUEST_BITS;
@@ -610,6 +611,17 @@ static inline unsigned long vmx_l1_guest_owned_cr0_bits(void)
return bits;
}
+static inline unsigned long vmx_l1_guest_owned_cr0_bits(struct kvm_vcpu *vcpu)
+{
+ /*
+ * A write filter (KVM_X86_SET_REG_WRITE_FILTER) forces interception
+ * of L1's writes to the filtered bits. It covers only L1:
+ * prepare_vmcs02() computes the nested masks without it.
+ */
+ return vmx_guest_owned_cr0_bits() &
+ ~vcpu->arch.reg_write_filter[KVM_X86_REG_FILTER_CR0];
+}
+
static __always_inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
{
return container_of(kvm, struct kvm_vmx, kvm);
diff --git a/arch/x86/kvm/vmx/x86_ops.h b/arch/x86/kvm/vmx/x86_ops.h
index cd72684d075d..0da766f1998f 100644
--- a/arch/x86/kvm/vmx/x86_ops.h
+++ b/arch/x86/kvm/vmx/x86_ops.h
@@ -45,6 +45,7 @@ int vmx_check_intercept(struct kvm_vcpu *vcpu,
struct x86_exception *exception);
bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu);
void vmx_migrate_timers(struct kvm_vcpu *vcpu);
+void vmx_update_reg_write_filter(struct kvm_vcpu *vcpu);
void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu);
void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr);
int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu);
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 4e6f0cb80288..7fe4b559ed73 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -760,6 +760,7 @@ bool __kvm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg, u64 changed_bits)
return changed_bits & vcpu->arch.reg_write_filter[reg];
}
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_reg_write_filtered);
/*
* KVM_RUN after KVM_EXIT_X86_REG_WRITE: userspace has performed the write,
@@ -812,6 +813,7 @@ void kvm_reg_write_user_space(struct kvm_vcpu *vcpu, u32 reg, u64 old_value,
kvm_fill_reg_write_exit(vcpu, reg, old_value, new_value, insn_len);
vcpu->arch.complete_userspace_io = complete_fast_reg_write;
}
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_reg_write_user_space);
int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu, u8 insn_len)
{
@@ -906,6 +908,7 @@ int kvm_vcpu_ioctl_set_reg_write_filter(struct kvm_vcpu *vcpu,
else
vcpu->arch.reg_write_filter_armed &= ~BIT(filter->reg);
+ kvm_x86_call(update_reg_write_filter)(vcpu);
return 0;
}
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 12/15] KVM: SVM: Support CR0 and CR4 write filters
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (10 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 11/15] KVM: VMX: Support CR0 and CR4 write filters David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:49 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 13/15] KVM: x86: Add descriptor-table registers to the write filter David Woodhouse
` (2 subsequent siblings)
14 siblings, 1 reply; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Keep INTERCEPT_CR0_WRITE set in vmcb01 while a CR0 filter is armed,
and check the filter in cr_interception(). Without NextRIP the write
goes to the emulator, which knows the instruction length. L2 is not
filtered.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
arch/x86/kvm/svm/svm.c | 66 +++++++++++++++++++++++++++++++++++++++++-
1 file changed, 65 insertions(+), 1 deletion(-)
diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index 4ffb41234dc2..c91467a59e20 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -1135,6 +1135,22 @@ static void svm_recalc_intercepts(struct kvm_vcpu *vcpu)
svm_recalc_msr_intercepts(vcpu);
}
+static void svm_update_reg_write_filter(struct kvm_vcpu *vcpu)
+{
+ struct vcpu_svm *svm = to_svm(vcpu);
+
+ /*
+ * CR4 writes are always intercepted. CR0 writes are not when the
+ * guest and host views agree (hcr0 == cr0): force the intercept in
+ * vmcb01 while a CR0 filter is armed. Disarming leaves the
+ * intercept in place - a forced intercept only costs exits, which
+ * cr_interception() handles as usual - and the next svm_set_cr0(),
+ * which respects the filter, restores its own state.
+ */
+ if (vcpu->arch.reg_write_filter_armed & BIT(KVM_X86_REG_FILTER_CR0))
+ svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
+}
+
static void init_vmcb(struct kvm_vcpu *vcpu, bool init_event)
{
struct vcpu_svm *svm = to_svm(vcpu);
@@ -1867,7 +1883,13 @@ void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
if (hcr0 == cr0) {
/* Selective CR0 write remains on. */
svm_clr_intercept(svm, INTERCEPT_CR0_READ);
- svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
+ /*
+ * The selective intercept misses writes that change only
+ * TS or MP, and CLTS: a CR0 write filter needs them all.
+ */
+ if (!(vcpu->arch.reg_write_filter_armed &
+ BIT(KVM_X86_REG_FILTER_CR0)))
+ svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
} else {
svm_set_intercept(svm, INTERCEPT_CR0_READ);
svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
@@ -2647,6 +2669,21 @@ static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
#define CR_VALID (1ULL << 63)
+/*
+ * Send an intercepted write which a register write filter catches to
+ * userspace instead of performing it. The caller has checked that the
+ * length of the instruction is known.
+ */
+static bool svm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg,
+ unsigned long old, unsigned long val)
+{
+ if (!kvm_reg_write_filtered(vcpu, reg, old, val))
+ return false;
+
+ kvm_reg_write_user_space(vcpu, reg, old, val, svm_exit_insn_len(vcpu));
+ return true;
+}
+
static int cr_interception(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
@@ -2660,6 +2697,16 @@ static int cr_interception(struct kvm_vcpu *vcpu)
if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
return emulate_on_interception(vcpu);
+ /*
+ * A filtered write reports the length of its instruction, which only
+ * NextRIP provides here. Without it, let the emulator raise the exit,
+ * as it does without Decode Assists.
+ */
+ if ((vcpu->arch.reg_write_filter_armed &
+ (BIT(KVM_X86_REG_FILTER_CR0) | BIT(KVM_X86_REG_FILTER_CR4))) &&
+ !svm_exit_insn_len(vcpu))
+ return emulate_on_interception(vcpu);
+
reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
@@ -2673,6 +2720,14 @@ static int cr_interception(struct kvm_vcpu *vcpu)
trace_kvm_cr_write(cr, val);
switch (cr) {
case 0:
+ /*
+ * The filter never triggers in guest mode and the
+ * selective-CR0 reflection only applies there, so
+ * the order of the two checks does not matter.
+ */
+ if (svm_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_CR0,
+ kvm_read_cr0(vcpu), val))
+ return 0;
if (!check_selective_cr0_intercepted(vcpu, val))
err = kvm_set_cr0(vcpu, val);
else
@@ -2683,6 +2738,9 @@ static int cr_interception(struct kvm_vcpu *vcpu)
err = kvm_set_cr3(vcpu, val);
break;
case 4:
+ if (svm_reg_write_filtered(vcpu, KVM_X86_REG_FILTER_CR4,
+ kvm_read_cr4(vcpu), val))
+ return 0;
err = kvm_set_cr4(vcpu, val);
break;
case 8:
@@ -5617,6 +5675,8 @@ struct kvm_x86_ops svm_x86_ops __initdata = {
.apic_init_signal_blocked = svm_apic_init_signal_blocked,
+ .update_reg_write_filter = svm_update_reg_write_filter,
+
.recalc_intercepts = svm_recalc_intercepts,
.complete_emulated_msr = svm_complete_emulated_msr,
@@ -5722,6 +5782,10 @@ static __init void svm_set_cpu_caps(void)
if (cpu_feature_enabled(X86_FEATURE_BUS_LOCK_THRESHOLD))
kvm_caps.has_bus_lock_exit = true;
+ /* CR0/CR4 write interception can always be forced. */
+ kvm_caps.supported_reg_write_filter |= BIT(KVM_X86_REG_FILTER_CR0) |
+ BIT(KVM_X86_REG_FILTER_CR4);
+
/* CPUID 0x80000008 */
if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
boot_cpu_has(X86_FEATURE_AMD_SSBD))
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 13/15] KVM: x86: Add descriptor-table registers to the write filter
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (11 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 12/15] KVM: SVM: " David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:52 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 14/15] KVM: selftests: Add x86 register write filter test David Woodhouse
2026-11-27 15:27 ` [PATCH v3 15/15] KVM: selftests: Test the register write filter with a nested guest David Woodhouse
14 siblings, 1 reply; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Add GDTR, IDTR, LDTR and TR. These have no per-bit semantics, so the
mask must be all ones and every LGDT, LIDT, LLDT or LTR exits.
VMX uses descriptor-table exiting, which UMIP emulation must now
share. SVM uses the four load intercepts, which init_vmcb() has to
re-arm after a shutdown.
The exit gains old_limit and new_limit, for GDTR and IDTR.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
Documentation/virt/kvm/api.rst | 40 +++++++++++++++++-----
arch/x86/include/asm/kvm_host.h | 2 +-
arch/x86/include/uapi/asm/kvm.h | 4 +++
arch/x86/kvm/emulate.c | 28 +++++++++++++++
arch/x86/kvm/kvm_emulate.h | 10 ++++++
arch/x86/kvm/regs.h | 22 ++++++++++++
arch/x86/kvm/svm/nested.c | 16 +++++++++
arch/x86/kvm/svm/svm.c | 51 ++++++++++++++++++++++++++++
arch/x86/kvm/vmx/vmx.c | 60 ++++++++++++++++++++++++++++-----
arch/x86/kvm/x86.c | 51 ++++++++++++++++++++++++++++
include/uapi/linux/kvm.h | 2 ++
11 files changed, 268 insertions(+), 18 deletions(-)
diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index a5192d1ca599..3ed1b07ad849 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -6822,8 +6822,21 @@ The classes are:
KVM_X86_REG_FILTER_CR0 CR0, written by MOV to CR0, CLTS and LMSW
KVM_X86_REG_FILTER_CR4 CR4, written by MOV to CR4
KVM_X86_REG_FILTER_XCR0 XCR0, written by XSETBV
+ KVM_X86_REG_FILTER_GDTR GDTR, written by LGDT
+ KVM_X86_REG_FILTER_IDTR IDTR, written by LIDT
+ KVM_X86_REG_FILTER_LDTR LDTR, written by LLDT
+ KVM_X86_REG_FILTER_TR TR, written by LTR
========================== ============================================
+For the descriptor-table registers, ``mask`` must be all ones, or zero
+to disarm: any load of the register triggers the filter, regardless of
+the old contents (reloading the same LDT selector re-reads the
+descriptor). The exit reports the base and limit the guest tried to
+load for GDTR/IDTR, and the selector (in ``new_value``, before any
+descriptor validation) for LDTR/TR. Userspace which performs an LLDT or
+LTR itself has to read the descriptor from the guest's GDT, load the
+hidden state from it and, for LTR, mark the TSS busy.
+
Only writes executed by the guest are filtered. Writes from userspace
(KVM_SET_SREGS, KVM_SET_XCRS and similar), CR0/CR4 loads performed as
part of VM entry and VM exit of a nested guest, and state loaded by RSM,
@@ -6851,6 +6864,12 @@ guest, a nested VM-exit loads CR0 and CR4 from the host-state fields of
the VMCS, which the guest writes. A VMM which arms a CR0 or CR4 filter
against the guest's kernel has to accept those, or not expose VMX.
+The same goes for the descriptor-table registers, of which only the
+LGDT, LIDT, LLDT and LTR instructions are filtered: a hardware task
+switch loads TR and LDTR; with VMX exposed to the guest, a nested
+VM-exit loads GDTR, IDTR and TR from the host-state fields of the VMCS
+and makes LDTR unusable; and with SVM exposed, VMLOAD loads TR and LDTR.
+
Filtering a CR0 or CR4 bit that KVM otherwise lets the guest own (for
example CR0.TS) forces interception of writes to that register, with the
attendant cost on write-heavy bits; the per-bit mask exists so that only
@@ -7872,18 +7891,23 @@ The supported 'ret' values and their respective SW_EXITINFO2 encodings:
__u32 reg; /* KVM_X86_REG_FILTER_* */
__u64 old_value;
__u64 new_value;
+ __u32 old_limit; /* GDTR/IDTR only */
+ __u32 new_limit; /* GDTR/IDTR only */
} reg_write;
Used on x86 systems. The guest executed a write, to a register with a
write filter armed by KVM_X86_SET_REG_WRITE_FILTER, that changes at
-least one of the filtered bits. The write has not taken effect and the
-instruction has not retired: RIP still points at it. ``reg`` identifies
-the register, ``old_value`` its current contents, ``new_value`` the
-value the guest tried to write and ``insn_len`` the length in bytes of
-the instruction, which is always valid and never zero. The exit is
-taken before KVM validates the write: ``new_value`` may be one for which
-the instruction would have faulted. ``pad`` is reserved and is zero.
-Userspace writes nothing to the structure but ``ret``.
+least one of the filtered bits (any load, for the descriptor-table
+registers). The write has not taken effect and the instruction has not
+retired: RIP still points at it. ``reg`` identifies the register,
+``old_value`` its current contents, ``new_value`` the value the guest
+tried to write and ``insn_len`` the length in bytes of the instruction,
+which is always valid and never zero. For GDTR and IDTR the values are
+the base addresses and the ``*_limit`` fields carry the limits; for LDTR
+and TR they are the selectors. The exit is taken before KVM validates
+the write: ``new_value`` may be one for which the instruction would have
+faulted. ``pad`` is reserved and is zero. Userspace writes nothing to
+the structure but ``ret``.
The exit needs completion. KVM does not perform the write, ever, and
sets ``ret`` to zero, KVM_INSN_COMPLETE. Re-entering the vCPU with
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 3e0365f5557a..c17a7022a575 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -221,7 +221,7 @@ enum x86_intercept_stage;
#define KVM_NR_DB_REGS 4
/* Register classes KVM_X86_SET_REG_WRITE_FILTER knows about */
-#define KVM_X86_NR_REG_WRITE_FILTERS (KVM_X86_REG_FILTER_XCR0 + 1)
+#define KVM_X86_NR_REG_WRITE_FILTERS (KVM_X86_REG_FILTER_TR + 1)
#define PFERR_PRESENT_MASK BIT(0)
#define PFERR_WRITE_MASK BIT(1)
diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kvm.h
index 5a16a2ce4399..623d66ff5562 100644
--- a/arch/x86/include/uapi/asm/kvm.h
+++ b/arch/x86/include/uapi/asm/kvm.h
@@ -234,6 +234,10 @@ struct kvm_msr_filter {
#define KVM_X86_REG_FILTER_CR0 0
#define KVM_X86_REG_FILTER_CR4 1
#define KVM_X86_REG_FILTER_XCR0 2
+#define KVM_X86_REG_FILTER_GDTR 3
+#define KVM_X86_REG_FILTER_IDTR 4
+#define KVM_X86_REG_FILTER_LDTR 5
+#define KVM_X86_REG_FILTER_TR 6
/* for KVM_X86_SET_REG_WRITE_FILTER */
struct kvm_x86_reg_write_filter {
diff --git a/arch/x86/kvm/emulate.c b/arch/x86/kvm/emulate.c
index 9a4aebcccc95..b40e347c498f 100644
--- a/arch/x86/kvm/emulate.c
+++ b/arch/x86/kvm/emulate.c
@@ -3375,9 +3375,20 @@ static int em_sldt(struct x86_emulate_ctxt *ctxt)
static int em_lldt(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
+ int rc;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
+
+ /*
+ * The filter check must precede any architectural effect, and sits
+ * here rather than in ->set_segment() so that a task switch, which
+ * loads LDTR through set_segment as well, is not diverted.
+ */
+ rc = ctxt->ops->filter_dt_write(ctxt, KVM_X86_REG_FILTER_LDTR, sel, 0);
+ if (rc != X86EMUL_CONTINUE)
+ return rc;
+
return load_segment_descriptor(ctxt, sel, VCPU_SREG_LDTR);
}
@@ -3389,9 +3400,21 @@ static int em_str(struct x86_emulate_ctxt *ctxt)
static int em_ltr(struct x86_emulate_ctxt *ctxt)
{
u16 sel = ctxt->src.val;
+ int rc;
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
+
+ /*
+ * The filter check must precede load_segment_descriptor(): that
+ * path marks the TSS descriptor busy in the GDT, and the exit must
+ * leave nothing behind. Userspace performs the load itself, or
+ * leaves it uncompleted and the LTR runs again.
+ */
+ rc = ctxt->ops->filter_dt_write(ctxt, KVM_X86_REG_FILTER_TR, sel, 0);
+ if (rc != X86EMUL_CONTINUE)
+ return rc;
+
return load_segment_descriptor(ctxt, sel, VCPU_SREG_TR);
}
@@ -3489,6 +3512,11 @@ static int em_lgdt_lidt(struct x86_emulate_ctxt *ctxt, bool lgdt)
emul_is_noncanonical_address(desc_ptr.address, ctxt,
X86EMUL_F_DT_LOAD))
return emulate_gp(ctxt, 0);
+ rc = ctxt->ops->filter_dt_write(ctxt, lgdt ? KVM_X86_REG_FILTER_GDTR :
+ KVM_X86_REG_FILTER_IDTR,
+ desc_ptr.address, desc_ptr.size);
+ if (rc != X86EMUL_CONTINUE)
+ return rc;
if (lgdt)
ctxt->ops->set_gdt(ctxt, &desc_ptr);
else
diff --git a/arch/x86/kvm/kvm_emulate.h b/arch/x86/kvm/kvm_emulate.h
index 311ff6a01079..981ba90926b9 100644
--- a/arch/x86/kvm/kvm_emulate.h
+++ b/arch/x86/kvm/kvm_emulate.h
@@ -224,6 +224,16 @@ struct x86_emulate_ops {
*/
int (*filter_cr_write)(struct x86_emulate_ctxt *ctxt, int cr,
ulong val);
+ /*
+ * Likewise for a descriptor-table load: @reg is the
+ * KVM_X86_REG_FILTER_* class, @value the base (GDTR/IDTR) or
+ * selector (LDTR/TR), @limit the limit (GDTR/IDTR only). Only the
+ * LGDT/LIDT/LLDT/LTR instructions are checked; loads on other
+ * instructions' behalf (task switches, RSM) are not register
+ * writes by the guest and stay unfiltered.
+ */
+ int (*filter_dt_write)(struct x86_emulate_ctxt *ctxt, u32 reg,
+ u64 value, u32 limit);
int (*cpl)(struct x86_emulate_ctxt *ctxt);
ulong (*get_effective_dr7)(struct x86_emulate_ctxt *ctxt);
ulong (*get_dr)(struct x86_emulate_ctxt *ctxt, int dr);
diff --git a/arch/x86/kvm/regs.h b/arch/x86/kvm/regs.h
index 9fbd6c37bf68..c4509175810b 100644
--- a/arch/x86/kvm/regs.h
+++ b/arch/x86/kvm/regs.h
@@ -65,6 +65,11 @@ unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu);
void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw);
int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);
+#define KVM_REG_WRITE_FILTER_DT_MASK (BIT(KVM_X86_REG_FILTER_GDTR) | \
+ BIT(KVM_X86_REG_FILTER_IDTR) | \
+ BIT(KVM_X86_REG_FILTER_LDTR) | \
+ BIT(KVM_X86_REG_FILTER_TR))
+
int kvm_vcpu_ioctl_set_reg_write_filter(struct kvm_vcpu *vcpu,
struct kvm_x86_reg_write_filter *filter);
bool __kvm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg, u64 changed_bits);
@@ -86,6 +91,23 @@ static inline bool kvm_reg_write_filtered(struct kvm_vcpu *vcpu, u32 reg,
return __kvm_reg_write_filtered(vcpu, reg, old_value ^ new_value);
}
+/*
+ * The descriptor-table variant: any LGDT, LIDT, LLDT or LTR triggers an
+ * armed filter, regardless of the old contents.
+ */
+static inline bool kvm_dt_write_filtered(struct kvm_vcpu *vcpu, u32 reg)
+{
+ if (likely(!(vcpu->arch.reg_write_filter_armed & BIT(reg))))
+ return false;
+
+ return __kvm_reg_write_filtered(vcpu, reg, ~0ULL);
+}
+
+static inline bool kvm_reg_write_filter_dt_armed(struct kvm_vcpu *vcpu)
+{
+ return vcpu->arch.reg_write_filter_armed & KVM_REG_WRITE_FILTER_DT_MASK;
+}
+
static inline bool is_long_mode(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_X86_64
diff --git a/arch/x86/kvm/svm/nested.c b/arch/x86/kvm/svm/nested.c
index 07554089ec05..618728034472 100644
--- a/arch/x86/kvm/svm/nested.c
+++ b/arch/x86/kvm/svm/nested.c
@@ -172,6 +172,22 @@ void nested_vmcb02_recalc_intercepts(struct vcpu_svm *svm)
for (i = 0; i < MAX_INTERCEPT; i++)
vmcb02->control.intercepts[i] |= vmcb12_ctrl->intercepts[i];
+ /*
+ * KVM arms the descriptor-table load intercepts in vmcb01 for the
+ * register write filters (KVM_X86_SET_REG_WRITE_FILTER), which
+ * cover only L1. Drop them from vmcb02 unless L1 wants the
+ * intercept itself, matching the SECONDARY_EXEC_DESC strip in
+ * VMX's prepare_vmcs02().
+ */
+ if (!vmcb12_is_intercept(vmcb12_ctrl, INTERCEPT_LOAD_GDTR))
+ vmcb_clr_intercept(&vmcb02->control, INTERCEPT_LOAD_GDTR);
+ if (!vmcb12_is_intercept(vmcb12_ctrl, INTERCEPT_LOAD_IDTR))
+ vmcb_clr_intercept(&vmcb02->control, INTERCEPT_LOAD_IDTR);
+ if (!vmcb12_is_intercept(vmcb12_ctrl, INTERCEPT_LOAD_LDTR))
+ vmcb_clr_intercept(&vmcb02->control, INTERCEPT_LOAD_LDTR);
+ if (!vmcb12_is_intercept(vmcb12_ctrl, INTERCEPT_LOAD_TR))
+ vmcb_clr_intercept(&vmcb02->control, INTERCEPT_LOAD_TR);
+
/* If SMI is not intercepted, ignore guest SMI intercept as well */
if (!intercept_smi)
vmcb_clr_intercept(&vmcb02->control, INTERCEPT_SMI);
diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
index c91467a59e20..47913ba03d3e 100644
--- a/arch/x86/kvm/svm/svm.c
+++ b/arch/x86/kvm/svm/svm.c
@@ -1135,6 +1135,30 @@ static void svm_recalc_intercepts(struct kvm_vcpu *vcpu)
svm_recalc_msr_intercepts(vcpu);
}
+/*
+ * The descriptor-table load intercepts are armed in vmcb01 as a block,
+ * matching VMX's all-or-nothing SECONDARY_EXEC_DESC; an exit the emulator
+ * does not divert applies the load normally.
+ * nested_vmcb02_recalc_intercepts() keeps them out of vmcb02 unless L1
+ * asked for them itself.
+ */
+static void svm_recalc_dt_load_intercepts(struct kvm_vcpu *vcpu)
+{
+ struct vcpu_svm *svm = to_svm(vcpu);
+
+ if (kvm_reg_write_filter_dt_armed(vcpu)) {
+ svm_set_intercept(svm, INTERCEPT_LOAD_GDTR);
+ svm_set_intercept(svm, INTERCEPT_LOAD_IDTR);
+ svm_set_intercept(svm, INTERCEPT_LOAD_LDTR);
+ svm_set_intercept(svm, INTERCEPT_LOAD_TR);
+ } else {
+ svm_clr_intercept(svm, INTERCEPT_LOAD_GDTR);
+ svm_clr_intercept(svm, INTERCEPT_LOAD_IDTR);
+ svm_clr_intercept(svm, INTERCEPT_LOAD_LDTR);
+ svm_clr_intercept(svm, INTERCEPT_LOAD_TR);
+ }
+}
+
static void svm_update_reg_write_filter(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
@@ -1149,6 +1173,8 @@ static void svm_update_reg_write_filter(struct kvm_vcpu *vcpu)
*/
if (vcpu->arch.reg_write_filter_armed & BIT(KVM_X86_REG_FILTER_CR0))
svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
+
+ svm_recalc_dt_load_intercepts(vcpu);
}
static void init_vmcb(struct kvm_vcpu *vcpu, bool init_event)
@@ -1317,6 +1343,13 @@ static void init_vmcb(struct kvm_vcpu *vcpu, bool init_event)
svm_hv_init_vmcb(vmcb);
+ /*
+ * A reset does not touch the register write filters, but a SHUTDOWN
+ * clears the VMCB: re-arm the intercepts which the filters need.
+ * The reset's svm_set_cr0() takes care of INTERCEPT_CR0_WRITE.
+ */
+ svm_recalc_dt_load_intercepts(vcpu);
+
kvm_make_request(KVM_REQ_RECALC_INTERCEPTS, vcpu);
vmcb_mark_all_dirty(vmcb);
@@ -2099,6 +2132,17 @@ static int npf_interception(struct kvm_vcpu *vcpu)
return rc;
}
+static int desc_interception(struct kvm_vcpu *vcpu)
+{
+ /*
+ * Descriptor-table load exits are armed only while a write filter
+ * covers one of the descriptor-table registers; the emulator
+ * diverts a filtered load into a KVM_EXIT_X86_REG_WRITE exit and
+ * applies an unfiltered one normally.
+ */
+ return kvm_emulate_instruction(vcpu, 0);
+}
+
static int db_interception(struct kvm_vcpu *vcpu)
{
struct kvm_run *kvm_run = vcpu->run;
@@ -3523,6 +3567,10 @@ static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
[SVM_EXIT_WRITE_CR3] = cr_interception,
[SVM_EXIT_WRITE_CR4] = cr_interception,
[SVM_EXIT_WRITE_CR8] = cr8_write_interception,
+ [SVM_EXIT_GDTR_WRITE] = desc_interception,
+ [SVM_EXIT_IDTR_WRITE] = desc_interception,
+ [SVM_EXIT_LDTR_WRITE] = desc_interception,
+ [SVM_EXIT_TR_WRITE] = desc_interception,
[SVM_EXIT_READ_DR0] = dr_interception,
[SVM_EXIT_READ_DR1] = dr_interception,
[SVM_EXIT_READ_DR2] = dr_interception,
@@ -5786,6 +5834,9 @@ static __init void svm_set_cpu_caps(void)
kvm_caps.supported_reg_write_filter |= BIT(KVM_X86_REG_FILTER_CR0) |
BIT(KVM_X86_REG_FILTER_CR4);
+ /* As can the four descriptor-table load intercepts. */
+ kvm_caps.supported_reg_write_filter |= KVM_REG_WRITE_FILTER_DT_MASK;
+
/* CPUID 0x80000008 */
if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
boot_cpu_has(X86_FEATURE_AMD_SSBD))
diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c
index d785bcf52a3f..9f322c672466 100644
--- a/arch/x86/kvm/vmx/vmx.c
+++ b/arch/x86/kvm/vmx/vmx.c
@@ -3611,13 +3611,25 @@ void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
if (vmx_umip_emulated()) {
+ bool clear = false;
+
if (cr4 & X86_CR4_UMIP) {
secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
hw_cr4 &= ~X86_CR4_UMIP;
- } else if (!is_guest_mode(vcpu) ||
- !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
- secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
+ } else if (is_guest_mode(vcpu)) {
+ clear = !nested_cpu_has2(get_vmcs12(vcpu),
+ SECONDARY_EXEC_DESC);
+ } else {
+ /*
+ * Clearing CR4.UMIP must not disarm the control
+ * while a descriptor-table write filter relies
+ * on it.
+ */
+ clear = !kvm_reg_write_filter_dt_armed(vcpu);
}
+
+ if (clear)
+ secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
}
vcpu->arch.cr4 = cr4;
@@ -4579,19 +4591,38 @@ void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
}
/*
- * Refresh the interception that the register write filter needs: a
- * filtered CR0/CR4 bit must be host-owned in the vmcs01 guest/host masks
- * so that the guest's writes to it actually exit. For vmcs01, which must
- * be loaded.
+ * SECONDARY_EXEC_DESC has two consumers: UMIP emulation (descriptor-table
+ * reads must #GP when CR4.UMIP is set and the CPU cannot do it) and the
+ * descriptor-table write filters. Every arm or disarm of the control for
+ * one consumer must preserve the other's claim.
+ */
+static bool vmx_need_desc_exiting(struct kvm_vcpu *vcpu)
+{
+ return (vmx_umip_emulated() &&
+ kvm_is_cr4_bit_set(vcpu, X86_CR4_UMIP)) ||
+ kvm_reg_write_filter_dt_armed(vcpu);
+}
+
+/*
+ * Refresh the interception that the register write filters need: a
+ * filtered CR0/CR4 bit must be host-owned in the vmcs01 guest/host masks,
+ * and a descriptor-table filter needs SECONDARY_EXEC_DESC, so that the
+ * guest's writes actually exit. For vmcs01, which must be loaded.
*
* This is all a nested VM-exit needs, for a filter which changed while
* vmcs02 was loaded: it loads L1's CR0 and CR4 afresh.
*/
void vmx_refresh_reg_write_filter(struct kvm_vcpu *vcpu)
{
+ struct vcpu_vmx *vmx = to_vmx(vcpu);
+
vcpu->arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits(vcpu);
vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
- set_cr4_guest_host_mask(to_vmx(vcpu));
+ set_cr4_guest_host_mask(vmx);
+
+ if (vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_DESC)
+ secondary_exec_controls_changebit(vmx, SECONDARY_EXEC_DESC,
+ vmx_need_desc_exiting(vcpu));
}
/*
@@ -5733,7 +5764,13 @@ static int handle_desc(struct kvm_vcpu *vcpu)
*/
BUILD_BUG_ON(KVM_POSSIBLE_CR4_GUEST_BITS & X86_CR4_UMIP);
- WARN_ON_ONCE(!kvm_is_cr4_bit_set(vcpu, X86_CR4_UMIP));
+ /*
+ * Descriptor-table exits are also armed by the write filters; only
+ * an exit with neither UMIP emulation nor a filter armed indicates
+ * a stale SECONDARY_EXEC_DESC control.
+ */
+ WARN_ON_ONCE(!kvm_is_cr4_bit_set(vcpu, X86_CR4_UMIP) &&
+ !kvm_reg_write_filter_dt_armed(vcpu));
return kvm_emulate_instruction(vcpu, 0);
}
@@ -8749,6 +8786,11 @@ __init int vmx_hardware_setup(void)
kvm_caps.supported_reg_write_filter |= BIT(KVM_X86_REG_FILTER_CR0) |
BIT(KVM_X86_REG_FILTER_CR4);
+ /* Descriptor-table filters need descriptor-table exiting. */
+ if (vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_DESC)
+ kvm_caps.supported_reg_write_filter |=
+ KVM_REG_WRITE_FILTER_DT_MASK;
+
set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
if (enable_ept)
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 7fe4b559ed73..e32edbd9777e 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -895,6 +895,20 @@ int kvm_vcpu_ioctl_set_reg_write_filter(struct kvm_vcpu *vcpu,
case KVM_X86_REG_FILTER_XCR0:
allowed = kvm_caps.supported_xcr0 | XFEATURE_MASK_FP;
break;
+ case KVM_X86_REG_FILTER_GDTR:
+ case KVM_X86_REG_FILTER_IDTR:
+ case KVM_X86_REG_FILTER_LDTR:
+ case KVM_X86_REG_FILTER_TR:
+ /*
+ * A descriptor-table load triggers regardless of the old
+ * contents (reloading the same LDT selector re-reads the
+ * descriptor), so the only meaningful masks are all ones
+ * and, to disarm, zero.
+ */
+ if (filter->mask && filter->mask != ~0ULL)
+ return -EINVAL;
+ allowed = ~0ULL;
+ break;
default:
return -EINVAL;
}
@@ -5885,6 +5899,42 @@ static int emulator_filter_cr_write(struct x86_emulate_ctxt *ctxt, int cr,
return emulator_reg_write_exit(ctxt, reg, old_value, new_value);
}
+static int emulator_filter_dt_write(struct x86_emulate_ctxt *ctxt, u32 reg,
+ u64 value, u32 limit)
+{
+ struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
+ struct kvm_segment seg;
+ struct desc_ptr dt;
+ u32 old_limit = 0;
+ u64 old_value;
+
+ if (!kvm_dt_write_filtered(vcpu, reg))
+ return X86EMUL_CONTINUE;
+
+ switch (reg) {
+ case KVM_X86_REG_FILTER_GDTR:
+ kvm_x86_call(get_gdt)(vcpu, &dt);
+ old_value = dt.address;
+ old_limit = dt.size;
+ break;
+ case KVM_X86_REG_FILTER_IDTR:
+ kvm_x86_call(get_idt)(vcpu, &dt);
+ old_value = dt.address;
+ old_limit = dt.size;
+ break;
+ default:
+ kvm_get_segment(vcpu, &seg, reg == KVM_X86_REG_FILTER_LDTR ?
+ VCPU_SREG_LDTR : VCPU_SREG_TR);
+ old_value = seg.selector;
+ break;
+ }
+
+ emulator_reg_write_exit(ctxt, reg, old_value, value);
+ vcpu->run->reg_write.old_limit = old_limit;
+ vcpu->run->reg_write.new_limit = limit;
+ return X86EMUL_IO_NEEDED;
+}
+
static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
{
return kvm_x86_call(get_cpl)(emul_to_vcpu(ctxt));
@@ -6158,6 +6208,7 @@ static const struct x86_emulate_ops emulate_ops = {
.get_cr = emulator_get_cr,
.set_cr = emulator_set_cr,
.filter_cr_write = emulator_filter_cr_write,
+ .filter_dt_write = emulator_filter_dt_write,
.cpl = emulator_get_cpl,
.get_effective_dr7 = emulator_get_effective_dr7,
.get_dr = emulator_get_dr,
diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h
index 165fa36c2479..566b98bb5823 100644
--- a/include/uapi/linux/kvm.h
+++ b/include/uapi/linux/kvm.h
@@ -521,6 +521,8 @@ struct kvm_run {
__u32 reg; /* KVM_X86_REG_FILTER_* */
__u64 old_value;
__u64 new_value;
+ __u32 old_limit; /* GDTR/IDTR only */
+ __u32 new_limit; /* GDTR/IDTR only */
} reg_write;
/* Fix the size of the union. */
char padding[256];
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 14/15] KVM: selftests: Add x86 register write filter test
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (12 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 13/15] KVM: x86: Add descriptor-table registers to the write filter David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:27 ` [PATCH v3 15/15] KVM: selftests: Test the register write filter with a nested guest David Woodhouse
14 siblings, 0 replies; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
Cover each register class with the write performed by userspace and
retired by KVM_RUN, single-stepped across an intercepted and an
emulated write; the write refused with #GP and #UD, left alone with #NM
queued, and a reserved answer, on both paths; a prefixed and an
emulated XSETBV; filters armed after the guest has run, and disarmed;
SMM; filters armed before KVM_SET_CPUID2, and across INIT and a triple
fault; and the error cases.
The library learns X86_FEATURE_AVX and the exit's name.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
tools/testing/selftests/kvm/Makefile.kvm | 1 +
.../selftests/kvm/include/x86/processor.h | 1 +
tools/testing/selftests/kvm/lib/kvm_util.c | 1 +
.../selftests/kvm/x86/reg_write_filter_test.c | 1004 +++++++++++++++++
4 files changed, 1007 insertions(+)
create mode 100644 tools/testing/selftests/kvm/x86/reg_write_filter_test.c
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 2f67399ddd68..6fcf54f58c48 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -115,6 +115,7 @@ TEST_GEN_PROGS_x86 += x86/pmu_counters_test
TEST_GEN_PROGS_x86 += x86/pmu_event_filter_test
TEST_GEN_PROGS_x86 += x86/private_mem_conversions_test
TEST_GEN_PROGS_x86 += x86/private_mem_kvm_exits_test
+TEST_GEN_PROGS_x86 += x86/reg_write_filter_test
TEST_GEN_PROGS_x86 += x86/save_restore_pf_stress_test
TEST_GEN_PROGS_x86 += x86/set_boot_cpu_id
TEST_GEN_PROGS_x86 += x86/set_sregs_test
diff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/testing/selftests/kvm/include/x86/processor.h
index 571f8a602edd..eec368e07b78 100644
--- a/tools/testing/selftests/kvm/include/x86/processor.h
+++ b/tools/testing/selftests/kvm/include/x86/processor.h
@@ -165,6 +165,7 @@ struct kvm_x86_cpu_feature {
#define X86_FEATURE_TSC_DEADLINE_TIMER KVM_X86_CPU_FEATURE(0x1, 0, ECX, 24)
#define X86_FEATURE_XSAVE KVM_X86_CPU_FEATURE(0x1, 0, ECX, 26)
#define X86_FEATURE_OSXSAVE KVM_X86_CPU_FEATURE(0x1, 0, ECX, 27)
+#define X86_FEATURE_AVX KVM_X86_CPU_FEATURE(0x1, 0, ECX, 28)
#define X86_FEATURE_RDRAND KVM_X86_CPU_FEATURE(0x1, 0, ECX, 30)
#define X86_FEATURE_HYPERVISOR KVM_X86_CPU_FEATURE(0x1, 0, ECX, 31)
#define X86_FEATURE_PAE KVM_X86_CPU_FEATURE(0x1, 0, EDX, 6)
diff --git a/tools/testing/selftests/kvm/lib/kvm_util.c b/tools/testing/selftests/kvm/lib/kvm_util.c
index d42e201eba76..c8879c3949bc 100644
--- a/tools/testing/selftests/kvm/lib/kvm_util.c
+++ b/tools/testing/selftests/kvm/lib/kvm_util.c
@@ -2079,6 +2079,7 @@ static struct exit_reason {
KVM_EXIT_STRING(LOONGARCH_IOCSR),
KVM_EXIT_STRING(MEMORY_FAULT),
KVM_EXIT_STRING(ARM_SEA),
+ KVM_EXIT_STRING(X86_REG_WRITE),
};
/*
diff --git a/tools/testing/selftests/kvm/x86/reg_write_filter_test.c b/tools/testing/selftests/kvm/x86/reg_write_filter_test.c
new file mode 100644
index 000000000000..7d7495c17466
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/reg_write_filter_test.c
@@ -0,0 +1,1004 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Test KVM_X86_SET_REG_WRITE_FILTER and the KVM_EXIT_X86_REG_WRITE exit:
+ * arming and disarming, the write performed by userspace and retired by
+ * KVM_RUN (single-stepped too), the write refused by KVM with #GP and
+ * with #UD, left alone with an exception queued and a reserved answer,
+ * each of those for an intercepted and for an emulated write, an
+ * intercepted write left alone with RIP moved and with nothing, the true
+ * length of a prefixed instruction, per-bit mask semantics on CR0 and CR4,
+ * XCR0 filtering, descriptor-table filtering where supported, that SMM
+ * writes bypass the filter, that a sibling vCPU without filters is
+ * unaffected while the first vCPU's are armed, and that filters armed
+ * before KVM_SET_CPUID2 work after it, and survive an INIT and a triple
+ * fault.
+ *
+ * Copyright © 2026 Amazon.com, Inc. or its affiliates.
+ */
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+#include "apic.h"
+#include "smm.h"
+
+#define FILTERED_CR4_BIT X86_CR4_TSD
+#define UNFILTERED_CR4_BIT X86_CR4_DE
+/*
+ * The filtered CR0 bit is CR0.TS: the one which CLTS and LMSW, with their
+ * own exits, change as well as MOV to CR0.
+ */
+#define UNFILTERED_CR0_BIT X86_CR0_AM
+
+#define SMRAM_GPA 0x1000000
+
+/* A port write which stops the guest without the FPU, unlike a ucall. */
+#define ARM_PORT 0x5a
+/* A port write by which the SMI handler shows that it runs. */
+#define SMM_PORT 0x5b
+
+static bool have_avx;
+static bool have_dt_filters;
+static bool have_smm;
+static bool crash;
+
+/*
+ * Say that the handler runs. SMM entry clears CR4; set and clear the
+ * filtered CR4.TSD bit, which must be applied without a filter exit, and
+ * return. RSM's restore of the pre-SMI CR4 is a state load and is not
+ * filtered either.
+ */
+static u8 smi_handler[] = {
+ 0xe6, SMM_PORT, /* out %al, $SMM_PORT */
+ 0x0f, 0x20, 0xe0, /* mov %cr4, %eax */
+ 0x0c, 0x04, /* or $X86_CR4_TSD, %al */
+ 0x0f, 0x22, 0xe0, /* mov %eax, %cr4 */
+ 0x24, 0xfb, /* and $~X86_CR4_TSD, %al */
+ 0x0f, 0x22, 0xe0, /* mov %eax, %cr4 */
+ 0x0f, 0xaa, /* rsm */
+};
+
+/* Fixed encodings, so that the host knows the length of each write. */
+#define MOV_TO_CR4_LEN 3
+#define MOV_TO_CR0_LEN 3
+#define CLTS_LEN 2
+#define LMSW_LEN 3
+#define XSETBV_LEN 3
+#define REX_XSETBV_LEN 4
+#define LGDT_LEN 3
+#define LIDT_LEN 3
+#define LLDT_LEN 3
+#define LTR_LEN 3
+
+static void write_cr4(u64 val)
+{
+ /* mov %rax, %cr4 */
+ asm volatile(".byte 0x0f, 0x22, 0xe0" : : "a"(val) : "memory");
+}
+
+static void write_cr0(u64 val)
+{
+ /* mov %rax, %cr0 */
+ asm volatile(".byte 0x0f, 0x22, 0xc0" : : "a"(val) : "memory");
+}
+
+static u8 write_cr4_safe(u64 val)
+{
+ /* mov %rax, %cr4 */
+ return kvm_asm_safe(".byte 0x0f, 0x22, 0xe0", "a"(val));
+}
+
+static void lgdt(const struct desc_ptr *gdt)
+{
+ /* lgdt (%rax) */
+ asm volatile(".byte 0x0f, 0x01, 0x10" : : "a"(gdt), "m"(*gdt));
+}
+
+static void lidt(const struct desc_ptr *idt)
+{
+ /* lidt (%rax) */
+ asm volatile(".byte 0x0f, 0x01, 0x18" : : "a"(idt), "m"(*idt));
+}
+
+static void lldt(u16 sel)
+{
+ /* lldt %ax */
+ asm volatile(".byte 0x0f, 0x00, 0xd0" : : "a"(sel));
+}
+
+static void ltr(u16 sel)
+{
+ /* ltr %ax */
+ asm volatile(".byte 0x0f, 0x00, 0xd8" : : "a"(sel));
+}
+
+static void guest_code(void)
+{
+ u64 cr0, cr4;
+ u8 vector;
+
+ /*
+ * Nothing is filtered yet, and the guest owns these two bits where
+ * the CPU lets it: KVM does not see them change. With CR0.TS set
+ * the guest must stay away from the FPU, so no ucall until CLTS.
+ */
+ write_cr4(get_cr4() | FILTERED_CR4_BIT);
+ write_cr0(get_cr0() | X86_CR0_TS);
+ asm volatile("outb %%al, $" __stringify(ARM_PORT) : : "a"(0));
+
+ /*
+ * The host has armed the filters, which takes the bits away from
+ * the guest. It must still read what it wrote, and its next write
+ * of each must exit: CLTS decides by the value KVM shows it.
+ */
+ cr0 = get_cr0();
+ cr4 = get_cr4();
+ asm volatile("clts");
+ GUEST_ASSERT(cr0 & X86_CR0_TS);
+ GUEST_ASSERT(cr4 & FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr0() & X86_CR0_TS));
+ write_cr4(get_cr4() & ~FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+
+ /* A write changing only an unfiltered bit must not exit. */
+ write_cr4(get_cr4() | UNFILTERED_CR4_BIT);
+ GUEST_ASSERT(get_cr4() & UNFILTERED_CR4_BIT);
+ write_cr0(get_cr0() ^ UNFILTERED_CR0_BIT);
+ write_cr0(get_cr0() ^ UNFILTERED_CR0_BIT);
+ GUEST_SYNC(1);
+
+ /* Filtered bit, userspace performs the write. */
+ write_cr4(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT(get_cr4() & FILTERED_CR4_BIT);
+ GUEST_SYNC(2);
+
+ /* Filtered bit, userspace leaves it uncompleted, then performs. */
+ write_cr4(get_cr4() & ~FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ GUEST_SYNC(3);
+
+ /* Filtered bit: KVM refuses with #GP(0) and #UD, userspace with #NM. */
+ vector = write_cr4_safe(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT_EQ(vector, GP_VECTOR);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ vector = write_cr4_safe(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT_EQ(vector, UD_VECTOR);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ vector = write_cr4_safe(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT_EQ(vector, NM_VECTOR);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ GUEST_SYNC(4);
+
+ /* Filtered bit, userspace steps over the write itself. */
+ write_cr4(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ GUEST_SYNC(5);
+
+ /* CR0.TS: set by MOV to CR0, cleared by CLTS, set again by LMSW. */
+ write_cr0(get_cr0() | X86_CR0_TS);
+ GUEST_ASSERT(get_cr0() & X86_CR0_TS);
+ asm volatile("clts");
+ GUEST_ASSERT(!(get_cr0() & X86_CR0_TS));
+ /* lmsw %ax */
+ asm volatile(".byte 0x0f, 0x01, 0xf0" : :
+ "a"((get_cr0() & 0xf) | X86_CR0_TS) : "memory");
+ GUEST_ASSERT(get_cr0() & X86_CR0_TS);
+ asm volatile("clts");
+ GUEST_SYNC(6);
+
+ if (have_avx) {
+ u64 legacy = XFEATURE_MASK_FP | XFEATURE_MASK_SSE;
+ u64 xcr0 = xgetbv(0);
+
+ /* Drop everything above SSE along with YMM, and restore it. */
+ GUEST_ASSERT(xcr0 & XFEATURE_MASK_YMM);
+ xsetbv(0, legacy);
+ GUEST_ASSERT_EQ(xgetbv(0), legacy);
+ xsetbv(0, xcr0);
+ GUEST_ASSERT_EQ(xgetbv(0), xcr0);
+
+ /* The same with a redundant REX.W prefix: one byte longer. */
+ asm volatile(".byte 0x48, 0x0f, 0x01, 0xd1" : :
+ "a"((u32)legacy), "d"((u32)(legacy >> 32)), "c"(0));
+ GUEST_ASSERT_EQ(xgetbv(0), legacy);
+ xsetbv(0, xcr0);
+ GUEST_ASSERT_EQ(xgetbv(0), xcr0);
+
+ /* And through the emulator, which must not let it past. */
+ if (is_forced_emulation_enabled) {
+ asm volatile(KVM_FEP ".byte 0x0f, 0x01, 0xd1" : :
+ "a"((u32)legacy), "d"((u32)(legacy >> 32)),
+ "c"(0));
+ GUEST_ASSERT_EQ(xgetbv(0), legacy);
+ asm volatile(KVM_FEP ".byte 0x0f, 0x01, 0xd1" : :
+ "a"((u32)xcr0), "d"((u32)(xcr0 >> 32)),
+ "c"(0));
+ GUEST_ASSERT_EQ(xgetbv(0), xcr0);
+ }
+ }
+ GUEST_SYNC(7);
+
+ if (have_dt_filters) {
+ struct desc_ptr gdt = get_gdt();
+ struct desc_ptr idt = get_idt();
+
+ /* Reloading the same GDT is still a filtered load. */
+ lgdt(&gdt);
+ GUEST_ASSERT_EQ(get_gdt().address, gdt.address);
+
+ /* So is reloading the IDT. */
+ lidt(&idt);
+ GUEST_ASSERT_EQ(get_idt().address, idt.address);
+
+ /*
+ * And the task register, whose TSS is busy: the load would
+ * fault if KVM performed it. Userspace leaves TR as it is
+ * and KVM retires the instruction.
+ */
+ ltr(get_tr());
+
+ /* A null LDT selector is architecturally fine. */
+ lldt(0);
+
+ /* Load refused by KVM: #GP(0), GDTR unchanged. */
+ vector = kvm_asm_safe(".byte 0x0f, 0x01, 0x10", "a"(&gdt),
+ "m"(gdt));
+ GUEST_ASSERT_EQ(vector, GP_VECTOR);
+ GUEST_ASSERT_EQ(get_gdt().address, gdt.address);
+
+ /* Load refused by KVM with #UD. */
+ vector = kvm_asm_safe(".byte 0x0f, 0x01, 0x10", "a"(&gdt),
+ "m"(gdt));
+ GUEST_ASSERT_EQ(vector, UD_VECTOR);
+ GUEST_ASSERT_EQ(get_gdt().address, gdt.address);
+
+ /* Load refused by userspace, with #NM. */
+ vector = kvm_asm_safe(".byte 0x0f, 0x01, 0x10", "a"(&gdt),
+ "m"(gdt));
+ GUEST_ASSERT_EQ(vector, NM_VECTOR);
+ GUEST_ASSERT_EQ(get_gdt().address, gdt.address);
+ }
+ GUEST_SYNC(8);
+
+ /* The host single-steps this write. */
+ write_cr4(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT(get_cr4() & FILTERED_CR4_BIT);
+ write_cr4(get_cr4() & ~FILTERED_CR4_BIT);
+ GUEST_SYNC(9);
+
+ /*
+ * The host injects an SMI here when SMM is available; the SMM
+ * handler's filtered-bit writes must go through unfiltered, and
+ * the filter must still work afterwards.
+ */
+ GUEST_SYNC(10);
+ if (have_smm) {
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ write_cr4(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT(get_cr4() & FILTERED_CR4_BIT);
+ write_cr4(get_cr4() & ~FILTERED_CR4_BIT);
+ }
+ GUEST_SYNC(11);
+
+ /* The host has disarmed every filter: no exit, the writes land. */
+ write_cr4(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT(get_cr4() & FILTERED_CR4_BIT);
+ write_cr4(get_cr4() & ~FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ write_cr0(get_cr0() | X86_CR0_TS);
+ asm volatile("clts");
+ GUEST_ASSERT(!(get_cr0() & X86_CR0_TS));
+ if (have_dt_filters) {
+ struct desc_ptr gdt = get_gdt();
+ struct desc_ptr idt = get_idt();
+
+ lgdt(&gdt);
+ lidt(&idt);
+ lldt(0);
+ }
+ if (have_avx) {
+ u64 xcr0 = xgetbv(0);
+
+ xsetbv(0, XFEATURE_MASK_FP | XFEATURE_MASK_SSE);
+ xsetbv(0, xcr0);
+ }
+ GUEST_SYNC(12);
+
+ GUEST_DONE();
+}
+
+/*
+ * One round of filtered writes, over and over, for the host to check that
+ * each still exits after an event which resets the vCPU. LTR of the busy
+ * TSS would fault if KVM performed it.
+ */
+static void reset_guest_code(void)
+{
+ struct desc_ptr gdt, idt, zero = {};
+
+ for (;;) {
+ gdt = get_gdt();
+ idt = get_idt();
+ GUEST_SYNC(1);
+ write_cr4(get_cr4() ^ FILTERED_CR4_BIT);
+ if (have_dt_filters) {
+ lgdt(&gdt);
+ lidt(&idt);
+ lldt(0);
+ ltr(get_tr());
+ }
+ GUEST_SYNC(2);
+ GUEST_SYNC(3);
+ if (READ_ONCE(crash)) {
+ /* No IDT: the #UD cannot be delivered, triple fault. */
+ lidt(&zero);
+ asm volatile("ud2");
+ }
+ }
+}
+
+static void init_sender_code(void)
+{
+ x2apic_enable();
+ /* INIT to APIC ID 0, physical destination. */
+ x2apic_write_reg(APIC_ICR, APIC_DM_INIT | APIC_INT_ASSERT);
+ GUEST_DONE();
+}
+
+static void sibling_guest_code(void)
+{
+ /* No filter on this vCPU: both writes must go straight through. */
+ set_cr4(get_cr4() | FILTERED_CR4_BIT);
+ GUEST_ASSERT(get_cr4() & FILTERED_CR4_BIT);
+ set_cr4(get_cr4() & ~FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ GUEST_DONE();
+}
+
+static void set_filter(struct kvm_vcpu *vcpu, u32 reg, u64 mask)
+{
+ struct kvm_x86_reg_write_filter filter = {
+ .reg = reg,
+ .mask = mask,
+ };
+
+ vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+}
+
+static void expect_sync(struct kvm_vcpu *vcpu, u64 stage)
+{
+ struct ucall uc;
+
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+ switch (get_ucall(vcpu, &uc)) {
+ case UCALL_SYNC:
+ TEST_ASSERT_EQ(uc.args[1], stage);
+ break;
+ case UCALL_ABORT:
+ REPORT_GUEST_ASSERT(uc);
+ default:
+ TEST_FAIL("Unexpected ucall %lu, wanted sync %lu",
+ uc.cmd, stage);
+ }
+}
+
+static void expect_done(struct kvm_vcpu *vcpu)
+{
+ struct ucall uc;
+
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+ switch (get_ucall(vcpu, &uc)) {
+ case UCALL_DONE:
+ break;
+ case UCALL_ABORT:
+ REPORT_GUEST_ASSERT(uc);
+ default:
+ TEST_FAIL("Unexpected ucall %lu, wanted done", uc.cmd);
+ }
+}
+
+/*
+ * Run the vCPU into a KVM_EXIT_X86_REG_WRITE on @reg made by an instruction
+ * of @insn_len bytes. KVM must not have performed the write or moved RIP.
+ */
+static struct kvm_run *expect_reg_write(struct kvm_vcpu *vcpu, u32 reg,
+ u8 insn_len)
+{
+ static const u8 zeroes[sizeof(vcpu->run->reg_write.pad)];
+ struct kvm_run *run = vcpu->run;
+
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_X86_REG_WRITE);
+ TEST_ASSERT_EQ(run->reg_write.reg, reg);
+ TEST_ASSERT_EQ(run->reg_write.insn_len, insn_len);
+ /* KVM hands over every exit as one which completes. */
+ TEST_ASSERT_EQ(run->reg_write.ret, KVM_INSN_COMPLETE);
+ TEST_ASSERT(!memcmp(run->reg_write.pad, zeroes, sizeof(zeroes)),
+ "Reserved bytes of the exit are not zero");
+ return run;
+}
+
+/*
+ * Perform the write which the exit reports, as userspace must before it
+ * lets KVM_RUN retire the instruction.
+ */
+static void perform_reg_write(struct kvm_vcpu *vcpu)
+{
+ struct kvm_run *run = vcpu->run;
+ struct kvm_xcrs xcrs = {
+ .nr_xcrs = 1,
+ .xcrs[0].value = run->reg_write.new_value,
+ };
+ struct kvm_sregs sregs;
+
+ vcpu_sregs_get(vcpu, &sregs);
+
+ switch (run->reg_write.reg) {
+ case KVM_X86_REG_FILTER_CR0:
+ sregs.cr0 = run->reg_write.new_value;
+ break;
+ case KVM_X86_REG_FILTER_CR4:
+ sregs.cr4 = run->reg_write.new_value;
+ break;
+ case KVM_X86_REG_FILTER_XCR0:
+ vcpu_xcrs_set(vcpu, &xcrs);
+ return;
+ case KVM_X86_REG_FILTER_GDTR:
+ sregs.gdt.base = run->reg_write.new_value;
+ sregs.gdt.limit = run->reg_write.new_limit;
+ break;
+ case KVM_X86_REG_FILTER_IDTR:
+ sregs.idt.base = run->reg_write.new_value;
+ sregs.idt.limit = run->reg_write.new_limit;
+ break;
+ case KVM_X86_REG_FILTER_LDTR:
+ /* Only the null selector, which needs no descriptor. */
+ TEST_ASSERT_EQ(run->reg_write.new_value, 0);
+ memset(&sregs.ldt, 0, sizeof(sregs.ldt));
+ sregs.ldt.unusable = 1;
+ break;
+ default:
+ TEST_FAIL("Unexpected register class %u", run->reg_write.reg);
+ }
+
+ vcpu_sregs_set(vcpu, &sregs);
+}
+
+/* The write was performed: KVM_RUN retires the instruction. */
+static struct kvm_run *reg_write_performed(struct kvm_vcpu *vcpu, u32 reg,
+ u8 insn_len)
+{
+ struct kvm_run *run = expect_reg_write(vcpu, reg, insn_len);
+
+ perform_reg_write(vcpu);
+ return run;
+}
+
+/*
+ * Say with @ret that the write does not complete, optionally queuing an
+ * exception for the guest to take at the instruction.
+ */
+static void leave_reg_write(struct kvm_vcpu *vcpu, u8 ret, int vector,
+ bool has_ec)
+{
+ struct kvm_vcpu_events events;
+
+ vcpu->run->reg_write.ret = ret;
+ if (vector < 0)
+ return;
+
+ vcpu_events_get(vcpu, &events);
+ events.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
+ events.exception.pending = 1;
+ events.exception.injected = 0;
+ events.exception.nr = vector;
+ events.exception.has_error_code = has_ec;
+ events.exception.error_code = 0;
+ events.exception_has_payload = 0;
+ vcpu_events_set(vcpu, &events);
+}
+
+/* Have KVM_RUN refuse a reserved answer: the write comes back as it was. */
+static void refuse_reg_write(struct kvm_vcpu *vcpu, u32 reg, u8 insn_len)
+{
+ struct kvm_regs regs;
+ u64 rip;
+
+ vcpu_regs_get(vcpu, ®s);
+ rip = regs.rip;
+ leave_reg_write(vcpu, KVM_INSN_RESUME + 1, -1, false);
+ TEST_ASSERT(__vcpu_run(vcpu) == -1 && errno == EINVAL,
+ "KVM_RUN accepted a reserved 'ret'");
+ expect_reg_write(vcpu, reg, insn_len);
+ vcpu_regs_get(vcpu, ®s);
+ TEST_ASSERT_EQ(regs.rip, rip);
+}
+
+/*
+ * The guest makes the same filtered write three times, expecting #GP, #UD
+ * and #NM: the first two from KVM, the third queued by userspace with the
+ * write left alone, after KVM_RUN has refused a reserved answer.
+ */
+static void refuse_reg_writes(struct kvm_vcpu *vcpu, u32 reg, u8 insn_len,
+ const char *what)
+{
+ expect_reg_write(vcpu, reg, insn_len);
+ leave_reg_write(vcpu, KVM_INSN_GP, -1, false);
+ expect_reg_write(vcpu, reg, insn_len);
+ leave_reg_write(vcpu, KVM_INSN_UD, -1, false);
+ expect_reg_write(vcpu, reg, insn_len);
+ refuse_reg_write(vcpu, reg, insn_len);
+ leave_reg_write(vcpu, KVM_INSN_RESUME, NM_VECTOR, false);
+ pr_info("%s: KVM_INSN_GP, KVM_INSN_UD, reserved, KVM_INSN_RESUME with #NM queued\n",
+ what);
+}
+
+static void test_bogus_args(struct kvm_vcpu *vcpu)
+{
+ struct kvm_x86_reg_write_filter filter = {};
+ int r;
+
+ /* Out of range register class. */
+ filter.reg = 0xffff;
+ filter.mask = ~0ULL;
+ r = __vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+ TEST_ASSERT(r && errno == EINVAL, "Bogus reg: wanted EINVAL, got %d",
+ r ? errno : 0);
+
+ /* Non-zero flags. */
+ filter.reg = KVM_X86_REG_FILTER_CR0;
+ filter.flags = 1;
+ filter.mask = X86_CR0_TS;
+ r = __vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+ TEST_ASSERT(r && errno == EINVAL, "Bogus flags: wanted EINVAL, got %d",
+ r ? errno : 0);
+ filter.flags = 0;
+
+ /* Non-zero reserved space. */
+ filter.reserved[3] = 1;
+ r = __vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+ TEST_ASSERT(r && errno == EINVAL,
+ "Bogus reserved: wanted EINVAL, got %d", r ? errno : 0);
+ filter.reserved[3] = 0;
+
+ /* CR0 bit 32 is reserved and can never change. */
+ filter.mask = BIT_ULL(32);
+ r = __vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+ TEST_ASSERT(r && errno == EINVAL, "Bogus mask: wanted EINVAL, got %d",
+ r ? errno : 0);
+
+ if (have_dt_filters) {
+ /* Descriptor-table filters take an all-ones mask only. */
+ filter.reg = KVM_X86_REG_FILTER_GDTR;
+ filter.mask = 1;
+ r = __vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+ TEST_ASSERT(r && errno == EINVAL,
+ "Bogus GDTR mask: wanted EINVAL, got %d",
+ r ? errno : 0);
+ }
+}
+
+/*
+ * Run the vCPU to the guest's sync @stop, performing the filtered writes on
+ * the way, except for TR, which stays as it is. Returns the classes whose
+ * writes exited.
+ */
+static u32 run_to_sync(struct kvm_vcpu *vcpu, u64 stop)
+{
+ struct ucall uc;
+ u32 seen = 0;
+
+ for (;;) {
+ vcpu_run(vcpu);
+ if (vcpu->run->exit_reason == KVM_EXIT_X86_REG_WRITE) {
+ seen |= BIT(vcpu->run->reg_write.reg);
+ if (vcpu->run->reg_write.reg != KVM_X86_REG_FILTER_TR)
+ perform_reg_write(vcpu);
+ continue;
+ }
+
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ switch (get_ucall(vcpu, &uc)) {
+ case UCALL_SYNC:
+ if (uc.args[1] == stop)
+ return seen;
+ break;
+ case UCALL_ABORT:
+ REPORT_GUEST_ASSERT(uc);
+ default:
+ TEST_FAIL("Unexpected ucall %lu", uc.cmd);
+ }
+ }
+}
+
+/* One round of the guest's writes: every armed filter must still exit. */
+static void check_round(struct kvm_vcpu *vcpu, u32 armed, const char *when)
+{
+ u32 seen;
+
+ run_to_sync(vcpu, 1);
+ seen = run_to_sync(vcpu, 2);
+ run_to_sync(vcpu, 3);
+ TEST_ASSERT(seen == armed,
+ "%s: writes of classes 0x%x exited, armed are 0x%x",
+ when, seen, armed);
+ pr_info("%s: MOV to CR4%s still exit\n", when,
+ have_dt_filters ? ", LGDT, LIDT, LLDT, LTR" : "");
+}
+
+/*
+ * KVM_SET_CPUID2 recomputes the controls of a vCPU which has not run, and a
+ * reset leaves the filters armed: both have to leave the interception which
+ * the filters need in place. Arm before KVM_SET_CPUID2, then reset with an
+ * INIT and with a triple fault, which on SVM clears the VMCB. Userspace
+ * puts the register state back each time, as a VMM which resets a vCPU
+ * would.
+ */
+static void test_reset(void)
+{
+ u32 armed = BIT(KVM_X86_REG_FILTER_CR4);
+ struct kvm_vcpu *vcpu, *sender;
+ struct kvm_mp_state mp_state;
+ struct kvm_sregs sregs, now;
+ struct kvm_regs regs;
+ struct kvm_vm *vm;
+ struct ucall uc;
+
+ vm = vm_create_with_one_vcpu(&vcpu, reset_guest_code);
+ sender = vm_vcpu_add(vm, 1, init_sender_code);
+ sync_global_to_guest(vm, have_dt_filters);
+
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR4, FILTERED_CR4_BIT);
+ if (have_dt_filters) {
+ set_filter(vcpu, KVM_X86_REG_FILTER_GDTR, ~0ULL);
+ set_filter(vcpu, KVM_X86_REG_FILTER_IDTR, ~0ULL);
+ set_filter(vcpu, KVM_X86_REG_FILTER_LDTR, ~0ULL);
+ set_filter(vcpu, KVM_X86_REG_FILTER_TR, ~0ULL);
+ armed |= BIT(KVM_X86_REG_FILTER_GDTR) |
+ BIT(KVM_X86_REG_FILTER_IDTR) |
+ BIT(KVM_X86_REG_FILTER_LDTR) |
+ BIT(KVM_X86_REG_FILTER_TR);
+ }
+
+ /*
+ * The vCPU has not run, so this is not the no-op which KVM makes of
+ * KVM_SET_CPUID2 afterwards: the vendor code computes its controls
+ * again, with the filters armed.
+ */
+ vcpu_set_cpuid(vcpu);
+ check_round(vcpu, armed, "Armed, then KVM_SET_CPUID2 before the first run");
+
+ /* INIT, which KVM_GET_MP_STATE has the vCPU take. */
+ vcpu_regs_get(vcpu, ®s);
+ vcpu_sregs_get(vcpu, &sregs);
+ vcpu_run(sender);
+ TEST_ASSERT_KVM_EXIT_REASON(sender, KVM_EXIT_IO);
+ TEST_ASSERT_EQ(get_ucall(sender, &uc), UCALL_DONE);
+ vcpu_mp_state_get(vcpu, &mp_state);
+ vcpu_sregs_get(vcpu, &now);
+ TEST_ASSERT(!now.cr4, "CR4 0x%llx after INIT: no reset", now.cr4);
+ mp_state.mp_state = KVM_MP_STATE_RUNNABLE;
+ vcpu_mp_state_set(vcpu, &mp_state);
+ vcpu_sregs_set(vcpu, &sregs);
+ vcpu_regs_set(vcpu, ®s);
+ check_round(vcpu, armed, "After INIT");
+
+ /* A triple fault. The guest's LIDT is filtered on the way to it. */
+ vcpu_regs_get(vcpu, ®s);
+ vcpu_sregs_get(vcpu, &sregs);
+ crash = true;
+ sync_global_to_guest(vm, crash);
+ for (;;) {
+ vcpu_run(vcpu);
+ if (vcpu->run->exit_reason == KVM_EXIT_X86_REG_WRITE) {
+ TEST_ASSERT_EQ(vcpu->run->reg_write.reg,
+ KVM_X86_REG_FILTER_IDTR);
+ perform_reg_write(vcpu);
+ } else if (vcpu->run->exit_reason == KVM_EXIT_IO) {
+ /* The guest's last sync, completed or repeated. */
+ TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_SYNC);
+ TEST_ASSERT_EQ(uc.args[1], 3);
+ } else {
+ break;
+ }
+ }
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_SHUTDOWN);
+ crash = false;
+ sync_global_to_guest(vm, crash);
+ vcpu_mp_state_get(vcpu, &mp_state);
+ mp_state.mp_state = KVM_MP_STATE_RUNNABLE;
+ vcpu_mp_state_set(vcpu, &mp_state);
+ vcpu_sregs_set(vcpu, &sregs);
+ vcpu_regs_set(vcpu, ®s);
+ check_round(vcpu, armed, "After a triple fault");
+
+ kvm_vm_free(vm);
+}
+
+int main(int argc, char *argv[])
+{
+ struct kvm_guest_debug debug = {};
+ struct kvm_vcpu *vcpu, *sibling;
+ struct kvm_regs regs;
+ struct kvm_run *run;
+ struct kvm_vm *vm;
+ u32 filters;
+ u64 rip;
+
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_X86_REG_WRITE_FILTER));
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_EXCEPTION_PAYLOAD));
+
+ filters = kvm_check_cap(KVM_CAP_X86_REG_WRITE_FILTER);
+ TEST_REQUIRE(filters & BIT(KVM_X86_REG_FILTER_CR0));
+ TEST_REQUIRE(filters & BIT(KVM_X86_REG_FILTER_CR4));
+ TEST_REQUIRE(filters & BIT(KVM_X86_REG_FILTER_XCR0));
+
+ have_avx = kvm_cpu_has(X86_FEATURE_AVX);
+ have_dt_filters = (filters & BIT(KVM_X86_REG_FILTER_GDTR)) &&
+ (filters & BIT(KVM_X86_REG_FILTER_IDTR)) &&
+ (filters & BIT(KVM_X86_REG_FILTER_LDTR)) &&
+ (filters & BIT(KVM_X86_REG_FILTER_TR));
+ have_smm = kvm_has_cap(KVM_CAP_X86_SMM);
+
+ vm = vm_create_with_one_vcpu(&vcpu, guest_code);
+ sibling = vm_vcpu_add(vm, 1, sibling_guest_code);
+
+ /* To queue an exception as pending, as the refusing legs do. */
+ vm_enable_cap(vm, KVM_CAP_EXCEPTION_PAYLOAD, 1);
+
+ if (have_smm)
+ setup_smram(vm, vcpu, SMRAM_GPA, smi_handler,
+ sizeof(smi_handler));
+
+ sync_global_to_guest(vm, have_avx);
+ sync_global_to_guest(vm, have_dt_filters);
+ sync_global_to_guest(vm, have_smm);
+
+ test_bogus_args(vcpu);
+
+ if (have_avx)
+ set_filter(vcpu, KVM_X86_REG_FILTER_XCR0, XFEATURE_MASK_YMM);
+ if (have_dt_filters) {
+ set_filter(vcpu, KVM_X86_REG_FILTER_GDTR, ~0ULL);
+ set_filter(vcpu, KVM_X86_REG_FILTER_IDTR, ~0ULL);
+ set_filter(vcpu, KVM_X86_REG_FILTER_LDTR, ~0ULL);
+ set_filter(vcpu, KVM_X86_REG_FILTER_TR, ~0ULL);
+ }
+
+ /*
+ * Stage 0: arm the CR0 and CR4 filters on a vCPU which has run, and
+ * whose guest has just set both bits behind KVM's back. The exits
+ * must report them as set, and the guest reads them so (it asserts).
+ */
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ TEST_ASSERT_EQ(vcpu->run->io.port, ARM_PORT);
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR4, FILTERED_CR4_BIT);
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR0, X86_CR0_TS);
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR0, CLTS_LEN);
+ TEST_ASSERT(run->reg_write.old_value & X86_CR0_TS,
+ "CR0 0x%llx of the exit lacks the TS which the guest set before the filter",
+ run->reg_write.old_value);
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ TEST_ASSERT(run->reg_write.old_value & FILTERED_CR4_BIT,
+ "CR4 0x%llx of the exit lacks the bit which the guest set before the filter",
+ run->reg_write.old_value);
+ pr_info("CR0.TS and CR4 filters armed on a vCPU which has run: values kept, writes exit\n");
+
+ /* Stage 1: unfiltered-bit write, no reg_write exit. */
+ expect_sync(vcpu, 1);
+
+ /* Stage 2: filtered CR4 write, performed by userspace. */
+ run = expect_reg_write(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ TEST_ASSERT(!(run->reg_write.old_value & FILTERED_CR4_BIT),
+ "Old CR4 value already has the filtered bit");
+ TEST_ASSERT(run->reg_write.new_value & FILTERED_CR4_BIT,
+ "New CR4 value lacks the filtered bit");
+ perform_reg_write(vcpu);
+ expect_sync(vcpu, 2);
+
+ /*
+ * Stage 3: left alone with nothing changed, the write runs again
+ * and exits again, at the same RIP.
+ */
+ run = expect_reg_write(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ TEST_ASSERT(run->reg_write.old_value & FILTERED_CR4_BIT,
+ "Old CR4 value lacks the filtered bit");
+ vcpu_regs_get(vcpu, ®s);
+ rip = regs.rip;
+ leave_reg_write(vcpu, KVM_INSN_RESUME, -1, false);
+ expect_reg_write(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ vcpu_regs_get(vcpu, ®s);
+ TEST_ASSERT_EQ(regs.rip, rip);
+ perform_reg_write(vcpu);
+ expect_sync(vcpu, 3);
+ pr_info("MOV to CR4 (intercepted): KVM_INSN_RESUME alone\n");
+
+ /*
+ * Stage 4: refused by KVM with #GP(0) and with #UD, then by
+ * userspace with #NM queued.
+ */
+ refuse_reg_writes(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN,
+ "MOV to CR4 (intercepted)");
+ expect_sync(vcpu, 4);
+
+ /*
+ * Stage 5: left alone with RIP moved past the write, which KVM
+ * then neither performs nor retires again.
+ */
+ run = expect_reg_write(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ leave_reg_write(vcpu, KVM_INSN_RESUME, -1, false);
+ vcpu_regs_get(vcpu, ®s);
+ regs.rip += run->reg_write.insn_len;
+ vcpu_regs_set(vcpu, ®s);
+ expect_sync(vcpu, 5);
+ pr_info("MOV to CR4 (intercepted): KVM_INSN_RESUME with RIP moved\n");
+
+ /* Stage 6: CR0.TS set by MOV, cleared by CLTS, set by LMSW. */
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR0, MOV_TO_CR0_LEN);
+ TEST_ASSERT(run->reg_write.new_value & X86_CR0_TS,
+ "New CR0 value lacks TS");
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR0, CLTS_LEN);
+ TEST_ASSERT((run->reg_write.old_value & X86_CR0_TS) &&
+ !(run->reg_write.new_value & X86_CR0_TS),
+ "CLTS exit does not clear TS (old 0x%llx new 0x%llx)",
+ run->reg_write.old_value, run->reg_write.new_value);
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR0, LMSW_LEN);
+ TEST_ASSERT(run->reg_write.new_value & X86_CR0_TS,
+ "LMSW exit does not set TS");
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR0, CLTS_LEN);
+ expect_sync(vcpu, 6);
+
+ /* Stage 7: XSETBV, both directions. */
+ if (have_avx) {
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_XCR0,
+ XSETBV_LEN);
+ TEST_ASSERT(!(run->reg_write.new_value & XFEATURE_MASK_YMM),
+ "New XCR0 value retains YMM");
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_XCR0, XSETBV_LEN);
+
+ /* A prefix makes the instruction longer, and KVM says so. */
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_XCR0,
+ REX_XSETBV_LEN);
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_XCR0, XSETBV_LEN);
+ pr_info("XSETBV (intercepted): performed, also with a REX prefix\n");
+
+ if (is_forced_emulation_enabled) {
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_XCR0,
+ XSETBV_LEN);
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_XCR0,
+ XSETBV_LEN);
+ pr_info("XSETBV (forced emulation): performed\n");
+ } else {
+ pr_info("XSETBV (forced emulation): not run, set kvm.force_emulation_prefix=1\n");
+ }
+ } else {
+ pr_info("XSETBV: not run, no AVX to take away\n");
+ }
+ expect_sync(vcpu, 7);
+
+ /* Stage 8: descriptor tables. */
+ if (have_dt_filters) {
+ /*
+ * LGDT reaches KVM through the emulator, which then retires
+ * it. Single-step across that one too.
+ */
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_GDTR,
+ LGDT_LEN);
+ TEST_ASSERT_EQ(run->reg_write.new_value,
+ run->reg_write.old_value);
+ TEST_ASSERT_EQ(run->reg_write.new_limit,
+ run->reg_write.old_limit);
+ vcpu_regs_get(vcpu, ®s);
+ rip = regs.rip;
+ debug.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
+ vcpu_guest_debug_set(vcpu, &debug);
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_DEBUG);
+ TEST_ASSERT_EQ(vcpu->run->debug.arch.pc, rip + LGDT_LEN);
+ debug.control = 0;
+ vcpu_guest_debug_set(vcpu, &debug);
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_IDTR,
+ LIDT_LEN);
+ TEST_ASSERT_EQ(run->reg_write.new_value,
+ run->reg_write.old_value);
+ TEST_ASSERT_EQ(run->reg_write.new_limit,
+ run->reg_write.old_limit);
+ /* TR stays as it is: userspace performs nothing. */
+ run = expect_reg_write(vcpu, KVM_X86_REG_FILTER_TR, LTR_LEN);
+ TEST_ASSERT_EQ(run->reg_write.new_value,
+ run->reg_write.old_value);
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_LDTR,
+ LLDT_LEN);
+ TEST_ASSERT_EQ(run->reg_write.new_value, 0);
+ pr_info("LGDT, LIDT, LTR, LLDT (emulated): performed\n");
+ /* The same refusals from the emulator's completion. */
+ refuse_reg_writes(vcpu, KVM_X86_REG_FILTER_GDTR, LGDT_LEN,
+ "LGDT (emulated)");
+ } else {
+ pr_info("LGDT (emulated): not run, no descriptor-table filters\n");
+ }
+ expect_sync(vcpu, 8);
+
+ /*
+ * Stage 9: single-step across a performed write. The step is
+ * reported once the instruction has retired, at the next one.
+ */
+ expect_reg_write(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ vcpu_regs_get(vcpu, ®s);
+ rip = regs.rip;
+ perform_reg_write(vcpu);
+ debug.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
+ vcpu_guest_debug_set(vcpu, &debug);
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_DEBUG);
+ TEST_ASSERT_EQ(vcpu->run->debug.arch.pc, rip + MOV_TO_CR4_LEN);
+ debug.control = 0;
+ vcpu_guest_debug_set(vcpu, &debug);
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR4, MOV_TO_CR4_LEN);
+ expect_sync(vcpu, 9);
+
+ /*
+ * Stage 10: the SMM handler sets and clears the filtered CR4 bit
+ * with no filter exit; the first exit after RSM is the guest's own
+ * filtered write, with the full (non-SMM) CR4 as the old value.
+ */
+ expect_sync(vcpu, 10);
+ if (have_smm) {
+ struct kvm_vcpu_events events;
+
+ /* The handler says that it runs, in SMM. */
+ inject_smi(vcpu);
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ TEST_ASSERT_EQ(vcpu->run->io.port, SMM_PORT);
+ vcpu_events_get(vcpu, &events);
+ TEST_ASSERT(events.smi.smm, "The SMI handler runs outside SMM");
+
+ run = reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR4,
+ MOV_TO_CR4_LEN);
+ TEST_ASSERT(run->reg_write.old_value &&
+ !(run->reg_write.old_value & FILTERED_CR4_BIT),
+ "Unexpected old CR4 0x%llx: SMM write filtered?",
+ run->reg_write.old_value);
+ TEST_ASSERT(run->reg_write.new_value & FILTERED_CR4_BIT,
+ "New CR4 value lacks the filtered bit");
+ reg_write_performed(vcpu, KVM_X86_REG_FILTER_CR4,
+ MOV_TO_CR4_LEN);
+ }
+ expect_sync(vcpu, 11);
+ pr_info("SMM: %s\n", have_smm ? "the handler ran, its CR4 writes took no exit" :
+ "not run, no KVM_CAP_X86_SMM");
+
+ /*
+ * The sibling vCPU has no filters and must run straight through,
+ * while this vCPU's are all still armed.
+ */
+ expect_done(sibling);
+
+ /* Stage 12: disarmed, the same writes take no exit. */
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR4, 0);
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR0, 0);
+ if (have_avx)
+ set_filter(vcpu, KVM_X86_REG_FILTER_XCR0, 0);
+ if (have_dt_filters) {
+ set_filter(vcpu, KVM_X86_REG_FILTER_GDTR, 0);
+ set_filter(vcpu, KVM_X86_REG_FILTER_IDTR, 0);
+ set_filter(vcpu, KVM_X86_REG_FILTER_LDTR, 0);
+ set_filter(vcpu, KVM_X86_REG_FILTER_TR, 0);
+ }
+ expect_sync(vcpu, 12);
+ pr_info("MOV to CR4, MOV to CR0, CLTS%s%s: no exit once the filters are disarmed\n",
+ have_avx ? ", XSETBV" : "",
+ have_dt_filters ? ", LGDT, LIDT, LLDT" : "");
+
+ expect_done(vcpu);
+
+ kvm_vm_free(vm);
+
+ test_reset();
+ return 0;
+}
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* [PATCH v3 15/15] KVM: selftests: Test the register write filter with a nested guest
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
` (13 preceding siblings ...)
2026-11-27 15:27 ` [PATCH v3 14/15] KVM: selftests: Add x86 register write filter test David Woodhouse
@ 2026-11-27 15:27 ` David Woodhouse
2026-11-27 15:47 ` sashiko-bot
14 siblings, 1 reply; 21+ messages in thread
From: David Woodhouse @ 2026-11-27 15:27 UTC (permalink / raw)
To: kvm
Cc: linux-kernel, linux-hyperv, linux-kselftest, linux-doc,
Paolo Bonzini, Sean Christopherson, Vitaly Kuznetsov,
Marcelo Tosatti, Joerg Roedel, Tom Lendacky, James Bottomley,
Thara Gopinath, Wei Liu, Michael Kelley, Nicolas Saenz Julienne,
Nikolas Wipper, Mushahid Hussain, Sriram Nambakam, Zack Rusin,
Doug Covelli, Jim Mattson, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, Dave Hansen, x86, H . Peter Anvin,
Jonathan Corbet, Randy Dunlap, Shuah Khan, Paul Durrant, Xin Li,
Francesco Lavra, Radim Krčmář, Liran Alon,
Arbel Moshe, David Woodhouse
From: David Woodhouse <dwmw@amazon.co.uk>
L1 and L2 share XCR0. Check that an XSETBV which KVM performs for L2
is filtered (SVM only), that one which exits to L1 is not, and that
filtered CR0 and CR4 bits which L2 writes are not. On VMX, check that
a CR4 bit filtered for L1 stays L2's to own across a VMRESUME for which
KVM recomputes nothing: the test resumes L2 itself, as the library's
helper writes host state fields before every entry.
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
---
tools/testing/selftests/kvm/Makefile.kvm | 1 +
.../kvm/x86/nested_reg_write_filter_test.c | 362 ++++++++++++++++++
2 files changed, 363 insertions(+)
create mode 100644 tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 6fcf54f58c48..5b4bc0ec37ad 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -104,6 +104,7 @@ TEST_GEN_PROGS_x86 += x86/nested_dirty_log_test
TEST_GEN_PROGS_x86 += x86/nested_emulation_test
TEST_GEN_PROGS_x86 += x86/nested_exceptions_test
TEST_GEN_PROGS_x86 += x86/nested_invalid_cr3_test
+TEST_GEN_PROGS_x86 += x86/nested_reg_write_filter_test
TEST_GEN_PROGS_x86 += x86/nested_set_state_test
TEST_GEN_PROGS_x86 += x86/nested_tdp_fault_test
TEST_GEN_PROGS_x86 += x86/nested_tsc_adjust_test
diff --git a/tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c b/tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c
new file mode 100644
index 000000000000..4977b3d5f64b
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c
@@ -0,0 +1,362 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Test the register write filters of a vCPU which runs a nested guest.
+ *
+ * XCR0 is shared by L1 and L2, so an XSETBV which KVM performs for L2 must
+ * be filtered like L1's own. On AMD CPUs L1 chooses whether to intercept
+ * XSETBV: without the intercept the write takes KVM_EXIT_X86_REG_WRITE with
+ * the vCPU in guest mode, with it the exit is L1's and userspace sees
+ * nothing. On Intel CPUs XSETBV in L2 always exits to L1, so only the
+ * XSETBV which L1 then executes itself is filtered.
+ *
+ * CR0 and CR4 writes of L2 are not filtered: they change L2's registers.
+ * L2 writes a filtered CR0 bit and a filtered CR4 bit which KVM intercepts
+ * (on Intel CPUs, bits which KVM does not let a guest own), and neither
+ * write may exit to userspace.
+ *
+ * On Intel CPUs a CR4 filter takes the filtered bits away from L1 in
+ * vmcs01, and must not take them away from L2 as well: a bit which L2 owns
+ * and changes after a VMRESUME has to show in vmcs12. That takes a
+ * VMRESUME for which KVM has nothing to recompute, i.e. one before which
+ * L1 wrote none but the fields a shadow VMCS would let it write. The
+ * library's vmresume() writes HOST_RSP and HOST_RIP every time, so this
+ * test resumes L2 twice from one stack frame by itself.
+ *
+ * Copyright © 2026 Amazon.com, Inc. or its affiliates.
+ */
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+#include "svm_util.h"
+#include "vmx.h"
+
+#define LEGACY (XFEATURE_MASK_FP | XFEATURE_MASK_SSE)
+#define FILTERED_CR4_BIT X86_CR4_TSD
+/* Bits which KVM never lets a guest own: a write to them always exits. */
+#define INTERCEPTED_CR4_BIT X86_CR4_MCE
+#define INTERCEPTED_CR0_BIT X86_CR0_MP
+#define XSETBV_LEN 3
+
+enum {
+ STAGE_READY = 1,
+ STAGE_L2_XSETBV,
+ STAGE_L1_XSETBV,
+ STAGE_L2_CR4,
+};
+
+static void l2_svm_code(void)
+{
+ xsetbv(0, LEGACY);
+
+ /* KVM intercepts both for a vCPU with a CR0 filter armed. */
+ set_cr0(get_cr0() ^ INTERCEPTED_CR0_BIT);
+ set_cr4(get_cr4() | FILTERED_CR4_BIT);
+ vmmcall();
+}
+
+static void l1_svm_code(struct svm_test_data *svm)
+{
+ struct vmcb *vmcb = svm->vmcb;
+ u64 xcr0 = xgetbv(0);
+
+ GUEST_ASSERT(xcr0 & XFEATURE_MASK_YMM);
+ GUEST_SYNC(STAGE_READY);
+
+ /* L1 leaves XSETBV to L0, which performs it for L2. */
+ generic_svm_setup(svm, l2_svm_code);
+ run_guest(vmcb, svm->vmcb_gpa);
+ GUEST_ASSERT_EQ(vmcb->control.exit_code, SVM_EXIT_VMMCALL);
+ /* L2 started with L1's CR0 and CR4, and its writes took effect. */
+ GUEST_ASSERT((vmcb->save.cr0 ^ get_cr0()) & INTERCEPTED_CR0_BIT);
+ GUEST_ASSERT(vmcb->save.cr4 & FILTERED_CR4_BIT);
+ GUEST_ASSERT(!(get_cr4() & FILTERED_CR4_BIT));
+ GUEST_SYNC_ARGS(STAGE_L2_XSETBV, xgetbv(0), 0, 0, 0);
+
+ /* Userspace has put XCR0 back. Now L1 intercepts XSETBV. */
+ GUEST_ASSERT_EQ(xgetbv(0), xcr0);
+ generic_svm_setup(svm, l2_svm_code);
+ vmcb->control.intercept |= BIT_ULL(INTERCEPT_XSETBV);
+ run_guest(vmcb, svm->vmcb_gpa);
+ GUEST_ASSERT_EQ(vmcb->control.exit_code, SVM_EXIT_XSETBV);
+ GUEST_SYNC_ARGS(STAGE_L1_XSETBV, xgetbv(0), 0, 0, 0);
+ GUEST_DONE();
+}
+
+static void l2_vmx_code(void)
+{
+ xsetbv(0, LEGACY);
+ vmcall();
+
+ /* Out to L1 once more, which resumes L2 with vmcs12 as it is. */
+ vmcall();
+
+ /* So L2 still owns this bit, and sets it without an exit. */
+ set_cr4(get_cr4() | FILTERED_CR4_BIT);
+
+ /* These two exit to KVM, which must not filter them. */
+ set_cr4(get_cr4() | INTERCEPTED_CR4_BIT);
+ set_cr0(get_cr0() ^ INTERCEPTED_CR0_BIT);
+ vmcall();
+}
+
+/* How often resume_twice() has come back from L2. */
+static u64 nr_resumed;
+
+/*
+ * Resume L2, step over the VMCALL it exits with, and resume it again having
+ * written nothing to the VMCS but GUEST_RIP. Both VM-exits land on the
+ * same label with the same stack pointer, so HOST_RSP and HOST_RIP are
+ * written once, before the first VMRESUME. Returns non-zero if a VMRESUME
+ * failed.
+ */
+static noinline u64 resume_twice(void)
+{
+ u64 failed;
+
+ nr_resumed = 0;
+ asm volatile("push %%rbp\n\t"
+ "mov %[host_rsp], %%eax\n\t"
+ "vmwrite %%rsp, %%rax\n\t"
+ "lea 1f(%%rip), %%rbx\n\t"
+ "mov %[host_rip], %%eax\n\t"
+ "vmwrite %%rbx, %%rax\n\t"
+ "vmresume\n\t"
+ "jmp 3f\n\t"
+ "1: incq %[nr]\n\t"
+ "cmpq $1, %[nr]\n\t"
+ "jne 2f\n\t"
+ "mov %[insn_len], %%eax\n\t"
+ "vmread %%rax, %%rcx\n\t"
+ "mov %[guest_rip], %%eax\n\t"
+ "vmread %%rax, %%rdx\n\t"
+ "add %%rcx, %%rdx\n\t"
+ "vmwrite %%rdx, %%rax\n\t"
+ "vmresume\n\t"
+ "jmp 3f\n\t"
+ "2: xor %%eax, %%eax\n\t"
+ "jmp 4f\n\t"
+ "3: mov $1, %%eax\n\t"
+ "4: pop %%rbp\n\t"
+ : "=&a"(failed), [nr] "+m"(nr_resumed)
+ : [host_rsp] "i"(HOST_RSP), [host_rip] "i"(HOST_RIP),
+ [insn_len] "i"(VM_EXIT_INSTRUCTION_LEN),
+ [guest_rip] "i"(GUEST_RIP)
+ : "cc", "memory", "rbx", "rcx", "rdx", "rsi", "rdi",
+ "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15");
+ return failed;
+}
+
+static void l1_vmx_code(struct vmx_pages *vmx)
+{
+ u64 xcr0 = xgetbv(0);
+
+ GUEST_ASSERT(xcr0 & XFEATURE_MASK_YMM);
+ prepare_for_vmx_operation(vmx);
+ load_vmcs(vmx);
+ prepare_vmcs(vmx, l2_vmx_code);
+ GUEST_ASSERT(!(vmread(GUEST_CR4) & FILTERED_CR4_BIT));
+ GUEST_ASSERT(!(vmread(CR4_GUEST_HOST_MASK) & FILTERED_CR4_BIT));
+ GUEST_SYNC(STAGE_READY);
+
+ /* XSETBV in L2 exits to L1, whatever L1 asked for. */
+ vmlaunch();
+ GUEST_ASSERT_EQ(vmread(VM_EXIT_REASON), EXIT_REASON_XSETBV);
+ GUEST_SYNC_ARGS(STAGE_L2_XSETBV, xgetbv(0), 0, 0, 0);
+
+ /* L1 makes the write for L2, as a hypervisor would: L1's own. */
+ xsetbv(0, LEGACY);
+ GUEST_SYNC_ARGS(STAGE_L1_XSETBV, xgetbv(0), 0, 0, 0);
+
+ /* Skip L2's XSETBV, and the VMCALL after it. */
+ vmwrite(GUEST_RIP, vmread(GUEST_RIP) + vmread(VM_EXIT_INSTRUCTION_LEN));
+ vmresume();
+ GUEST_ASSERT_EQ(vmread(VM_EXIT_REASON), EXIT_REASON_VMCALL);
+ vmwrite(GUEST_RIP, vmread(GUEST_RIP) + vmread(VM_EXIT_INSTRUCTION_LEN));
+
+ /*
+ * The first VMRESUME below recomputes everything for vmcs02, the
+ * second nothing. After it L2 sets the CR4 bit which is filtered
+ * for L1, without an exit: it is L2's to own, and vmcs12 must
+ * show it.
+ */
+ GUEST_ASSERT(!resume_twice());
+ GUEST_ASSERT_EQ(nr_resumed, 2);
+ GUEST_ASSERT_EQ(vmread(VM_EXIT_REASON), EXIT_REASON_VMCALL);
+ GUEST_ASSERT(vmread(GUEST_CR4) & INTERCEPTED_CR4_BIT);
+ GUEST_ASSERT((vmread(GUEST_CR0) ^ get_cr0()) & INTERCEPTED_CR0_BIT);
+ GUEST_SYNC_ARGS(STAGE_L2_CR4, vmread(GUEST_CR4), 0, 0, 0);
+ GUEST_DONE();
+}
+
+static void set_filter(struct kvm_vcpu *vcpu, u32 reg, u64 mask)
+{
+ struct kvm_x86_reg_write_filter filter = {
+ .reg = reg,
+ .mask = mask,
+ };
+
+ vcpu_ioctl(vcpu, KVM_X86_SET_REG_WRITE_FILTER, &filter);
+}
+
+static void set_xcr0(struct kvm_vcpu *vcpu, u64 xcr0)
+{
+ struct kvm_xcrs xcrs = {
+ .nr_xcrs = 1,
+ .xcrs[0].value = xcr0,
+ };
+
+ vcpu_xcrs_set(vcpu, &xcrs);
+}
+
+/*
+ * Run to the guest's next sync, performing every filtered XCR0 write on the
+ * way. Returns the value the guest reported; counts the exits, and those
+ * of them which were taken in guest mode.
+ */
+static u64 run_to_sync(struct kvm_vcpu *vcpu, u64 stage, int *exits,
+ int *nested_exits)
+{
+ struct kvm_run *run = vcpu->run;
+ struct ucall uc;
+
+ *exits = 0;
+ *nested_exits = 0;
+
+ for (;;) {
+ vcpu_run(vcpu);
+ if (run->exit_reason == KVM_EXIT_X86_REG_WRITE) {
+ TEST_ASSERT_EQ(run->reg_write.reg, KVM_X86_REG_FILTER_XCR0);
+ TEST_ASSERT_EQ(run->reg_write.new_value, LEGACY);
+ TEST_ASSERT_EQ(run->reg_write.insn_len, XSETBV_LEN);
+ set_xcr0(vcpu, run->reg_write.new_value);
+ (*exits)++;
+ if (run->flags & KVM_RUN_X86_GUEST_MODE)
+ (*nested_exits)++;
+ continue;
+ }
+
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ switch (get_ucall(vcpu, &uc)) {
+ case UCALL_SYNC:
+ TEST_ASSERT_EQ(uc.args[1], stage);
+ return uc.args[2];
+ case UCALL_ABORT:
+ REPORT_GUEST_ASSERT(uc);
+ default:
+ TEST_FAIL("Unexpected ucall %lu, wanted sync %lu",
+ uc.cmd, stage);
+ }
+ }
+}
+
+static void expect_done(struct kvm_vcpu *vcpu)
+{
+ struct ucall uc;
+
+ vcpu_run(vcpu);
+ TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+ if (get_ucall(vcpu, &uc) == UCALL_ABORT)
+ REPORT_GUEST_ASSERT(uc);
+ TEST_ASSERT_EQ(uc.cmd, UCALL_DONE);
+}
+
+static void test_svm(struct kvm_vcpu *vcpu, u64 full)
+{
+ int exits, nested;
+ u64 xcr0;
+
+ xcr0 = run_to_sync(vcpu, STAGE_L2_XSETBV, &exits, &nested);
+ TEST_ASSERT(exits == 1 && nested == 1,
+ "XSETBV in L2, not intercepted by L1: %d filter exits, %d in guest mode, wanted one of each (XCR0 0x%lx)",
+ exits, nested, xcr0);
+ TEST_ASSERT_EQ(xcr0, LEGACY);
+ pr_info("SVM, XSETBV in L2 which L1 does not intercept: filtered, in guest mode\n");
+ pr_info("SVM, filtered CR0 and CR4 bits written by L2, intercepted by KVM: not filtered\n");
+
+ /* Put XCR0 back from userspace: a state load, not filtered. */
+ set_xcr0(vcpu, full);
+
+ xcr0 = run_to_sync(vcpu, STAGE_L1_XSETBV, &exits, &nested);
+ TEST_ASSERT(!exits, "XSETBV in L2, intercepted by L1: %d filter exits",
+ exits);
+ TEST_ASSERT_EQ(xcr0, full);
+ pr_info("SVM, XSETBV in L2 which L1 intercepts: L1's exit, not filtered\n");
+}
+
+static void test_vmx(struct kvm_vcpu *vcpu, u64 full)
+{
+ int exits, nested;
+ u64 val;
+
+ val = run_to_sync(vcpu, STAGE_L2_XSETBV, &exits, &nested);
+ TEST_ASSERT(!exits, "XSETBV in L2: %d filter exits before L1's own",
+ exits);
+ TEST_ASSERT_EQ(val, full);
+ pr_info("VMX, XSETBV in L2: always L1's exit, not filtered\n");
+
+ val = run_to_sync(vcpu, STAGE_L1_XSETBV, &exits, &nested);
+ TEST_ASSERT(exits == 1 && !nested,
+ "XSETBV by L1 for L2: %d filter exits, %d in guest mode, wanted one outside it",
+ exits, nested);
+ TEST_ASSERT_EQ(val, LEGACY);
+ pr_info("VMX, XSETBV which L1 executes for L2: filtered\n");
+
+ val = run_to_sync(vcpu, STAGE_L2_CR4, &exits, &nested);
+ TEST_ASSERT(!exits, "CR4 write in L2: %d filter exits", exits);
+ TEST_ASSERT(val & FILTERED_CR4_BIT,
+ "vmcs12 guest CR4 0x%lx lacks the bit L2 set after a VMRESUME with nothing to recompute",
+ val);
+ pr_info("VMX, CR4 bit filtered for L1 and owned by L2: unfiltered, and in vmcs12 after a VMRESUME with nothing to recompute\n");
+ pr_info("VMX, filtered CR0 and CR4 bits written by L2, intercepted by KVM: not filtered\n");
+}
+
+int main(int argc, char *argv[])
+{
+ bool svm = kvm_cpu_has(X86_FEATURE_SVM);
+ struct kvm_xcrs xcrs = {};
+ struct kvm_vcpu *vcpu;
+ gva_t nested_gva = 0;
+ int exits, nested;
+ struct kvm_vm *vm;
+ u32 filters;
+ u64 full;
+
+ TEST_REQUIRE(svm || kvm_cpu_has(X86_FEATURE_VMX));
+ TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_AVX));
+ TEST_REQUIRE(kvm_has_cap(KVM_CAP_X86_REG_WRITE_FILTER));
+
+ filters = kvm_check_cap(KVM_CAP_X86_REG_WRITE_FILTER);
+ TEST_REQUIRE(filters & BIT(KVM_X86_REG_FILTER_XCR0));
+ TEST_REQUIRE(filters & BIT(KVM_X86_REG_FILTER_CR0));
+ TEST_REQUIRE(filters & BIT(KVM_X86_REG_FILTER_CR4));
+
+ vm = vm_create_with_one_vcpu(&vcpu, svm ? (void *)l1_svm_code :
+ (void *)l1_vmx_code);
+ if (svm)
+ vcpu_alloc_svm(vm, &nested_gva);
+ else
+ vcpu_alloc_vmx(vm, &nested_gva);
+ vcpu_args_set(vcpu, 1, nested_gva);
+
+ /* L1 gets ready with nothing filtered; then arm. */
+ run_to_sync(vcpu, STAGE_READY, &exits, &nested);
+ TEST_ASSERT_EQ(exits, 0);
+ vcpu_xcrs_get(vcpu, &xcrs);
+ full = xcrs.xcrs[0].value;
+ set_filter(vcpu, KVM_X86_REG_FILTER_XCR0, XFEATURE_MASK_YMM);
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR0, INTERCEPTED_CR0_BIT);
+ set_filter(vcpu, KVM_X86_REG_FILTER_CR4,
+ FILTERED_CR4_BIT | INTERCEPTED_CR4_BIT);
+
+ if (svm) {
+ test_svm(vcpu, full);
+ pr_info("VMX legs: not run, this is an AMD CPU\n");
+ } else {
+ test_vmx(vcpu, full);
+ pr_info("SVM legs: not run, this is an Intel CPU\n");
+ }
+
+ expect_done(vcpu);
+ kvm_vm_free(vm);
+ return 0;
+}
--
2.50.1
^ permalink raw reply related [flat|nested] 21+ messages in thread
* Re: [PATCH v3 15/15] KVM: selftests: Test the register write filter with a nested guest
2026-11-27 15:27 ` [PATCH v3 15/15] KVM: selftests: Test the register write filter with a nested guest David Woodhouse
@ 2026-11-27 15:47 ` sashiko-bot
0 siblings, 0 replies; 21+ messages in thread
From: sashiko-bot @ 2026-11-27 15:47 UTC (permalink / raw)
To: David Woodhouse, kvm; +Cc: linux-hyperv
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] KVM: selftests: intercepted CR4 write in l2_vmx_code() masks
clean-vmcs12 bug
--
commit 6862822e0c88af446e20e6806bc0fab3b0651065
Author: David Woodhouse <dwmw@amazon.co.uk>
KVM: selftests: Test the register write filter with a nested guest
This commit adds an x86 KVM selftest to verify XCR0, CR0, and CR4 register
write filter behavior across L1 and L2 on SVM and VMX.
> diff --git a/tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c b/tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c
> new file mode 100644
> index 0000000000000..4977b3d5f64bd
> --- /dev/null
> +++ b/tools/testing/selftests/kvm/x86/nested_reg_write_filter_test.c
[ ... ]
> +static void l2_vmx_code(void)
> +{
> + xsetbv(0, LEGACY);
> + vmcall();
> +
> + /* Out to L1 once more, which resumes L2 with vmcs12 as it is. */
> + vmcall();
> +
> + /* So L2 still owns this bit, and sets it without an exit. */
> + set_cr4(get_cr4() | FILTERED_CR4_BIT);
> +
> + /* These two exit to KVM, which must not filter them. */
> + set_cr4(get_cr4() | INTERCEPTED_CR4_BIT);
> + set_cr0(get_cr0() ^ INTERCEPTED_CR0_BIT);
> + vmcall();
> +}
[Severity: Medium]
Does writing INTERCEPTED_CR4_BIT after FILTERED_CR4_BIT cause the
STAGE_L2_CR4 check in test_vmx() to pass even if KVM fails to update
vcpu->arch.cr4_guest_owned_bits on the second VMRESUME in resume_twice()?
The first VMRESUME in resume_twice() has a dirty vmcs12, so
prepare_vmcs02_rare() clears FILTERED_CR4_BIT in vmcs02's hardware
CR4_GUEST_HOST_MASK. The nested VM-exit to L1 then clears FILTERED_CR4_BIT
from vcpu->arch.cr4_guest_owned_bits via vmx_refresh_reg_write_filter(),
while vmcs02's hardware CR4_GUEST_HOST_MASK keeps FILTERED_CR4_BIT clear.
Even if the second (clean-vmcs12) VMRESUME skips updating
vcpu->arch.cr4_guest_owned_bits, setting FILTERED_CR4_BIT in L2 updates
hardware GUEST_CR4 without an exit. The subsequent get_cr4() |
INTERCEPTED_CR4_BIT then reads FILTERED_CR4_BIT = 1 from hardware GUEST_CR4
and triggers a CR4 VM-exit to KVM, where handle_set_cr4() writes the full
register value (including FILTERED_CR4_BIT) into vmcs02's CR4_READ_SHADOW.
When L2 later exits on vmcall(), vmcs12_guest_cr4() pulls FILTERED_CR4_BIT
from CR4_READ_SHADOW into vmcs12->guest_cr4 regardless of
vcpu->arch.cr4_guest_owned_bits.
Setting INTERCEPTED_CR4_BIT before FILTERED_CR4_BIT avoids populating
CR4_READ_SHADOW with FILTERED_CR4_BIT.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261127152730.99319-1-dwmw2@infradead.org?part=15
^ permalink raw reply [flat|nested] 21+ messages in thread
* Re: [PATCH v3 10/15] KVM: x86: Filter emulated CR0 and CR4 writes
2026-11-27 15:27 ` [PATCH v3 10/15] KVM: x86: Filter emulated CR0 and CR4 writes David Woodhouse
@ 2026-11-27 15:48 ` sashiko-bot
0 siblings, 0 replies; 21+ messages in thread
From: sashiko-bot @ 2026-11-27 15:48 UTC (permalink / raw)
To: David Woodhouse, kvm; +Cc: linux-hyperv
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] KVM: x86: 32-bit truncation of CR0/CR4 writes in
emulator_filter_cr_write()
--
commit 08515d18b5f74a7d7b3ddcb78d650f9907df852f
Author: David Woodhouse <dwmw@amazon.co.uk>
KVM: x86: Filter emulated CR0 and CR4 writes
This commit adds register write filter checks to the x86 emulator's MOV to CR,
CLTS, and LMSW instruction handlers so filtered CR0 and CR4 writes exit to
userspace with KVM_EXIT_X86_REG_WRITE.
> diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
> index b559c7880e546..4e6f0cb80288c 100644
> --- a/arch/x86/kvm/x86.c
> +++ b/arch/x86/kvm/x86.c
> @@ -5846,6 +5846,42 @@ static int emulator_filter_xcr_write(struct x86_emulate_ctxt *ctxt, u32 index,
> vcpu->arch.xcr0, xcr);
> }
>
> +/*
> + * Divert an emulated CR0/CR4 write into a KVM_EXIT_X86_REG_WRITE exit when
> + * it hits a write filter. Called by the instruction handlers (MOV to CR,
> + * CLTS, LMSW) before any architectural effect; state loads that reach
> + * ->set_cr() on other instructions' behalf (RSM, task switches) are not
> + * guest register writes and stay unfiltered.
> + */
> +static int emulator_filter_cr_write(struct x86_emulate_ctxt *ctxt, int cr,
> + ulong val)
> +{
> + struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
> + u64 old_value, new_value;
> + u32 reg;
> +
> + switch (cr) {
> + case 0:
> + reg = KVM_X86_REG_FILTER_CR0;
> + old_value = kvm_read_cr0(vcpu);
> + break;
> + case 4:
> + reg = KVM_X86_REG_FILTER_CR4;
> + old_value = kvm_read_cr4(vcpu);
> + break;
> + default:
> + return X86EMUL_CONTINUE;
> + }
> +
> + /* Match the merge emulator_set_cr() will do with the same value. */
> + new_value = mk_cr_64(old_value, val);
> +
> + if (!kvm_reg_write_filtered(vcpu, reg, old_value, new_value))
> + return X86EMUL_CONTINUE;
> +
> + return emulator_reg_write_exit(ctxt, reg, old_value, new_value);
> +}
[Severity: Medium]
Does calling mk_cr_64() here truncate the upper 32 bits of val on 64-bit
MOV to CR0/CR4?
arch/x86/kvm/x86.c:mk_cr_64() {
static u64 mk_cr_64(u64 curr_cr, u32 new_val)
{
return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
}
}
Because mk_cr_64() takes a u32 new_val, passing the 64-bit operand val
discards bits 63:32 and replaces them with old_value[63:32] (which are zero
for CR0 and CR4). When a 64-bit guest executes an emulated MOV to CR0 or
CR4 with any upper bits set, kvm_reg_write_filtered() cannot match filters
on bits 63:32, and vcpu->run->reg_write.new_value strips fault-inducing
reserved upper bits that userspace needs to see in order to reject the
write with KVM_INSN_GP.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261127152730.99319-1-dwmw2@infradead.org?part=10
^ permalink raw reply [flat|nested] 21+ messages in thread
* Re: [PATCH v3 12/15] KVM: SVM: Support CR0 and CR4 write filters
2026-11-27 15:27 ` [PATCH v3 12/15] KVM: SVM: " David Woodhouse
@ 2026-11-27 15:49 ` sashiko-bot
0 siblings, 0 replies; 21+ messages in thread
From: sashiko-bot @ 2026-11-27 15:49 UTC (permalink / raw)
To: David Woodhouse, kvm; +Cc: linux-hyperv
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] KVM: SVM: unnecessary INTERCEPT_CR0_WRITE for non-TS/MP
filters and L2 guests
--
commit 94f59c3becb8e9910d861b5136b68fa9775be16d
Author: David Woodhouse <dwmw@amazon.co.uk>
KVM: SVM: Support CR0 and CR4 write filters
This commit adds support for CR0 and CR4 register write filters on SVM by
keeping INTERCEPT_CR0_WRITE enabled while a CR0 filter is armed and
checking for filtered writes in cr_interception().
> diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c
> index 4ffb41234dc25..c91467a59e201 100644
> --- a/arch/x86/kvm/svm/svm.c
> +++ b/arch/x86/kvm/svm/svm.c
> @@ -1135,6 +1135,22 @@ static void svm_recalc_intercepts(struct kvm_vcpu *vcpu)
> svm_recalc_msr_intercepts(vcpu);
> }
>
> +static void svm_update_reg_write_filter(struct kvm_vcpu *vcpu)
> +{
> + struct vcpu_svm *svm = to_svm(vcpu);
> +
> + /*
> + * CR4 writes are always intercepted. CR0 writes are not when the
> + * guest and host views agree (hcr0 == cr0): force the intercept in
> + * vmcb01 while a CR0 filter is armed. Disarming leaves the
> + * intercept in place - a forced intercept only costs exits, which
> + * cr_interception() handles as usual - and the next svm_set_cr0(),
> + * which respects the filter, restores its own state.
> + */
> + if (vcpu->arch.reg_write_filter_armed & BIT(KVM_X86_REG_FILTER_CR0))
> + svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
> +}
> +
> static void init_vmcb(struct kvm_vcpu *vcpu, bool init_event)
> {
> struct vcpu_svm *svm = to_svm(vcpu);
> @@ -1867,7 +1883,13 @@ void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
> if (hcr0 == cr0) {
> /* Selective CR0 write remains on. */
> svm_clr_intercept(svm, INTERCEPT_CR0_READ);
> - svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
> + /*
> + * The selective intercept misses writes that change only
> + * TS or MP, and CLTS: a CR0 write filter needs them all.
> + */
> + if (!(vcpu->arch.reg_write_filter_armed &
> + BIT(KVM_X86_REG_FILTER_CR0)))
> + svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
> } else {
> svm_set_intercept(svm, INTERCEPT_CR0_READ);
> svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
[Severity: Medium]
Should INTERCEPT_CR0_WRITE only be forced when
vcpu->arch.reg_write_filter[KVM_X86_REG_FILTER_CR0] intersects
SVM_CR0_SELECTIVE_MASK (and when not running in L2 guest mode)?
INTERCEPT_SELECTIVE_CR0 is always enabled and already traps writes to any
CR0 bit outside CR0.TS and CR0.MP. Forcing INTERCEPT_CR0_WRITE for any
armed CR0 filter causes every guest CLTS and TS/MP-only CR0 write to
VM-exit (with CLTS falling back to the instruction emulator in
cr_interception() because CR_VALID is clear), even when userspace only
filters bits like CR0.WP.
Because nested_vmcb02_recalc_intercepts() copies vmcb01's intercepts into
vmcb02 and svm_set_cr0() also runs during nested entry, this also forces
INTERCEPT_CR0_WRITE on unfiltered L2 guests.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261127152730.99319-1-dwmw2@infradead.org?part=12
^ permalink raw reply [flat|nested] 21+ messages in thread
* Re: [PATCH v3 13/15] KVM: x86: Add descriptor-table registers to the write filter
2026-11-27 15:27 ` [PATCH v3 13/15] KVM: x86: Add descriptor-table registers to the write filter David Woodhouse
@ 2026-11-27 15:52 ` sashiko-bot
0 siblings, 0 replies; 21+ messages in thread
From: sashiko-bot @ 2026-11-27 15:52 UTC (permalink / raw)
To: David Woodhouse, kvm; +Cc: linux-hyperv
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] KVM: x86: em_lgdt_lidt() validates canonical base before
filter_dt_write()
--
commit a776c4d770743069de4432de278b52d34d58dbce
Author: David Woodhouse <dwmw@amazon.co.uk>
KVM: x86: Add descriptor-table registers to the write filter
This commit extends KVM_X86_SET_REG_WRITE_FILTER to support filtering guest
writes to GDTR, IDTR, LDTR, and TR via LGDT, LIDT, LLDT, and LTR across VMX
and SVM.
> diff --git a/arch/x86/kvm/emulate.c b/arch/x86/kvm/emulate.c
> index 9a4aebcccc958..b40e347c498f4 100644
> --- a/arch/x86/kvm/emulate.c
> +++ b/arch/x86/kvm/emulate.c
[ ... ]
> @@ -3489,6 +3512,11 @@ static int em_lgdt_lidt(struct x86_emulate_ctxt *ctxt, bool lgdt)
> emul_is_noncanonical_address(desc_ptr.address, ctxt,
> X86EMUL_F_DT_LOAD))
> return emulate_gp(ctxt, 0);
> + rc = ctxt->ops->filter_dt_write(ctxt, lgdt ? KVM_X86_REG_FILTER_GDTR :
> + KVM_X86_REG_FILTER_IDTR,
> + desc_ptr.address, desc_ptr.size);
> + if (rc != X86EMUL_CONTINUE)
> + return rc;
> if (lgdt)
> ctxt->ops->set_gdt(ctxt, &desc_ptr);
> else
[Severity: Medium]
Should em_lgdt_lidt() call filter_dt_write() before checking whether
desc_ptr.address is canonical?
The KVM_EXIT_X86_REG_WRITE documentation states that the exit is taken
before KVM validates the write, so new_value may be one for which the
instruction would have faulted (matching em_lldt(), em_ltr(), CR writes,
and XSETBV). Calling emul_is_noncanonical_address() first injects #GP(0)
into a 64-bit guest that loads a non-canonical GDTR or IDTR base instead
of exiting to userspace when a filter is armed.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261127152730.99319-1-dwmw2@infradead.org?part=13
^ permalink raw reply [flat|nested] 21+ messages in thread
* Re: [PATCH v3 02/15] KVM: Define what completing an exit does with its instruction
2026-11-27 15:27 ` [PATCH v3 02/15] KVM: Define what completing an exit does with its instruction David Woodhouse
@ 2026-11-27 15:55 ` sashiko-bot
0 siblings, 0 replies; 21+ messages in thread
From: sashiko-bot @ 2026-11-27 15:55 UTC (permalink / raw)
To: David Woodhouse, kvm; +Cc: linux-hyperv
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [High] KVM: x86: stale emulate_regs_need_sync_to_vcpu in
kvm_insn_uncompleted()
--
commit a2d5858612fe849c4fd217f459db157f10703c3f
Author: David Woodhouse <dwmw@amazon.co.uk>
KVM: Define what completing an exit does with its instruction
This commit defines KVM_INSN_COMPLETE, KVM_INSN_GP, KVM_INSN_UD, and
KVM_INSN_RESUME to let userspace choose how KVM handles an uncompleted
instruction after an exit, along with the x86 kvm_insn_uncompleted()
helper.
> diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h
> index 436e2fb1396c4..7e5ccbce9114f 100644
> --- a/arch/x86/kvm/x86.h
> +++ b/arch/x86/kvm/x86.h
> @@ -526,6 +526,38 @@ static inline void kvm_inject_gp(struct kvm_vcpu *vcpu, u32 error_code)
> kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
> }
>
> +/*
> + * Act on the KVM_INSN_* answer which userspace gave to an exit that left an
> + * instruction to complete. Returns 0 if the caller is to complete the
> + * instruction, 1 if there is nothing more to do for it, or -EINVAL.
> + *
> + * A guest whose state is protected does not execute the instruction again,
> + * and KVM cannot inject #UD into it: all that can be done there is to
> + * complete the exit, with an outcome which is the caller's to choose from
> + * the answer, or to ignore it.
> + */
> +static inline int kvm_insn_uncompleted(struct kvm_vcpu *vcpu, u8 answer)
> +{
> + if (vcpu->kvm->arch.has_protected_state ||
> + vcpu->arch.guest_state_protected)
> + return 0;
> +
> + switch (answer) {
> + case KVM_INSN_COMPLETE:
> + return 0;
> + case KVM_INSN_GP:
> + kvm_inject_gp(vcpu, 0);
> + return 1;
> + case KVM_INSN_UD:
> + kvm_queue_exception(vcpu, UD_VECTOR);
> + return 1;
> + case KVM_INSN_RESUME:
> + return 1;
> + default:
> + return -EINVAL;
> + }
> +}
[Severity: High]
Does kvm_insn_uncompleted() leave vcpu->arch.emulate_regs_need_sync_to_vcpu
set when returning 1 for an emulated instruction exit?
When x86_emulate_instruction() exits to userspace without writing back
registers, it sets vcpu->arch.emulate_regs_need_sync_to_vcpu = true, while
x86_decode_insn() has already marked register operands in ctxt->regs_dirty
via decode_register() -> reg_rmw(). If userspace responds with KVM_INSN_GP,
KVM_INSN_UD, or KVM_INSN_RESUME without calling KVM_GET_REGS or
KVM_SET_REGS, completion skips x86_emulate_instruction() and resumes the
guest with emulate_regs_need_sync_to_vcpu still true. A later __get_regs()
call then flushes the stale ctxt->_regs[] values over vcpu->arch.regs:
arch/x86/kvm/regs.c:__get_regs() {
if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
emulator_writeback_register_cache(vcpu->arch.emulate_ctxt);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
}
...
}
Clearing vcpu->arch.emulate_regs_need_sync_to_vcpu when skipping instruction
completion avoids clobbering guest GPRs after the guest resumes.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20261127152730.99319-1-dwmw2@infradead.org?part=2
^ permalink raw reply [flat|nested] 21+ messages in thread
end of thread, other threads:[~2026-11-27 15:55 UTC | newest]
Thread overview: 21+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-27 15:27 [PATCH v3 00/15] KVM: x86: Exit handling for Hyper-V hcalls, register intercept David Woodhouse
2026-11-27 15:27 ` [PATCH v3 01/15] KVM: selftests: Make the x86 SSE register helpers volatile David Woodhouse
2026-11-27 15:27 ` [PATCH v3 02/15] KVM: Define what completing an exit does with its instruction David Woodhouse
2026-11-27 15:55 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 03/15] KVM: x86: Let userspace leave an MSR access alone David Woodhouse
2026-11-27 15:27 ` [PATCH v3 04/15] KVM: selftests: Test MSR accesses which userspace leaves alone David Woodhouse
2026-11-27 15:27 ` [PATCH v3 05/15] KVM: x86: hyper-v: Add KVM_CAP_HYPERV_FORWARD_HCALL David Woodhouse
2026-11-27 15:27 ` [PATCH v3 06/15] KVM: x86: hyper-v: Let userspace leave a hypercall uncompleted David Woodhouse
2026-11-27 15:27 ` [PATCH v3 07/15] KVM: x86: hyper-v: Advertise XMM fast hypercall output David Woodhouse
2026-11-27 15:27 ` [PATCH v3 08/15] KVM: selftests: Add Hyper-V hypercall forwarding test David Woodhouse
2026-11-27 15:27 ` [PATCH v3 09/15] KVM: x86: Add a per-vCPU register write filter David Woodhouse
2026-11-27 15:27 ` [PATCH v3 10/15] KVM: x86: Filter emulated CR0 and CR4 writes David Woodhouse
2026-11-27 15:48 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 11/15] KVM: VMX: Support CR0 and CR4 write filters David Woodhouse
2026-11-27 15:27 ` [PATCH v3 12/15] KVM: SVM: " David Woodhouse
2026-11-27 15:49 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 13/15] KVM: x86: Add descriptor-table registers to the write filter David Woodhouse
2026-11-27 15:52 ` sashiko-bot
2026-11-27 15:27 ` [PATCH v3 14/15] KVM: selftests: Add x86 register write filter test David Woodhouse
2026-11-27 15:27 ` [PATCH v3 15/15] KVM: selftests: Test the register write filter with a nested guest David Woodhouse
2026-11-27 15:47 ` sashiko-bot
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox