Skip to contentSkip to conversation

KVM: x86: GPR accessors and x86.{c,h} spring cleaning

PATCH Superseded Sean Christopherson 5 participants 121 messages May 29 – Jun 8

Subsystems (6)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Sean Christopherson

author maintainer
#0 lore raw

v3 cover KVM: x86: GPR accessors and x86.{c,h} spring cleaning

The first half of this series adds proper, explicit "raw" versions of kvm_<reg>_{read,write}(), along with "e" versions (for hardcoded 32-bit accesses), and converts the existing kvm_<reg>_{read,write}() APIs into mode-aware variants.

At the end of that journey, introduce regs.{c,h} to avoid moving _more_ code into x86.h, especially since the resulting code split would be super arbitrary.

The second half of the series runs with the regs.{c,h} changes and performs spring cleaning on x86.{c,h} and asm/kvm_host.h (in case it wasn't already obvious, I have poor impulse control when it comes to cleaning up code).

I'm most intersted in getting feedback on the file names (regs.{c,h} and msrs.{c,h}. I'm quite confident the actual code split is the way to go, and pulling stuff out of asm/kvm_host.h has been on my wish/todo list for years.

I'll grab these fixes for 7.2 no matter what:

KVM: x86: Trace hypercall register *after* truncating values for 32-bit
KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode
KVM: x86/xen: Don't truncate RAX when handling hypercall from protected guest
KVM: x86/xen: Bug the VM if 32-bit KVM observes a 64-bit mode hypercall

Depending on how people feel about the names and cleanups, I'll either send the big cleanups as a separate pull request after the initial for-7.2 pull requests (if there's overwhelming consensus on the names/splits), or wait for 7.3 (if more discussion is needed).

v3:
- Collect more tags. [David, Binbin, Yosry]
- Use kvm_run_sync_regs_{from,to}_user() instead of kvm_run_{g,s}et_regs(). [Kai]
- Fix a variety of typos. [Binbin]
- Everything beyond patch 15...

v2:
- https://lore.kernel.org/all/[email protected]
- Collect tags. [Yosry, Kai]
- Fix some truly egregious goofs. [Binbin]
- Rename kvm_cache_regs.h => regs.h, add regs.c. [Yosry, because he complained, not because he actually suggested this :-D ]
- Drop superfluous casting/masking of e*x() usage. [Kai]

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

Sean Christopherson (40):
KVM: SVM: Truncate INVLPGA address in compatibility mode
KVM: x86/xen: Bug the VM if 32-bit KVM observes a 64-bit mode
hypercall
KVM: x86/xen: Don't truncate RAX when handling hypercall from
protected guest
KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of

    64-bit mode
  KVM: x86: Trace hypercall register *after* truncating values for
    32-bit

KVM: x86: Rename kvm_cache_regs.h => regs.h
KVM: x86: Move inlined GPR, CR, and DR helpers from x86.h to regs.h
KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers
KVM: x86: Drop non-raw kvm_<reg>_write() helpers
KVM: nSVM: Use kvm_rax_read() now that it's mode-aware Revert "KVM: VMX: Read 32-bit GPR values for ENCLS instructions
outside of 64-bit mode"
KVM: x86: Harden is_64_bit_hypercall() against bugs on 32-bit kernels
KVM: x86: Move update_cr8_intercept() to lapic.c
KVM: x86: Move async #PF helpers to x86.h (as inlines)
KVM: x86: Move the bulk of register specific code from x86.c to regs.c
KVM: x86: Move local APIC specific helpers out of asm/kvm_host.h
KVM: x86: Drop defunct vcpu_tsc_khz() declaration
KVM: x86: Move kvm_caps and kvm_host_values to asm/kvm_host.h
KVM: x86: Swap the include order between x86.h and mmu.h
KVM: x86: Move tdp_enabled from kvm_host.h to mmu.h
KVM: x86: Move eager_page_split to mmu.{c,h}
KVM: x86/hyperv: Eliminate an unnecessary include of x86.h in hyperv.h
KVM: x86: Move kvm_{load,put}_guest_fpu() to fpu.h
KVM: x86: Extract get/set MSR (list) ioctl logic to helpers
KVM: x86: Expose several TSC helpers via x86.h for use by MSR code
KVM: x86: Move the bulk of MSR specific code from x86.c to msrs.{c,h}
KVM: x86: Move register helper declarations from kvm_host.h => regs.h
KVM: x86: Move kvm_{g,s}et_segment() to inline helpers in regs.h
KVM: x86: Remove defunct kvm_load_segment_descriptor() declaration.
KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h
KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h
KVM: x86: Move LLDT assembly wrappers into VMX
KVM: x86: Move kvm_cpu_get_apicid() from kvm_host.h => avic.c
KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c
KVM: x86: Move __kvm_irq_line_state() from kvm_host.h => ioapic.h
KVM: x86: Move IRQ-related helper declarations from kvm_host.h =>
irq.h
KVM: x86: Move kvm_pv_send_ipi() declaration from kvm_host.h =>
lapic.h
KVM: x86/mmu: Move kvm_arch_async_page_ready() below
kvm_tdp_page_fault()
KVM: x86/mmu: Move kvm_mmu_do_page_fault() from mmu_internal.h =>
mmu.c
KVM: x86: Move a pile of stuff from kvm_host.h => x86.h

 arch/x86/include/asm/kvm_host.h           |  452 +--
 arch/x86/kvm/Makefile                     |    4 +-
 arch/x86/kvm/cpuid.c                      |   13 +-
 arch/x86/kvm/emulate.c                    |    2 +-
 arch/x86/kvm/fpu.h                        |   26 +
 arch/x86/kvm/hyperv.c                     |   21 +-
 arch/x86/kvm/hyperv.h                     |    7 +-
 arch/x86/kvm/ioapic.c                     |    1 +
 arch/x86/kvm/ioapic.h                     |   12 +
 arch/x86/kvm/irq.c                        |    7 +
 arch/x86/kvm/irq.h                        |    6 +
 arch/x86/kvm/lapic.c                      |   28 +-
 arch/x86/kvm/lapic.h                      |    9 +
 arch/x86/kvm/mmu.h                        |   92 +-
 arch/x86/kvm/mmu/mmu.c                    |  134 +-
 arch/x86/kvm/mmu/mmu_internal.h           |   66 -
 arch/x86/kvm/msrs.c                       | 2732 +++++++++++++++
 arch/x86/kvm/msrs.h                       |  156 +
 arch/x86/kvm/mtrr.c                       |    1 +
 arch/x86/kvm/regs.c                       |  875 +++++
 arch/x86/kvm/{kvm_cache_regs.h => regs.h} |  258 +-
 arch/x86/kvm/smm.c                        |    2 +-
 arch/x86/kvm/svm/avic.c                   |    5 +
 arch/x86/kvm/svm/nested.c                 |    9 +-
 arch/x86/kvm/svm/svm.c                    |   19 +-
 arch/x86/kvm/svm/svm.h                    |    2 +-
 arch/x86/kvm/vmx/nested.c                 |    9 +-
 arch/x86/kvm/vmx/nested.h                 |    2 +-
 arch/x86/kvm/vmx/sgx.c                    |    6 +-
 arch/x86/kvm/vmx/tdx.c                    |   18 +-
 arch/x86/kvm/vmx/vmx.c                    |   14 +-
 arch/x86/kvm/vmx/vmx.h                    |    2 +-
 arch/x86/kvm/x86.c                        | 3789 +--------------------
 arch/x86/kvm/x86.h                        |  480 ++-
 arch/x86/kvm/xen.c                        |   39 +-
 35 files changed, 4722 insertions(+), 4576 deletions(-)
 create mode 100644 arch/x86/kvm/msrs.c
 create mode 100644 arch/x86/kvm/msrs.h
 create mode 100644 arch/x86/kvm/regs.c
 rename arch/x86/kvm/{kvm_cache_regs.h => regs.h} (50%)

base-commit: d1568b1332b6b3b36b222c2868fc102727c12a34

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#1 lore raw

PATCH v3 1/40 KVM: SVM: Truncate INVLPGA address in compatibility mode

Check for full 64-bit mode, not just long mode, when truncating the virtual address as part of INVLPGA emulation. Compatibility mode doesn't support 64-bit addressing.

Note, the FIXME still applies, e.g. if the guest deliberately targeted EAX while in 64-bit via an address size override. That flaw isn't worth fixing as it would require decoding the code stream, which would open an entirely different can of worms, and in practice no sane guest would shove garbage into RAX[63:32] and execute INVLPGA.

Note #2, VMSAVE, VMLOAD, and VMRUN all suffer from the same architectural flaw of not providing the full linear address in a VMCB exit information field, because, quoting the APM verbatim:

the linear address is available directly from the guest rAX register

(VMSAVE, VMLOAD, and VMRUN take a physical address, but their behavior with respect to rAX is otherwise identical).

Fixes bc9eff67fc35 ("KVM: SVM: Use default rAX size for INVLPGA emulation")
---
 arch/x86/kvm/svm/svm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kvm/svm/svm.c +1 -1
index 717af5c4d057..7d8a433b5c5e 100644
@@ -2416,7 +2416,7 @@ static int invlpga_interception(struct kvm_vcpu *vcpu)
 		return 1;
 
 	/* FIXME: Handle an address size prefix. */
-	if (!is_long_mode(vcpu))
+	if (!is_64_bit_mode(vcpu))
 		gva = (u32)gva;
 
 	trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#2 lore raw

PATCH v3 2/40 KVM: x86/xen: Bug the VM if 32-bit KVM observes a 64-bit mode hypercall

In reply to Sean Christopherson

Bug the VM if 32-bit KVM attempts to handle a 64-bit hypercall, primarily so that a future change to set "input" in mode-specific code doesn't trigger a false positive warn=>error:

arch/x86/kvm/xen.c:1687:6: error: variable 'input' is used uninitialized
whenever 'if' condition is false [-Werror,-Wsometimes-uninitialized]

   1687 |         if (!longmode) {
        |             ^~~~~~~~~
  arch/x86/kvm/xen.c:1708:31: note: uninitialized use occurs here
   1708 |         trace_kvm_xen_hypercall(cpl, input, params[0], params[1], params[2],
        |                                      ^~~~~
  x86/kvm/xen.c:1687:2: note: remove the 'if' if its condition is always true
   1687 |         if (!longmode) {
        |         ^~~~~~~~~~~~~~

arch/x86/kvm/xen.c:1677:11: note: initialize the variable 'input' to silence this warning
1677 | u64 input, params[6], r = -ENOSYS;
| ^
1 error generated.

Note, params[] also has the same flaw, but -Wsometimes-uninitialized doesn't seem to be enforced for arrays, presumably because it's difficult to avoid false positives on specific entries.

---
 arch/x86/kvm/xen.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
arch/x86/kvm/xen.c +5 -2
index 91fd3673c09a..6d9be74bb673 100644
@@ -1694,16 +1694,19 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
 		params[4] = (u32)kvm_rdi_read(vcpu);
 		params[5] = (u32)kvm_rbp_read(vcpu);
 	}
-#ifdef CONFIG_X86_64
 	else {
+#ifdef CONFIG_X86_64
 		params[0] = (u64)kvm_rdi_read(vcpu);
 		params[1] = (u64)kvm_rsi_read(vcpu);
 		params[2] = (u64)kvm_rdx_read(vcpu);
 		params[3] = (u64)kvm_r10_read(vcpu);
 		params[4] = (u64)kvm_r8_read(vcpu);
 		params[5] = (u64)kvm_r9_read(vcpu);
-	}
+#else
+		KVM_BUG_ON(1, vcpu->kvm);
+		return -EIO;
 #endif
+	}
 	cpl = kvm_x86_call(get_cpl)(vcpu);
 	trace_kvm_xen_hypercall(cpl, input, params[0], params[1], params[2],
 				params[3], params[4], params[5]);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#3 lore raw

PATCH v3 3/40 KVM: x86/xen: Don't truncate RAX when handling hypercall from protected guest

In reply to Sean Christopherson

Don't truncate RAX when handling a Xen hypercall for a guest with protected state, as KVM's ABI is to assume the guest is in 64-bit for such cases (the guest leaving garbage in 63:32 after a transition to 32-bit mode is far less likely than 63:32 being necessary to complete the hypercall).

Fixes b5aead0064f3 ("KVM: x86: Assume a 64-bit hypercall for guests with protected state")
---
 arch/x86/kvm/xen.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
arch/x86/kvm/xen.c +3 -3
index 6d9be74bb673..895095dc684e 100644
@@ -1678,15 +1678,14 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
 	bool handled = false;
 	u8 cpl;
 
-	input = (u64)kvm_register_read(vcpu, VCPU_REGS_RAX);
-
 	/* Hyper-V hypercalls get bit 31 set in EAX */
-	if ((input & 0x80000000) &&
+	if ((kvm_rax_read(vcpu) & 0x80000000) &&
 	    kvm_hv_hypercall_enabled(vcpu))
 		return kvm_hv_hypercall(vcpu);
 
 	longmode = is_64_bit_hypercall(vcpu);
 	if (!longmode) {
+		input = (u32)kvm_rax_read(vcpu);
 		params[0] = (u32)kvm_rbx_read(vcpu);
 		params[1] = (u32)kvm_rcx_read(vcpu);
 		params[2] = (u32)kvm_rdx_read(vcpu);
@@ -1696,6 +1695,7 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
 	}
 	else {
 #ifdef CONFIG_X86_64
+		input = (u64)kvm_rax_read(vcpu);
 		params[0] = (u64)kvm_rdi_read(vcpu);
 		params[1] = (u64)kvm_rsi_read(vcpu);
 		params[2] = (u64)kvm_rdx_read(vcpu);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#4 lore raw

PATCH v3 4/40 KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode

In reply to Sean Christopherson

When getting register values for ENCLS emulation, use kvm_register_read() instead of kvm_<reg>_read() so that bits 63:32 of the register are dropped if the guest is in 32-bit mode.

Note, the misleading/surprising behavior of kvm_<reg>_read() being "raw" variants under the hood will be addressed once all non-benign bugs are fixed.

Fixes 70210c044b4e ("KVM: VMX: Add SGX ENCLS[ECREATE] handler to enforce CPUID restrictions")
Fixes b6f084ca5538 ("KVM: VMX: Add ENCLS[EINIT] handler to support SGX Launch Control (LC)")
---
 arch/x86/kvm/vmx/sgx.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/sgx.c +5 -5
index df1d0cf76947..4c61fc33f764 100644
@@ -225,8 +225,8 @@ static int handle_encls_ecreate(struct kvm_vcpu *vcpu)
 	struct x86_exception ex;
 	int r;
 
-	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 32, 32, &pageinfo_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva))
+	if (sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RBX), 32, 32, &pageinfo_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RCX), 4096, 4096, &secs_gva))
 		return 1;
 
 	/*
@@ -302,9 +302,9 @@ static int handle_encls_einit(struct kvm_vcpu *vcpu)
 	gpa_t sig_gpa, secs_gpa, token_gpa;
 	int ret, trapnr;
 
-	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 1808, 4096, &sig_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_rdx_read(vcpu), 304, 512, &token_gva))
+	if (sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RBX), 1808, 4096, &sig_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RCX), 4096, 4096, &secs_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RDX), 304, 512, &token_gva))
 		return 1;
 
 	/*
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#6 lore raw

PATCH v3 5/40 KVM: x86: Trace hypercall register *after* truncating values for 32-bit

In reply to Sean Christopherson

When tracing hypercalls, invoke the tracepoint *after* truncating the register values for 32-bit guests so as not to record unused garbage (in the extremely unlikely scenario that the guest left garbage in a register after transitioning from 64-bit mode to 32-bit mode).

Fixes 229456fc34b1 ("KVM: convert custom marker based tracing to event traces")
---
 arch/x86/kvm/x86.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +2 -2
index e6f1dd84f22d..634a6d0197f6 100644
@@ -10429,8 +10429,6 @@ int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
 
 	++vcpu->stat.hypercalls;
 
-	trace_kvm_hypercall(nr, a0, a1, a2, a3);
-
 	if (!op_64_bit) {
 		nr &= 0xFFFFFFFF;
 		a0 &= 0xFFFFFFFF;
@@ -10439,6 +10437,8 @@ int ____kvm_emulate_hypercall(struct kvm_vcpu *vcpu, int cpl,
 		a3 &= 0xFFFFFFFF;
 	}
 
+	trace_kvm_hypercall(nr, a0, a1, a2, a3);
+
 	if (cpl) {
 		ret = -KVM_EPERM;
 		goto out;
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#7 lore raw

PATCH v3 6/40 KVM: x86: Rename kvm_cache_regs.h => regs.h

In reply to Sean Christopherson

Rename kvm_cache_regs.h to simply regs.h, as the "cache" nomenclature is already a lie (the file deals with state/registers that aren't cached per se), and so that more code/functionality can be landed in the header without making it a truly horrible misnomer.

Deliberately drop the kvm_ prefix/namespace to align with other "local" headers, and to further differentiate regs.h from the public/global arch/x86/include/asm/kvm_vcpu_regs.h, which sadly needs to stay in asm/ so that the number of registers can be referenced by kvm_vcpu_arch.

No functional change intended.

---
 arch/x86/kvm/emulate.c                    | 2 +-
 arch/x86/kvm/lapic.c                      | 2 +-
 arch/x86/kvm/mmu.h                        | 2 +-
 arch/x86/kvm/mmu/mmu.c                    | 2 +-
 arch/x86/kvm/{kvm_cache_regs.h => regs.h} | 4 ++--
 arch/x86/kvm/smm.c                        | 2 +-
 arch/x86/kvm/svm/svm.c                    | 2 +-
 arch/x86/kvm/svm/svm.h                    | 2 +-
 arch/x86/kvm/vmx/nested.h                 | 2 +-
 arch/x86/kvm/vmx/sgx.c                    | 2 +-
 arch/x86/kvm/vmx/vmx.c                    | 2 +-
 arch/x86/kvm/vmx/vmx.h                    | 2 +-
 arch/x86/kvm/x86.c                        | 2 +-
 arch/x86/kvm/x86.h                        | 2 +-
 14 files changed, 15 insertions(+), 15 deletions(-)
 rename arch/x86/kvm/{kvm_cache_regs.h => regs.h} (99%)
arch/x86/kvm/emulate.c +1 -1
index 585a8ceab220..b566ab5c7515 100644
@@ -20,7 +20,7 @@
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 
 #include <linux/kvm_host.h>
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "kvm_emulate.h"
 #include <linux/stringify.h>
 #include <asm/debugreg.h>
arch/x86/kvm/lapic.c +1 -1
index 4e34f75e705d..15777869b292 100644
@@ -37,7 +37,7 @@
 #include <asm/delay.h>
 #include <linux/atomic.h>
 #include <linux/jump_label.h>
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "irq.h"
 #include "ioapic.h"
 #include "trace.h"
arch/x86/kvm/mmu.h +1 -1
index ddf4e467c071..e1bb663ebbd5 100644
@@ -3,7 +3,7 @@
 #define __KVM_X86_MMU_H
 
 #include <linux/kvm_host.h>
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "x86.h"
 #include "cpuid.h"
 
arch/x86/kvm/mmu/mmu.c +1 -1
index c87c26bf4149..b8f2edf2cfeb 100644
@@ -22,7 +22,7 @@
 #include "mmu_internal.h"
 #include "tdp_mmu.h"
 #include "x86.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "smm.h"
 #include "kvm_emulate.h"
 #include "page_track.h"
arch/x86/kvm/regs.h renamed from arch/x86/kvm/kvm_cache_regs.h +2 -2
similarity index 99%
rename from arch/x86/kvm/kvm_cache_regs.h
rename to arch/x86/kvm/regs.h
index 2ae492ad6412..4440f3992fce 100644
@@ -1,6 +1,6 @@
 /* SPDX-License-Identifier: GPL-2.0 */
-#ifndef ASM_KVM_CACHE_REGS_H
-#define ASM_KVM_CACHE_REGS_H
+#ifndef ARCH_X86_KVM_REGS_H
+#define ARCH_X86_KVM_REGS_H
 
 #include <linux/kvm_host.h>
 
arch/x86/kvm/smm.c +1 -1
index f623c5986119..a446487bdd5c 100644
@@ -3,7 +3,7 @@
 
 #include <linux/kvm_host.h>
 #include "x86.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "kvm_emulate.h"
 #include "smm.h"
 #include "cpuid.h"
arch/x86/kvm/svm/svm.c +1 -1
index 7d8a433b5c5e..d4bfda10f1df 100644
@@ -4,7 +4,7 @@
 
 #include "irq.h"
 #include "mmu.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "x86.h"
 #include "smm.h"
 #include "cpuid.h"
arch/x86/kvm/svm/svm.h +1 -1
index 87c6b105deef..cbc716885398 100644
@@ -23,7 +23,7 @@
 #include <asm/sev-common.h>
 
 #include "cpuid.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "x86.h"
 #include "pmu.h"
 
arch/x86/kvm/vmx/nested.h +1 -1
index 213a448104af..6d6cd5904ddf 100644
@@ -2,7 +2,7 @@
 #ifndef __KVM_X86_VMX_NESTED_H
 #define __KVM_X86_VMX_NESTED_H
 
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "hyperv.h"
 #include "vmcs12.h"
 #include "vmx.h"
arch/x86/kvm/vmx/sgx.c +1 -1
index 4c61fc33f764..66c315554b46 100644
@@ -6,7 +6,7 @@
 #include <asm/sgx.h>
 
 #include "x86.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "nested.h"
 #include "sgx.h"
 #include "vmx.h"
arch/x86/kvm/vmx/vmx.c +1 -1
index cbc2034d7924..bb19f6df921b 100644
@@ -59,7 +59,7 @@
 #include "hyperv.h"
 #include "kvm_onhyperv.h"
 #include "irq.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "lapic.h"
 #include "mmu.h"
 #include "nested.h"
arch/x86/kvm/vmx/vmx.h +1 -1
index daedf663c0a9..de9de0d2016c 100644
@@ -10,7 +10,7 @@
 #include <asm/posted_intr.h>
 
 #include "capabilities.h"
-#include "../kvm_cache_regs.h"
+#include "../regs.h"
 #include "pmu_intel.h"
 #include "vmcs.h"
 #include "vmx_ops.h"
arch/x86/kvm/x86.c +1 -1
index 634a6d0197f6..4fe2fb3ceba6 100644
@@ -23,7 +23,7 @@
 #include "mmu.h"
 #include "i8254.h"
 #include "tss.h"
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "kvm_emulate.h"
 #include "mmu/page_track.h"
 #include "x86.h"
arch/x86/kvm/x86.h +1 -1
index a49424f9c968..a6b2be462e6d 100644
@@ -6,7 +6,7 @@
 #include <asm/fpu/xstate.h>
 #include <asm/mce.h>
 #include <asm/pvclock.h>
-#include "kvm_cache_regs.h"
+#include "regs.h"
 #include "kvm_emulate.h"
 #include "cpuid.h"
 
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#8 lore raw

PATCH v3 7/40 KVM: x86: Move inlined GPR, CR, and DR helpers from x86.h to regs.h

In reply to Sean Christopherson

Move inlined General Purpose Register, Control Register, and Debug Register helpers from x86.h to the aptly named regs.h, to help trim down x86.h (and x86.c in the future).

Move *very* select EFER functionality as well, but leave behind the bulk of EFER handling and all other MSR handling. There is more than enough MSR code to carve out msrs.{c,h} in the future. Give is_long_bit_mode() special treatment as it's more along the lines of a CR4 bit check, but just happens to be accessed through an MSR interface. And more importantly, because giving regs.h access to is_long_bit_mode() greatly simplifies dependency chains.

No functional change intended.

---
 arch/x86/kvm/regs.h | 123 ++++++++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/x86.h  | 117 -----------------------------------------
 2 files changed, 120 insertions(+), 120 deletions(-)
arch/x86/kvm/regs.h +120 -3
index 4440f3992fce..62cc9deea226 100644
@@ -16,6 +16,37 @@
 
 static_assert(!(KVM_POSSIBLE_CR0_GUEST_BITS & X86_CR0_PDPTR_BITS));
 
+static inline bool is_long_mode(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_X86_64
+	return !!(vcpu->arch.efer & EFER_LMA);
+#else
+	return false;
+#endif
+}
+
+static inline bool is_64_bit_mode(struct kvm_vcpu *vcpu)
+{
+	int cs_db, cs_l;
+
+	WARN_ON_ONCE(vcpu->arch.guest_state_protected);
+
+	if (!is_long_mode(vcpu))
+		return false;
+	kvm_x86_call(get_cs_db_l_bits)(vcpu, &cs_db, &cs_l);
+	return cs_l;
+}
+
+static inline bool is_64_bit_hypercall(struct kvm_vcpu *vcpu)
+{
+	/*
+	 * If running with protected guest state, the CS register is not
+	 * accessible. The hypercall register values will have had to been
+	 * provided in 64-bit mode, so assume the guest is in 64-bit.
+	 */
+	return vcpu->arch.guest_state_protected || is_64_bit_mode(vcpu);
+}
+
 #define BUILD_KVM_GPR_ACCESSORS(lname, uname)				      \
 static __always_inline unsigned long kvm_##lname##_read(struct kvm_vcpu *vcpu)\
 {									      \
@@ -143,6 +174,13 @@ static inline unsigned long kvm_register_read_raw(struct kvm_vcpu *vcpu, int reg
 	return vcpu->arch.regs[reg];
 }
 
+static inline unsigned long kvm_register_read(struct kvm_vcpu *vcpu, int reg)
+{
+	unsigned long val = kvm_register_read_raw(vcpu, reg);
+
+	return is_64_bit_mode(vcpu) ? val : (u32)val;
+}
+
 static inline void kvm_register_write_raw(struct kvm_vcpu *vcpu, int reg,
 					  unsigned long val)
 {
@@ -153,6 +191,14 @@ static inline void kvm_register_write_raw(struct kvm_vcpu *vcpu, int reg,
 	kvm_register_mark_dirty(vcpu, reg);
 }
 
+static inline void kvm_register_write(struct kvm_vcpu *vcpu,
+				       int reg, unsigned long val)
+{
+	if (!is_64_bit_mode(vcpu))
+		val = (u32)val;
+	return kvm_register_write_raw(vcpu, reg, val);
+}
+
 static inline unsigned long kvm_rip_read(struct kvm_vcpu *vcpu)
 {
 	if (!kvm_register_is_available(vcpu, VCPU_REG_RIP))
@@ -177,6 +223,12 @@ static inline void kvm_rsp_write(struct kvm_vcpu *vcpu, unsigned long val)
 	kvm_register_write_raw(vcpu, VCPU_REGS_RSP, val);
 }
 
+static inline u64 kvm_read_edx_eax(struct kvm_vcpu *vcpu)
+{
+	return (kvm_rax_read(vcpu) & -1u)
+		| ((u64)(kvm_rdx_read(vcpu) & -1u) << 32);
+}
+
 static inline u64 kvm_pdptr_read(struct kvm_vcpu *vcpu, int index)
 {
 	might_sleep();  /* on svm */
@@ -243,10 +295,75 @@ static inline ulong kvm_read_cr4(struct kvm_vcpu *vcpu)
 	return kvm_read_cr4_bits(vcpu, ~0UL);
 }
 
-static inline u64 kvm_read_edx_eax(struct kvm_vcpu *vcpu)
+static inline bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 {
-	return (kvm_rax_read(vcpu) & -1u)
-		| ((u64)(kvm_rdx_read(vcpu) & -1u) << 32);
+	return !(cr4 & vcpu->arch.cr4_guest_rsvd_bits);
+}
+
+#define __cr4_reserved_bits(__cpu_has, __c)             \
+({                                                      \
+	u64 __reserved_bits = CR4_RESERVED_BITS;        \
+                                                        \
+	if (!__cpu_has(__c, X86_FEATURE_XSAVE))         \
+		__reserved_bits |= X86_CR4_OSXSAVE;     \
+	if (!__cpu_has(__c, X86_FEATURE_SMEP))          \
+		__reserved_bits |= X86_CR4_SMEP;        \
+	if (!__cpu_has(__c, X86_FEATURE_SMAP))          \
+		__reserved_bits |= X86_CR4_SMAP;        \
+	if (!__cpu_has(__c, X86_FEATURE_FSGSBASE))      \
+		__reserved_bits |= X86_CR4_FSGSBASE;    \
+	if (!__cpu_has(__c, X86_FEATURE_PKU))           \
+		__reserved_bits |= X86_CR4_PKE;         \
+	if (!__cpu_has(__c, X86_FEATURE_LA57))          \
+		__reserved_bits |= X86_CR4_LA57;        \
+	if (!__cpu_has(__c, X86_FEATURE_UMIP))          \
+		__reserved_bits |= X86_CR4_UMIP;        \
+	if (!__cpu_has(__c, X86_FEATURE_VMX))           \
+		__reserved_bits |= X86_CR4_VMXE;        \
+	if (!__cpu_has(__c, X86_FEATURE_PCID))          \
+		__reserved_bits |= X86_CR4_PCIDE;       \
+	if (!__cpu_has(__c, X86_FEATURE_LAM))           \
+		__reserved_bits |= X86_CR4_LAM_SUP;     \
+	if (!__cpu_has(__c, X86_FEATURE_SHSTK) &&       \
+	    !__cpu_has(__c, X86_FEATURE_IBT))           \
+		__reserved_bits |= X86_CR4_CET;         \
+	__reserved_bits;                                \
+})
+
+static inline bool is_protmode(struct kvm_vcpu *vcpu)
+{
+	return kvm_is_cr0_bit_set(vcpu, X86_CR0_PE);
+}
+
+static inline bool is_pae(struct kvm_vcpu *vcpu)
+{
+	return kvm_is_cr4_bit_set(vcpu, X86_CR4_PAE);
+}
+
+static inline bool is_pse(struct kvm_vcpu *vcpu)
+{
+	return kvm_is_cr4_bit_set(vcpu, X86_CR4_PSE);
+}
+
+static inline bool is_paging(struct kvm_vcpu *vcpu)
+{
+	return likely(kvm_is_cr0_bit_set(vcpu, X86_CR0_PG));
+}
+
+static inline bool is_pae_paging(struct kvm_vcpu *vcpu)
+{
+	return !is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu);
+}
+
+static inline bool kvm_dr7_valid(u64 data)
+{
+	/* Bits [63:32] are reserved */
+	return !(data >> 32);
+}
+static inline bool kvm_dr6_valid(u64 data)
+{
+	/* Bits [63:32] are reserved */
+	return !(data >> 32);
 }
 
 static inline void enter_guest_mode(struct kvm_vcpu *vcpu)
arch/x86/kvm/x86.h +0 -117

147 lines not on this page · raw message

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#9 lore raw

PATCH v3 8/40 KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers

In reply to Sean Christopherson

Make kvm_<reg>_{read,write}() mode-aware (where the value is truncated to 32 bits if the vCPU isn't in 64-bit mode), and convert all the intentional "raw" accesses to kvm_<reg>_{read,write}_raw() versions. To avoid confusion and bikeshedding over whether or not explicit 32-bit accesses should use the "raw" or mode-aware variants, add and use "e" versions, e.g. for things like RDMSR, WRMSR, and CPUID, where the instruction uses only bits 31:0, regardless of mode.

No functional change intended (all use of "e" versions is for cases where the value is already truncated due to bouncing through a u32).

---
 arch/x86/kvm/cpuid.c      |  12 ++--
 arch/x86/kvm/hyperv.c     |  21 +++----
 arch/x86/kvm/hyperv.h     |   4 +-
 arch/x86/kvm/regs.h       |  88 +++++++++++++++++----------
 arch/x86/kvm/svm/nested.c |   6 +-
 arch/x86/kvm/svm/svm.c    |  13 ++--
 arch/x86/kvm/vmx/nested.c |   8 +--
 arch/x86/kvm/vmx/sgx.c    |   4 +-
 arch/x86/kvm/vmx/tdx.c    |  18 +++---
 arch/x86/kvm/x86.c        | 121 +++++++++++++++++++-------------------
 arch/x86/kvm/xen.c        |  32 +++++-----
 11 files changed, 173 insertions(+), 154 deletions(-)
arch/x86/kvm/cpuid.c +6 -6
index 8e5340dd2621..fd3b02575cd0 100644
@@ -2166,13 +2166,13 @@ int kvm_emulate_cpuid(struct kvm_vcpu *vcpu)
 		return 1;
 	}
 
-	eax = kvm_rax_read(vcpu);
-	ecx = kvm_rcx_read(vcpu);
+	eax = kvm_eax_read(vcpu);
+	ecx = kvm_ecx_read(vcpu);
 	kvm_cpuid(vcpu, &eax, &ebx, &ecx, &edx, false);
-	kvm_rax_write(vcpu, eax);
-	kvm_rbx_write(vcpu, ebx);
-	kvm_rcx_write(vcpu, ecx);
-	kvm_rdx_write(vcpu, edx);
+	kvm_eax_write(vcpu, eax);
+	kvm_ebx_write(vcpu, ebx);
+	kvm_ecx_write(vcpu, ecx);
+	kvm_edx_write(vcpu, edx);
 	return kvm_skip_emulated_instruction(vcpu);
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_cpuid);
arch/x86/kvm/hyperv.c +9 -12
index 015c6947b462..3551af9a9453 100644
@@ -2377,10 +2377,10 @@ static void kvm_hv_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)
 
 	longmode = is_64_bit_hypercall(vcpu);
 	if (longmode)
-		kvm_rax_write(vcpu, result);
+		kvm_rax_write_raw(vcpu, result);
 	else {
-		kvm_rdx_write(vcpu, result >> 32);
-		kvm_rax_write(vcpu, result & 0xffffffff);
+		kvm_edx_write(vcpu, result >> 32);
+		kvm_eax_write(vcpu, result);
 	}
 }
 
@@ -2544,18 +2544,15 @@ int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
 
 #ifdef CONFIG_X86_64
 	if (is_64_bit_hypercall(vcpu)) {
-		hc.param = kvm_rcx_read(vcpu);
-		hc.ingpa = kvm_rdx_read(vcpu);
-		hc.outgpa = kvm_r8_read(vcpu);
+		hc.param = kvm_rcx_read_raw(vcpu);
+		hc.ingpa = kvm_rdx_read_raw(vcpu);
+		hc.outgpa = kvm_r8_read_raw(vcpu);
 	} else
 #endif
 	{
-		hc.param = ((u64)kvm_rdx_read(vcpu) << 32) |
-			    (kvm_rax_read(vcpu) & 0xffffffff);
-		hc.ingpa = ((u64)kvm_rbx_read(vcpu) << 32) |
-			    (kvm_rcx_read(vcpu) & 0xffffffff);
-		hc.outgpa = ((u64)kvm_rdi_read(vcpu) << 32) |
-			     (kvm_rsi_read(vcpu) & 0xffffffff);
+		hc.param = ((u64)kvm_edx_read(vcpu) << 32) | kvm_eax_read(vcpu);
+		hc.ingpa = ((u64)kvm_ebx_read(vcpu) << 32) | kvm_ecx_read(vcpu);
+		hc.outgpa = ((u64)kvm_edi_read(vcpu) << 32) | kvm_esi_read(vcpu);
 	}
 
 	hc.code = hc.param & 0xffff;
arch/x86/kvm/hyperv.h +2 -2
index 6301f79fcbae..65e89ed65349 100644
@@ -232,8 +232,8 @@ static inline bool kvm_hv_is_tlb_flush_hcall(struct kvm_vcpu *vcpu)
 	if (!hv_vcpu)
 		return false;
 
-	code = is_64_bit_hypercall(vcpu) ? kvm_rcx_read(vcpu) :
-					   kvm_rax_read(vcpu);
+	code = is_64_bit_hypercall(vcpu) ? kvm_rcx_read_raw(vcpu) :
+					   kvm_eax_read(vcpu);
 
 	return (code == HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE ||
 		code == HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST ||
arch/x86/kvm/regs.h +56 -32

114 lines not on this page · raw message

arch/x86/kvm/svm/nested.c +3 -3
index 7ad4b4fb7a1c..d817dbb350d6 100644
@@ -793,7 +793,7 @@ static void nested_vmcb02_prepare_save(struct vcpu_svm *svm)
 
 	svm->vcpu.arch.cr2 = save->cr2;
 
-	kvm_rax_write(vcpu, save->rax);
+	kvm_rax_write_raw(vcpu, save->rax);
 	kvm_rsp_write(vcpu, save->rsp);
 	kvm_rip_write(vcpu, save->rip);
 
@@ -1272,7 +1272,7 @@ static int nested_svm_vmexit_update_vmcb12(struct kvm_vcpu *vcpu)
 	vmcb12->save.rflags = kvm_get_rflags(vcpu);
 	vmcb12->save.rip    = kvm_rip_read(vcpu);
 	vmcb12->save.rsp    = kvm_rsp_read(vcpu);
-	vmcb12->save.rax    = kvm_rax_read(vcpu);
+	vmcb12->save.rax    = kvm_rax_read_raw(vcpu);
 	vmcb12->save.dr7    = vmcb02->save.dr7;
 	vmcb12->save.dr6    = svm->vcpu.arch.dr6;
 	vmcb12->save.cpl    = vmcb02->save.cpl;
@@ -1424,7 +1424,7 @@ void nested_svm_vmexit(struct vcpu_svm *svm)
 	svm_set_efer(vcpu, vmcb01->save.efer);
 	svm_set_cr0(vcpu, vmcb01->save.cr0 | X86_CR0_PE);
 	svm_set_cr4(vcpu, vmcb01->save.cr4);
-	kvm_rax_write(vcpu, vmcb01->save.rax);
+	kvm_rax_write_raw(vcpu, vmcb01->save.rax);
 	kvm_rsp_write(vcpu, vmcb01->save.rsp);
 	kvm_rip_write(vcpu, vmcb01->save.rip);
 
arch/x86/kvm/svm/svm.c +5 -8
index d4bfda10f1df..8402e94ac094 100644
@@ -2409,15 +2409,12 @@ static int clgi_interception(struct kvm_vcpu *vcpu)
 
 static int invlpga_interception(struct kvm_vcpu *vcpu)
 {
-	gva_t gva = kvm_rax_read(vcpu);
-	u32 asid = kvm_rcx_read(vcpu);
-
-	if (nested_svm_check_permissions(vcpu))
-		return 1;
-
 	/* FIXME: Handle an address size prefix. */
-	if (!is_64_bit_mode(vcpu))
-		gva = (u32)gva;
+	gva_t gva = kvm_rax_read(vcpu);
+	u32 asid = kvm_ecx_read(vcpu);
+
+	if (nested_svm_check_permissions(vcpu))
+		return 1;
 
 	trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
 
arch/x86/kvm/vmx/nested.c +4 -4
index 30dcabc899a2..b2c851cc7d5c 100644
@@ -6165,7 +6165,7 @@ static int handle_invvpid(struct kvm_vcpu *vcpu)
 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
 				     struct vmcs12 *vmcs12)
 {
-	u32 index = kvm_rcx_read(vcpu);
+	u32 index = kvm_ecx_read(vcpu);
 	u64 new_eptp;
 
 	if (WARN_ON_ONCE(!nested_cpu_has_ept(vmcs12)))
@@ -6199,7 +6199,7 @@ static int handle_vmfunc(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 	struct vmcs12 *vmcs12;
-	u32 function = kvm_rax_read(vcpu);
+	u32 function = kvm_eax_read(vcpu);
 
 	/*
 	 * VMFUNC should never execute cleanly while L1 is active; KVM supports
@@ -6321,7 +6321,7 @@ static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
 	    exit_reason.basic == EXIT_REASON_MSR_WRITE_IMM)
 		msr_index = vmx_get_exit_qual(vcpu);
 	else
-		msr_index = kvm_rcx_read(vcpu);
+		msr_index = kvm_ecx_read(vcpu);
 
 	/*
 	 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
@@ -6431,7 +6431,7 @@ static bool nested_vmx_exit_handled_encls(struct kvm_vcpu *vcpu,
 	    !nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENCLS_EXITING))
 		return false;
 
-	encls_leaf = kvm_rax_read(vcpu);
+	encls_leaf = kvm_eax_read(vcpu);
 	if (encls_leaf > 62)
 		encls_leaf = 63;
 	return vmcs12->encls_exiting_bitmap & BIT_ULL(encls_leaf);
arch/x86/kvm/vmx/sgx.c +2 -2
index 66c315554b46..2f5a1c58f3c5 100644
@@ -352,7 +352,7 @@ static int handle_encls_einit(struct kvm_vcpu *vcpu)
 		rflags &= ~X86_EFLAGS_ZF;
 	vmx_set_rflags(vcpu, rflags);
 
-	kvm_rax_write(vcpu, ret);
+	kvm_eax_write(vcpu, ret);
 	return kvm_skip_emulated_instruction(vcpu);
 }
 
@@ -380,7 +380,7 @@ static inline bool sgx_enabled_in_guest_bios(struct kvm_vcpu *vcpu)
 
 int handle_encls(struct kvm_vcpu *vcpu)
 {
-	u32 leaf = (u32)kvm_rax_read(vcpu);
+	u32 leaf = kvm_eax_read(vcpu);
 
 	if (!enable_sgx || !guest_cpu_cap_has(vcpu, X86_FEATURE_SGX) ||
 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_SGX1)) {
arch/x86/kvm/vmx/tdx.c +9 -9
index 77e3d1bb24cb..ffe9d0db58c5 100644
@@ -1169,11 +1169,11 @@ static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
 
 static int tdx_emulate_vmcall(struct kvm_vcpu *vcpu)
 {
-	kvm_rax_write(vcpu, to_tdx(vcpu)->vp_enter_args.r10);
-	kvm_rbx_write(vcpu, to_tdx(vcpu)->vp_enter_args.r11);
-	kvm_rcx_write(vcpu, to_tdx(vcpu)->vp_enter_args.r12);
-	kvm_rdx_write(vcpu, to_tdx(vcpu)->vp_enter_args.r13);
-	kvm_rsi_write(vcpu, to_tdx(vcpu)->vp_enter_args.r14);
+	kvm_rax_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r10);
+	kvm_rbx_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r11);
+	kvm_rcx_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r12);
+	kvm_rdx_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r13);
+	kvm_rsi_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r14);
 
 	return __kvm_emulate_hypercall(vcpu, 0, complete_hypercall_exit);
 }
@@ -2107,12 +2107,12 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
 	case EXIT_REASON_IO_INSTRUCTION:
 		return tdx_emulate_io(vcpu);
 	case EXIT_REASON_MSR_READ:
-		kvm_rcx_write(vcpu, tdx->vp_enter_args.r12);
+		kvm_ecx_write(vcpu, tdx->vp_enter_args.r12);
 		return kvm_emulate_rdmsr(vcpu);
 	case EXIT_REASON_MSR_WRITE:
-		kvm_rcx_write(vcpu, tdx->vp_enter_args.r12);
-		kvm_rax_write(vcpu, tdx->vp_enter_args.r13 & -1u);
-		kvm_rdx_write(vcpu, tdx->vp_enter_args.r13 >> 32);
+		kvm_ecx_write(vcpu, tdx->vp_enter_args.r12);
+		kvm_eax_write(vcpu, tdx->vp_enter_args.r13);
+		kvm_edx_write(vcpu, tdx->vp_enter_args.r13 >> 32);
 		return kvm_emulate_wrmsr(vcpu);
 	case EXIT_REASON_EPT_MISCONFIG:
 		return tdx_emulate_mmio(vcpu);
arch/x86/kvm/x86.c +61 -60

230 lines not on this page · raw message

arch/x86/kvm/xen.c +16 -16
index 895095dc684e..694b31c1fcc9 100644
@@ -1408,7 +1408,7 @@ int kvm_xen_hvm_config(struct kvm *kvm, struct kvm_xen_hvm_config *xhc)
 
 static int kvm_xen_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)
 {
-	kvm_rax_write(vcpu, result);
+	kvm_rax_write_raw(vcpu, result);
 	return kvm_skip_emulated_instruction(vcpu);
 }
 
@@ -1679,29 +1679,29 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
 	u8 cpl;
 
 	/* Hyper-V hypercalls get bit 31 set in EAX */
-	if ((kvm_rax_read(vcpu) & 0x80000000) &&
+	if ((kvm_rax_read_raw(vcpu) & 0x80000000) &&
 	    kvm_hv_hypercall_enabled(vcpu))
 		return kvm_hv_hypercall(vcpu);
 
 	longmode = is_64_bit_hypercall(vcpu);
 	if (!longmode) {
-		input = (u32)kvm_rax_read(vcpu);
-		params[0] = (u32)kvm_rbx_read(vcpu);
-		params[1] = (u32)kvm_rcx_read(vcpu);
-		params[2] = (u32)kvm_rdx_read(vcpu);
-		params[3] = (u32)kvm_rsi_read(vcpu);
-		params[4] = (u32)kvm_rdi_read(vcpu);
-		params[5] = (u32)kvm_rbp_read(vcpu);
+		input = kvm_eax_read(vcpu);
+		params[0] = kvm_ebx_read(vcpu);
+		params[1] = kvm_ecx_read(vcpu);
+		params[2] = kvm_edx_read(vcpu);
+		params[3] = kvm_esi_read(vcpu);
+		params[4] = kvm_edi_read(vcpu);
+		params[5] = kvm_ebp_read(vcpu);
 	}
 	else {
 #ifdef CONFIG_X86_64
-		input = (u64)kvm_rax_read(vcpu);
-		params[0] = (u64)kvm_rdi_read(vcpu);
-		params[1] = (u64)kvm_rsi_read(vcpu);
-		params[2] = (u64)kvm_rdx_read(vcpu);
-		params[3] = (u64)kvm_r10_read(vcpu);
-		params[4] = (u64)kvm_r8_read(vcpu);
-		params[5] = (u64)kvm_r9_read(vcpu);
+		input = (u64)kvm_rax_read_raw(vcpu);
+		params[0] = (u64)kvm_rdi_read_raw(vcpu);
+		params[1] = (u64)kvm_rsi_read_raw(vcpu);
+		params[2] = (u64)kvm_rdx_read_raw(vcpu);
+		params[3] = (u64)kvm_r10_read_raw(vcpu);
+		params[4] = (u64)kvm_r8_read_raw(vcpu);
+		params[5] = (u64)kvm_r9_read_raw(vcpu);
 #else
 		KVM_BUG_ON(1, vcpu->kvm);
 		return -EIO;
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#11 lore raw

PATCH v3 9/40 KVM: x86: Drop non-raw kvm_<reg>_write() helpers

In reply to Sean Christopherson

Drop the non-raw, mode-aware kvm_<reg>_write() helpers as there is no usage in KVM, and in all likelihood there will never be usage in KVM as use of hardcoded registers in instructions is uncommon, and *modifying* hardcoded registers is practically unheard of. While there are a few instructions that modify registers in mode-aware ways, e.g. REP string and some ENCLS varieties, the odds of KVM needing to emulate such instructions (outside of the fully emulator) are vanishingly small.

Drop kvm_<reg>_write() to prevent incorrect usage; _if_ a new instruction comes along that needs to modify a hardcoded register, this can be reverted.

No functional change intended.

---
 arch/x86/kvm/regs.h | 5 -----
 1 file changed, 5 deletions(-)
arch/x86/kvm/regs.h +0 -5
index 12db5039aace..f22b3a8cd483 100644
@@ -61,11 +61,6 @@ static __always_inline unsigned long kvm_##lname##_read(struct kvm_vcpu *vcpu)
 {											\
 	return vcpu->arch.regs[VCPU_REGS_##uname] & kvm_reg_mode_mask(vcpu);		\
 }											\
-static __always_inline void kvm_##lname##_write(struct kvm_vcpu *vcpu,			\
-						unsigned long val)			\
-{											\
-	vcpu->arch.regs[VCPU_REGS_##uname] = val & kvm_reg_mode_mask(vcpu);		\
-}											\
 static __always_inline unsigned long kvm_##lname##_read_raw(struct kvm_vcpu *vcpu)	\
 {											\
 	return vcpu->arch.regs[VCPU_REGS_##uname];					\
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#12 lore raw

PATCH v3 10/40 KVM: nSVM: Use kvm_rax_read() now that it's mode-aware

In reply to Sean Christopherson

Now that kvm_rax_read() truncates the output value to 32 bits if the vCPU isn't in 64-bit mode, use it instead of the more verbose (and very technically slower) kvm_register_read().

Note! VMLOAD, VMSAVE, and VMRUN emulation are still technically buggy, as they can use EAX (versus RAX) in 64-bit mode via an operand size prefix. Don't bother trying to handle that case, as it would require decoding the code stream, which would open an entirely different can of worms, and in practice no sane guest would shove garbage into RAX[63:32] and then execute VMLOAD/VMSAVE/VMRUN with just EAX.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 2 +-
 arch/x86/kvm/svm/svm.c    | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
arch/x86/kvm/svm/nested.c +1 -1
index d817dbb350d6..1ab8b95975a4 100644
@@ -1135,7 +1135,7 @@ int nested_svm_vmrun(struct kvm_vcpu *vcpu)
 	if (WARN_ON_ONCE(!svm->nested.initialized))
 		return -EINVAL;
 
-	vmcb12_gpa = kvm_register_read(vcpu, VCPU_REGS_RAX);
+	vmcb12_gpa = kvm_rax_read(vcpu);
 	if (!page_address_valid(vcpu, vmcb12_gpa)) {
 		kvm_inject_gp(vcpu, 0);
 		return 1;
arch/x86/kvm/svm/svm.c +2 -2
index 8402e94ac094..526e0fdcd16b 100644
@@ -2218,7 +2218,7 @@ static int intr_interception(struct kvm_vcpu *vcpu)
 
 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
 {
-	u64 vmcb12_gpa = kvm_register_read(vcpu, VCPU_REGS_RAX);
+	u64 vmcb12_gpa = kvm_rax_read(vcpu);
 	struct vcpu_svm *svm = to_svm(vcpu);
 	struct vmcb *vmcb12;
 	struct kvm_host_map map;
@@ -2326,7 +2326,7 @@ static int gp_interception(struct kvm_vcpu *vcpu)
 		if (nested_svm_check_permissions(vcpu))
 			return 1;
 
-		if (!page_address_valid(vcpu, kvm_register_read(vcpu, VCPU_REGS_RAX)))
+		if (!page_address_valid(vcpu, kvm_rax_read(vcpu)))
 			goto reinject;
 
 		/*
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#13 lore raw

PATCH v3 11/40 Revert "KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode"

In reply to Sean Christopherson

Now that kvm_<reg>_read() are mode aware, i.e. are functionally equivalent to kvm_register_read(), revert aback to the less verbose versions.

No functional change intended.

This reverts commit 60919eccf6764c71cef31a1afeaa1a36b8e5ab85.

---
 arch/x86/kvm/vmx/sgx.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/sgx.c +5 -5
index 2f5a1c58f3c5..876dc2814108 100644
@@ -225,8 +225,8 @@ static int handle_encls_ecreate(struct kvm_vcpu *vcpu)
 	struct x86_exception ex;
 	int r;
 
-	if (sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RBX), 32, 32, &pageinfo_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RCX), 4096, 4096, &secs_gva))
+	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 32, 32, &pageinfo_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva))
 		return 1;
 
 	/*
@@ -302,9 +302,9 @@ static int handle_encls_einit(struct kvm_vcpu *vcpu)
 	gpa_t sig_gpa, secs_gpa, token_gpa;
 	int ret, trapnr;
 
-	if (sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RBX), 1808, 4096, &sig_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RCX), 4096, 4096, &secs_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RDX), 304, 512, &token_gva))
+	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 1808, 4096, &sig_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_rdx_read(vcpu), 304, 512, &token_gva))
 		return 1;
 
 	/*
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#14 lore raw

PATCH v3 12/40 KVM: x86: Harden is_64_bit_hypercall() against bugs on 32-bit kernels

In reply to Sean Christopherson

Unconditionally return %false for is_64_bit_hypercall() on 32-bit kernels to guard against incorrectly setting guest_state_protected, and because in a (very) hypothetical world where 32-bit KVM supports protected guests, assuming a hypercall was made in 64-bit mode is flat out wrong.

---
 arch/x86/kvm/regs.h | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/regs.h +4 -0
index f22b3a8cd483..a57ba26279ed 100644
@@ -39,12 +39,16 @@ static inline bool is_64_bit_mode(struct kvm_vcpu *vcpu)
 
 static inline bool is_64_bit_hypercall(struct kvm_vcpu *vcpu)
 {
+#ifdef CONFIG_X86_64
 	/*
 	 * If running with protected guest state, the CS register is not
 	 * accessible. The hypercall register values will have had to been
 	 * provided in 64-bit mode, so assume the guest is in 64-bit.
 	 */
 	return vcpu->arch.guest_state_protected || is_64_bit_mode(vcpu);
+#else
+	return false;
+#endif
 }
 
 static __always_inline unsigned long kvm_reg_mode_mask(struct kvm_vcpu *vcpu)
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#15 lore raw

PATCH v3 13/40 KVM: x86: Move update_cr8_intercept() to lapic.c

In reply to Sean Christopherson

Move update_cr8_intercept() to lapic.c so that it's globally visible in anticipation of extracting most of the register-specific code out of x86.c and into a new compilation unit. Opportunistically prefix the helper kvm_lapic_ to make its role/scope more obvious.

No functional change intended.

---
 arch/x86/kvm/lapic.c | 26 ++++++++++++++++++++++++++
 arch/x86/kvm/lapic.h |  1 +
 arch/x86/kvm/x86.c   | 34 +++-------------------------------
 3 files changed, 30 insertions(+), 31 deletions(-)
arch/x86/kvm/lapic.c +26 -0
index 15777869b292..9d2df8623f6d 100644
@@ -2761,6 +2761,32 @@ u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
 	return (tpr & 0xf0) >> 4;
 }
 
+void kvm_lapic_update_cr8_intercept(struct kvm_vcpu *vcpu)
+{
+	int max_irr, tpr;
+
+	if (!kvm_x86_ops.update_cr8_intercept)
+		return;
+
+	if (!lapic_in_kernel(vcpu))
+		return;
+
+	if (vcpu->arch.apic->apicv_active)
+		return;
+
+	if (!vcpu->arch.apic->vapic_addr)
+		max_irr = kvm_lapic_find_highest_irr(vcpu);
+	else
+		max_irr = -1;
+
+	if (max_irr != -1)
+		max_irr >>= 4;
+
+	tpr = kvm_lapic_get_cr8(vcpu);
+
+	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
+}
+
 static void __kvm_apic_set_base(struct kvm_vcpu *vcpu, u64 value)
 {
 	u64 old_value = vcpu->arch.apic_base;
arch/x86/kvm/lapic.h +1 -0
index f763cd29a508..71970213dc1f 100644
@@ -100,6 +100,7 @@ int kvm_apic_accept_events(struct kvm_vcpu *vcpu);
 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event);
 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu);
 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8);
+void kvm_lapic_update_cr8_intercept(struct kvm_vcpu *vcpu);
 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu);
 void kvm_apic_set_version(struct kvm_vcpu *vcpu);
 void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu);
arch/x86/kvm/x86.c +3 -31
index a102269a7af9..034428b3d8e9 100644
@@ -128,7 +128,6 @@ static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
 				    KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST	| \
 				    KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST)
 
-static void update_cr8_intercept(struct kvm_vcpu *vcpu);
 static void process_nmi(struct kvm_vcpu *vcpu);
 static void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
 static void store_regs(struct kvm_vcpu *vcpu);
@@ -5337,7 +5336,7 @@ static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
 	r = kvm_apic_set_state(vcpu, s);
 	if (r)
 		return r;
-	update_cr8_intercept(vcpu);
+	kvm_lapic_update_cr8_intercept(vcpu);
 
 	return 0;
 }
@@ -10582,33 +10581,6 @@ static void post_kvm_run_save(struct kvm_vcpu *vcpu)
 		kvm_run->flags |= KVM_RUN_X86_GUEST_MODE;
 }
 
-static void update_cr8_intercept(struct kvm_vcpu *vcpu)
-{
-	int max_irr, tpr;
-
-	if (!kvm_x86_ops.update_cr8_intercept)
-		return;
-
-	if (!lapic_in_kernel(vcpu))
-		return;
-
-	if (vcpu->arch.apic->apicv_active)
-		return;
-
-	if (!vcpu->arch.apic->vapic_addr)
-		max_irr = kvm_lapic_find_highest_irr(vcpu);
-	else
-		max_irr = -1;
-
-	if (max_irr != -1)
-		max_irr >>= 4;
-
-	tpr = kvm_lapic_get_cr8(vcpu);
-
-	kvm_x86_call(update_cr8_intercept)(vcpu, tpr, max_irr);
-}
-
-
 int kvm_check_nested_events(struct kvm_vcpu *vcpu)
 {
 	if (kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
@@ -11349,7 +11321,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 			kvm_x86_call(enable_irq_window)(vcpu);
 
 		if (kvm_lapic_enabled(vcpu)) {
-			update_cr8_intercept(vcpu);
+			kvm_lapic_update_cr8_intercept(vcpu);
 			kvm_lapic_sync_to_vapic(vcpu);
 		}
 	}
@@ -12495,7 +12467,7 @@ static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
 	kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
 	kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
 
-	update_cr8_intercept(vcpu);
+	kvm_lapic_update_cr8_intercept(vcpu);
 
 	/* Older userspace won't unhalt the vcpu on reset. */
 	if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#18 lore raw

PATCH v3 14/40 KVM: x86: Move async #PF helpers to x86.h (as inlines)

In reply to Sean Christopherson

Move kvm_pv_async_pf_enabled() and kvm_async_pf_hash_reset() to x86.h in anticipation of extracting the majority of register and MSR specific code out of x86.c.

No functional change intended.

---
 arch/x86/kvm/x86.c | 19 -------------------
 arch/x86/kvm/x86.h | 19 +++++++++++++++++++
 2 files changed, 19 insertions(+), 19 deletions(-)
arch/x86/kvm/x86.c +0 -19
index 034428b3d8e9..cd68a5bad0c6 100644
@@ -566,13 +566,6 @@ static struct kmem_cache *kvm_alloc_emulator_cache(void)
 
 static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
 
-static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
-{
-	int i;
-	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
-		vcpu->arch.apf.gfns[i] = ~0;
-}
-
 static void kvm_destroy_user_return_msrs(void)
 {
 	int cpu;
@@ -1023,18 +1016,6 @@ bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr)
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_require_dr);
 
-static bool __kvm_pv_async_pf_enabled(u64 data)
-{
-	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
-
-	return (data & mask) == mask;
-}
-
-static bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
-{
-	return __kvm_pv_async_pf_enabled(vcpu->arch.apf.msr_en_val);
-}
-
 static inline u64 pdptr_rsvd_bits(struct kvm_vcpu *vcpu)
 {
 	return vcpu->arch.reserved_gpa_bits | rsvd_bits(5, 8) | rsvd_bits(1, 2);
arch/x86/kvm/x86.h +19 -0
index 3845b10020c9..acb22167901f 100644
@@ -556,6 +556,25 @@ static inline bool kvm_pat_valid(u64 data)
 	return (data | ((data & 0x0202020202020202ull) << 1)) == data;
 }
 
+static inline bool __kvm_pv_async_pf_enabled(u64 data)
+{
+	u64 mask = KVM_ASYNC_PF_ENABLED | KVM_ASYNC_PF_DELIVERY_AS_INT;
+
+	return (data & mask) == mask;
+}
+
+static inline bool kvm_pv_async_pf_enabled(struct kvm_vcpu *vcpu)
+{
+	return __kvm_pv_async_pf_enabled(vcpu->arch.apf.msr_en_val);
+}
+
+static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
+{
+	int i;
+	for (i = 0; i < ASYNC_PF_PER_VCPU; i++)
+		vcpu->arch.apf.gfns[i] = ~0;
+}
+
 /*
  * Trigger machine check on the host. We assume all the MSRs are already set up
  * by the CPU and that we still run on the same CPU as the MCE occurred on.
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#23 lore raw

PATCH v3 15/40 KVM: x86: Move the bulk of register specific code from x86.c to regs.c

In reply to Sean Christopherson

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code (except for EFER, which can hardly be called an MSR), as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h |   2 -
 arch/x86/kvm/Makefile           |   4 +-
 arch/x86/kvm/regs.c             | 875 +++++++++++++++++++++++++++++++
 arch/x86/kvm/regs.h             |  31 ++
 arch/x86/kvm/x86.c              | 885 +-------------------------------
 arch/x86/kvm/x86.h              |   2 +
 6 files changed, 918 insertions(+), 881 deletions(-)
 create mode 100644 arch/x86/kvm/regs.c
arch/x86/include/asm/kvm_host.h +0 -2
index 6ae7d539af90..983bdc84f9f9 100644
@@ -2332,8 +2332,6 @@ static inline int __kvm_irq_line_state(unsigned long *irq_state,
 void kvm_inject_nmi(struct kvm_vcpu *vcpu);
 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu);
 
-void kvm_update_dr7(struct kvm_vcpu *vcpu);
-
 bool __kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 				       bool always_retry);
 
arch/x86/kvm/Makefile +2 -2
index 77337c37324b..f39c311fd756 100644
@@ -5,8 +5,8 @@ ccflags-$(CONFIG_KVM_WERROR) += -Werror
 
 include $(srctree)/virt/kvm/Makefile.kvm
 
-kvm-y			+= x86.o emulate.o irq.o lapic.o cpuid.o pmu.o mtrr.o \
-			   debugfs.o mmu/mmu.o mmu/page_track.o mmu/spte.o
+kvm-y			+= x86.o emulate.o irq.o lapic.o cpuid.o pmu.o regs.o \
+			   mtrr.o debugfs.o mmu/mmu.o mmu/page_track.o mmu/spte.o
 
 kvm-$(CONFIG_X86_64) += mmu/tdp_iter.o mmu/tdp_mmu.o
 kvm-$(CONFIG_KVM_IOAPIC) += i8259.o i8254.o ioapic.o
arch/x86/kvm/regs.c new file +875 -0

875 lines not on this page · raw message

arch/x86/kvm/regs.h +31 -0
index a57ba26279ed..c224874bbdde 100644
@@ -389,6 +389,14 @@ static inline bool kvm_dr6_valid(u64 data)
 	return !(data >> 32);
 }
 
+static inline unsigned long kvm_get_effective_dr7(struct kvm_vcpu *vcpu)
+{
+	if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
+		return vcpu->arch.guest_debug_dr7;
+
+	return vcpu->arch.dr7;
+}
+
 static inline void enter_guest_mode(struct kvm_vcpu *vcpu)
 {
 	vcpu->arch.hflags |= HF_GUEST_MASK;
@@ -412,4 +420,27 @@ static inline bool is_guest_mode(struct kvm_vcpu *vcpu)
 	return vcpu->arch.hflags & HF_GUEST_MASK;
 }
 
+static inline unsigned long kvm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
+{
+	return kvm_x86_call(get_segment_base)(vcpu, seg);
+}
+
+void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
+
+void kvm_x86_vcpu_ioctl_get_sregs2(struct kvm_vcpu *vcpu,
+				   struct kvm_sregs2 *sregs2);
+int kvm_x86_vcpu_ioctl_set_sregs2(struct kvm_vcpu *vcpu,
+				  struct kvm_sregs2 *sregs2);
+
+void kvm_run_sync_regs_to_user(struct kvm_vcpu *vcpu);
+int kvm_run_sync_regs_from_user(struct kvm_vcpu *vcpu);
+
+void kvm_update_dr0123(struct kvm_vcpu *vcpu);
+void kvm_update_dr7(struct kvm_vcpu *vcpu);
+int kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
+				     struct kvm_debugregs *dbgregs);
+int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
+				     struct kvm_debugregs *dbgregs);
+
+
 #endif
arch/x86/kvm/x86.c +8 -877

978 lines not on this page · raw message

arch/x86/kvm/x86.h +2 -0
index acb22167901f..80ed36d5d62a 100644
@@ -403,6 +403,7 @@ int handle_ud(struct kvm_vcpu *vcpu);
 
 void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
 				   struct kvm_queued_exception *ex);
+void kvm_handle_exception_payload_quirk(struct kvm_vcpu *vcpu);
 
 int kvm_mtrr_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data);
 int kvm_mtrr_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata);
@@ -597,6 +598,7 @@ static inline void kvm_machine_check(void)
 int kvm_spec_ctrl_test_value(u64 value);
 int kvm_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
 			      struct x86_exception *e);
+void kvm_invalidate_pcid(struct kvm_vcpu *vcpu, unsigned long pcid);
 int kvm_handle_invpcid(struct kvm_vcpu *vcpu, unsigned long type, gva_t gva);
 bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type);
 
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#28 lore raw

PATCH v3 16/40 KVM: x86: Move local APIC specific helpers out of asm/kvm_host.h

In reply to Sean Christopherson

Move single-use local APIC IRQ helpers out of asm/kvm_host.h so that they are co-located with their user, and not exposed to the broader world.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 12 ------------
 arch/x86/kvm/irq.c              |  7 +++++++
 arch/x86/kvm/lapic.h            |  5 +++++
 3 files changed, 12 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -12
index 983bdc84f9f9..ee205f8ad5af 100644
@@ -1772,11 +1772,6 @@ struct kvm_lapic_irq {
 	bool msi_redir_hint;
 };
 
-static inline u16 kvm_lapic_irq_dest_mode(bool dest_mode_logical)
-{
-	return dest_mode_logical ? APIC_DEST_LOGICAL : APIC_DEST_PHYSICAL;
-}
-
 enum kvm_x86_run_flags {
 	KVM_RUN_FORCE_IMMEDIATE_EXIT	= BIT(0),
 	KVM_RUN_LOAD_GUEST_DR6		= BIT(1),
@@ -2510,13 +2505,6 @@ void __user *__x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu);
 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu);
 
-static inline bool kvm_irq_is_postable(struct kvm_lapic_irq *irq)
-{
-	/* We can only post Fixed and LowPrio IRQs */
-	return (irq->delivery_mode == APIC_DM_FIXED ||
-		irq->delivery_mode == APIC_DM_LOWEST);
-}
-
 static inline void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
 {
 	kvm_x86_call(vcpu_blocking)(vcpu);
arch/x86/kvm/irq.c +7 -0
index 9519fec09ee6..2b4e68e7cadb 100644
@@ -423,6 +423,13 @@ void kvm_arch_irq_routing_update(struct kvm *kvm)
 		kvm_make_scan_ioapic_request(kvm);
 }
 
+static bool kvm_irq_is_postable(struct kvm_lapic_irq *irq)
+{
+	/* We can only post Fixed and LowPrio IRQs */
+	return (irq->delivery_mode == APIC_DM_FIXED ||
+		irq->delivery_mode == APIC_DM_LOWEST);
+}
+
 static int kvm_pi_update_irte(struct kvm_kernel_irqfd *irqfd,
 			      struct kvm_kernel_irq_routing_entry *entry)
 {
arch/x86/kvm/lapic.h +5 -0
index 71970213dc1f..32f09b25884a 100644
@@ -237,6 +237,11 @@ static inline int kvm_lapic_latched_init(struct kvm_vcpu *vcpu)
 	return lapic_in_kernel(vcpu) && test_bit(KVM_APIC_INIT, &vcpu->arch.apic->pending_events);
 }
 
+static inline u16 kvm_lapic_irq_dest_mode(bool dest_mode_logical)
+{
+	return dest_mode_logical ? APIC_DEST_LOGICAL : APIC_DEST_PHYSICAL;
+}
+
 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector);
 
 bool kvm_lapic_suppress_eoi_broadcast(struct kvm_lapic *apic);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#31 lore raw

PATCH v3 17/40 KVM: x86: Drop defunct vcpu_tsc_khz() declaration

In reply to Sean Christopherson

Remove a dead vcpu_tsc_khz() declaration. No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 2 --
 1 file changed, 2 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -2
index ee205f8ad5af..2e535027dd5c 100644
@@ -2146,8 +2146,6 @@ int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);
 
 extern bool tdp_enabled;
 
-u64 vcpu_tsc_khz(struct kvm_vcpu *vcpu);
-
 /*
  * EMULTYPE_NO_DECODE - Set when re-emulating an instruction (after completing
  *			userspace I/O) to indicate that the emulation context
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#34 lore raw

PATCH v3 18/40 KVM: x86: Move kvm_caps and kvm_host_values to asm/kvm_host.h

In reply to Sean Christopherson

Relocate the kvm_caps and kvm_host_values struct definitions and their associated global variable declarations to asm/kvm_host.h to allow for a variety of cleanups in x86.h and mmu.h, and to establish a (hopefully) maintainable rule that asm/kvm_host.h's role is to define common structures (and declare any associated globals), and anything needed by arch-neutral KVM.

While it would be lovely to trim kvm_host.h down to the point where it *only* holds things needed by arch-neutral and/or non-KVM code, multiple attempts to do just that have failed miserably. Trying to "hide" code from arch-neutral KVM is too restrictive (and ultimately pointless), and KVM x86 itself also needs a place to define common structures and their globals, e.g. to avoid inconsistent header include chains and/or misplaced helpers.

E.g. as pointed out by Kai, it's weird that x86.h, which is a kitchen sink of sorts, includes regs.h, but not mmu.h. Literally the only reason that x86.h doesn't include mmu.h is that mmu.h references struct kvm_host, which is currently defined in x86.h. As a result of odd include ordering, the very clearly MMU-specific helper mmu_is_nested() lives in x86.h, not mmu.h

"Fix" the kvm_host dependency so that x86.h can be the "central" include everyone expects it to be, and set KVM x86 on the path to having somewhat sensible "rules" for what goes where:

- asm/kvm_host.h holds "common" structure definitions and associated key global variables, and things that are referenced by arch-neutral KVM.
- <thing>.{c,h} holds relevant declarations and definitions.
- x86.{c,h} is the kitchen sink for everything else.

---
 arch/x86/include/asm/kvm_host.h | 44 ++++++++++++++++++++++++++++++++
 arch/x86/kvm/x86.h              | 45 ---------------------------------
 2 files changed, 44 insertions(+), 45 deletions(-)
arch/x86/include/asm/kvm_host.h +44 -0
index 2e535027dd5c..f7130eb98473 100644
@@ -315,6 +315,50 @@ enum x86_intercept_stage;
 struct kvm_kernel_irqfd;
 struct kvm_kernel_irq_routing_entry;
 
+struct kvm_caps {
+	/* control of guest tsc rate supported? */
+	bool has_tsc_control;
+	/* maximum supported tsc_khz for guests */
+	u32  max_guest_tsc_khz;
+	/* number of bits of the fractional part of the TSC scaling ratio */
+	u8   tsc_scaling_ratio_frac_bits;
+	/* maximum allowed value of TSC scaling ratio */
+	u64  max_tsc_scaling_ratio;
+	/* 1ull << kvm_caps.tsc_scaling_ratio_frac_bits */
+	u64  default_tsc_scaling_ratio;
+	/* bus lock detection supported? */
+	bool has_bus_lock_exit;
+	/* notify VM exit supported? */
+	bool has_notify_vmexit;
+	/* bit mask of VM types */
+	u32 supported_vm_types;
+
+	u64 supported_mce_cap;
+	u64 supported_xcr0;
+	u64 supported_xss;
+	u64 supported_perf_cap;
+
+	u64 supported_quirks;
+	u64 inapplicable_quirks;
+};
+extern struct kvm_caps kvm_caps;
+
+struct kvm_host_values {
+	/*
+	 * The host's raw MAXPHYADDR, i.e. the number of non-reserved physical
+	 * address bits irrespective of features that repurpose legal bits,
+	 * e.g. MKTME.
+	 */
+	u8 maxphyaddr;
+
+	u64 efer;
+	u64 xcr0;
+	u64 xss;
+	u64 s_cet;
+	u64 arch_capabilities;
+};
+extern struct kvm_host_values kvm_host;
+
 /*
  * kvm_mmu_page_role tracks the properties of a shadow page (where shadow page
  * also includes TDP pages) to determine whether or not a page can be used in
arch/x86/kvm/x86.h +0 -45

57 lines not on this page · raw message

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#37 lore raw

PATCH v3 19/40 KVM: x86: Swap the include order between x86.h and mmu.h

In reply to Sean Christopherson

Invert the include ordering between x86.h and mmu.h, so that x86.h is the "top-level" include for KVM x86.

No functional change intended.

---
 arch/x86/kvm/mmu.h | 6 +++++-
 arch/x86/kvm/x86.h | 6 +-----
 2 files changed, 6 insertions(+), 6 deletions(-)
arch/x86/kvm/mmu.h +5 -1
index e1bb663ebbd5..28fca48dcf64 100644
@@ -4,7 +4,6 @@
 
 #include <linux/kvm_host.h>
 #include "regs.h"
-#include "x86.h"
 #include "cpuid.h"
 
 extern bool __read_mostly enable_mmio_caching;
@@ -300,6 +299,11 @@ static inline void kvm_update_page_stats(struct kvm *kvm, int level, int count)
 	atomic64_add(count, &kvm->stat.pages[level - 1]);
 }
 
+static inline bool mmu_is_nested(struct kvm_vcpu *vcpu)
+{
+	return vcpu->arch.walk_mmu == &vcpu->arch.nested_mmu;
+}
+
 static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 				      struct kvm_mmu *mmu,
 				      gpa_t gpa, u64 access,
arch/x86/kvm/x86.h +1 -5
index b7d3b54cde15..a0e68eaf1f80 100644
@@ -6,6 +6,7 @@
 #include <asm/fpu/xstate.h>
 #include <asm/mce.h>
 #include <asm/pvclock.h>
+#include "mmu.h"
 #include "regs.h"
 #include "kvm_emulate.h"
 #include "cpuid.h"
@@ -210,11 +211,6 @@ static inline bool x86_exception_has_error_code(unsigned int vector)
 	return (1U << vector) & exception_has_error_code;
 }
 
-static inline bool mmu_is_nested(struct kvm_vcpu *vcpu)
-{
-	return vcpu->arch.walk_mmu == &vcpu->arch.nested_mmu;
-}
-
 static inline u8 vcpu_virt_addr_bits(struct kvm_vcpu *vcpu)
 {
 	return kvm_is_cr4_bit_set(vcpu, X86_CR4_LA57) ? 57 : 48;
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#43 lore raw

PATCH v3 20/40 KVM: x86: Move tdp_enabled from kvm_host.h to mmu.h

In reply to Sean Christopherson

Relocated the declaration of tdp_enabled into mmu.h, and opportunistically hoist tdp_mmu_enabled up to the top so that the two are co-located.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h |  2 --
 arch/x86/kvm/mmu.h              | 12 ++++++------
 2 files changed, 6 insertions(+), 8 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -2
index f7130eb98473..19091d89d3cc 100644
@@ -2188,8 +2188,6 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
 
 int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);
 
-extern bool tdp_enabled;
-
 /*
  * EMULTYPE_NO_DECODE - Set when re-emulating an instruction (after completing
  *			userspace I/O) to indicate that the emulation context
arch/x86/kvm/mmu.h +6 -6
index 28fca48dcf64..0eaea2d4fac9 100644
@@ -6,6 +6,12 @@
 #include "regs.h"
 #include "cpuid.h"
 
+extern bool tdp_enabled;
+#ifdef CONFIG_X86_64
+extern bool tdp_mmu_enabled;
+#else
+#define tdp_mmu_enabled false
+#endif
 extern bool __read_mostly enable_mmio_caching;
 
 #define PT_WRITABLE_SHIFT 1
@@ -260,12 +266,6 @@ static inline bool kvm_shadow_root_allocated(struct kvm *kvm)
 	return smp_load_acquire(&kvm->arch.shadow_root_allocated);
 }
 
-#ifdef CONFIG_X86_64
-extern bool tdp_mmu_enabled;
-#else
-#define tdp_mmu_enabled false
-#endif
-
 int kvm_tdp_mmu_map_private_pfn(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn);
 
 static inline bool kvm_memslots_have_rmaps(struct kvm *kvm)
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#46 lore raw

PATCH v3 21/40 KVM: x86: Move eager_page_split to mmu.{c,h}

In reply to Sean Christopherson

Move KVM's eager_page_split module param to the MMU, as it is very much an MMU knob.

No functional change intended.

---
 arch/x86/kvm/mmu.h     | 1 +
 arch/x86/kvm/mmu/mmu.c | 3 +++
 arch/x86/kvm/x86.c     | 3 ---
 arch/x86/kvm/x86.h     | 2 --
 4 files changed, 4 insertions(+), 5 deletions(-)
arch/x86/kvm/mmu.h +1 -0
index 0eaea2d4fac9..d30676935fff 100644
@@ -13,6 +13,7 @@ extern bool tdp_mmu_enabled;
 #define tdp_mmu_enabled false
 #endif
 extern bool __read_mostly enable_mmio_caching;
+extern bool eager_page_split;
 
 #define PT_WRITABLE_SHIFT 1
 #define PT_USER_SHIFT 2
arch/x86/kvm/mmu/mmu.c +3 -0
index b8f2edf2cfeb..e4d971d42f0e 100644
@@ -114,6 +114,9 @@ module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(tdp_mmu_enabled);
 #endif
 
+bool __read_mostly eager_page_split = true;
+module_param(eager_page_split, bool, 0644);
+
 static int max_huge_page_level __read_mostly;
 static int tdp_root_level __read_mostly;
 static int max_tdp_level __read_mostly;
arch/x86/kvm/x86.c +0 -3
index 20eeff79b46d..be421f467563 100644
@@ -177,9 +177,6 @@ module_param(force_emulation_prefix, int, 0644);
 int __read_mostly pi_inject_timer = -1;
 module_param(pi_inject_timer, bint, 0644);
 
-bool __read_mostly eager_page_split = true;
-module_param(eager_page_split, bool, 0644);
-
 /* Enable/disable SMT_RSB bug mitigation */
 static bool __read_mostly mitigate_smt_rsb;
 module_param(mitigate_smt_rsb, bool, 0444);
arch/x86/kvm/x86.h +0 -2
index a0e68eaf1f80..635a21bfa681 100644
@@ -415,8 +415,6 @@ extern int pi_inject_timer;
 
 extern bool report_ignored_msrs;
 
-extern bool eager_page_split;
-
 static inline void kvm_pr_unimpl_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 {
 	if (report_ignored_msrs)
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#49 lore raw

PATCH v3 22/40 KVM: x86/hyperv: Eliminate an unnecessary include of x86.h in hyperv.h

In reply to Sean Christopherson

Drop an mostly unused include of x86.h from hyperv.h, and instead pull in regs.h, which is need for at least is_guest_mode(). This eliminates the last include of x86.h from a common x86 header, i.e. solidifies that x86.h is the top of the pyramid.

Add a missing x86.h include in cpuid.c to avoid build breakage.

No functional change intended.

---
 arch/x86/kvm/cpuid.c  | 1 +
 arch/x86/kvm/hyperv.h | 3 ++-
 2 files changed, 3 insertions(+), 1 deletion(-)
arch/x86/kvm/cpuid.c +1 -0
index fd3b02575cd0..db8be9173bd0 100644
@@ -28,6 +28,7 @@
 #include "trace.h"
 #include "pmu.h"
 #include "xen.h"
+#include "x86.h"
 
 /*
  * Unlike "struct cpuinfo_x86.x86_capability", kvm_cpu_caps doesn't need to be
arch/x86/kvm/hyperv.h +2 -1
index 65e89ed65349..1c8f7aaab063 100644
@@ -22,7 +22,8 @@
 #define __ARCH_X86_KVM_HYPERV_H__
 
 #include <linux/kvm_host.h>
-#include "x86.h"
+
+#include "regs.h"
 
 #ifdef CONFIG_KVM_HYPERV
 
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#51 lore raw

PATCH v3 23/40 KVM: x86: Move kvm_{load,put}_guest_fpu() to fpu.h

In reply to Sean Christopherson

Move the kvm_{load,put}_guest_fpu() helpers to fpu.h in anticipation of moving the bulk of KVM's register specific code out of x86.c.

No functional change intended.

---
 arch/x86/kvm/fpu.h | 26 ++++++++++++++++++++++++++
 arch/x86/kvm/x86.c | 24 ------------------------
 2 files changed, 26 insertions(+), 24 deletions(-)
arch/x86/kvm/fpu.h +26 -0
index f898781b6a06..6b7b628f530d 100644
@@ -3,8 +3,34 @@
 #ifndef __KVM_FPU_H_
 #define __KVM_FPU_H_
 
+#include <linux/kvm_host.h>
+
+#include <trace/events/kvm.h>
+
 #include <asm/fpu/api.h>
 
+/* Swap (qemu) user FPU context for the guest FPU context. */
+static inline void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
+	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
+	trace_kvm_fpu(1);
+}
+
+/* When vcpu_run ends, restore user space FPU context. */
+static inline void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
+	++vcpu->stat.fpu_reload;
+	trace_kvm_fpu(0);
+}
+
 typedef u32		__attribute__((vector_size(16))) sse128_t;
 #define __sse128_u	union { sse128_t vec; u64 as_u64[2]; u32 as_u32[4]; }
 #define sse128_lo(x)	({ __sse128_u t; t.vec = x; t.as_u64[0]; })
arch/x86/kvm/x86.c +0 -24
index be421f467563..56ccb6b77abb 100644
@@ -133,8 +133,6 @@ static void store_regs(struct kvm_vcpu *vcpu);
 static int sync_regs(struct kvm_vcpu *vcpu);
 
 static DEFINE_MUTEX(vendor_module_lock);
-static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu);
-static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu);
 
 struct kvm_x86_ops kvm_x86_ops __read_mostly;
 
@@ -11432,28 +11430,6 @@ static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
 	return 0;
 }
 
-/* Swap (qemu) user FPU context for the guest FPU context. */
-static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
-{
-	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
-		return;
-
-	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
-	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
-	trace_kvm_fpu(1);
-}
-
-/* When vcpu_run ends, restore user space FPU context. */
-static void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
-{
-	if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
-		return;
-
-	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
-	++vcpu->stat.fpu_reload;
-	trace_kvm_fpu(0);
-}
-
 static int kvm_x86_vcpu_pre_run(struct kvm_vcpu *vcpu)
 {
 	/*
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#55 lore raw

PATCH v3 24/40 KVM: x86: Extract get/set MSR (list) ioctl logic to helpers

In reply to Sean Christopherson

Extract the code for getting/setting MSRs and MSR lists to dedicated helpers in anticipation of moving the MSR code to a new msrs.c.

No functional change intended.

---
 arch/x86/kvm/x86.c | 135 ++++++++++++++++++++++++++-------------------
 1 file changed, 78 insertions(+), 57 deletions(-)
arch/x86/kvm/x86.c +78 -57
index 56ccb6b77abb..64c3680d889b 100644
@@ -4602,6 +4602,61 @@ static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
 	return __kvm_x86_dev_get_attr(attr, &val);
 }
 
+static int kvm_get_msr_index_list(struct kvm_msr_list __user *user_msr_list)
+{
+	struct kvm_msr_list msr_list;
+	unsigned int n;
+
+	if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
+		return -EFAULT;
+
+	n = msr_list.nmsrs;
+	msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
+	if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
+		return -EFAULT;
+
+	if (n < msr_list.nmsrs)
+		return -E2BIG;
+
+	if (copy_to_user(user_msr_list->indices, &msrs_to_save,
+				num_msrs_to_save * sizeof(u32)))
+		return -EFAULT;
+
+	if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
+			 &emulated_msrs, num_emulated_msrs * sizeof(u32)))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int kvm_get_feature_msr_index_list(struct kvm_msr_list __user *user_msr_list)
+{
+	struct kvm_msr_list msr_list;
+	unsigned int n;
+
+	if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
+		return -EFAULT;
+
+	n = msr_list.nmsrs;
+	msr_list.nmsrs = num_msr_based_features;
+	if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
+		return -EFAULT;
+
+	if (n < msr_list.nmsrs)
+		return -E2BIG;
+
+	if (copy_to_user(user_msr_list->indices, &msr_based_features,
+				num_msr_based_features * sizeof(u32)))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int kvm_get_feature_msrs(struct kvm_msrs __user *user_msrs)
+{
+	return msr_io(NULL, user_msrs, do_get_feature_msr, 1);
+}
+
 long kvm_arch_dev_ioctl(struct file *filp,
 			unsigned int ioctl, unsigned long arg)
 {
@@ -4609,32 +4664,9 @@ long kvm_arch_dev_ioctl(struct file *filp,
 	long r;
 
 	switch (ioctl) {
-	case KVM_GET_MSR_INDEX_LIST: {
-		struct kvm_msr_list __user *user_msr_list = argp;
-		struct kvm_msr_list msr_list;
-		unsigned n;
-
-		r = -EFAULT;
-		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
-			goto out;
-		n = msr_list.nmsrs;
-		msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
-		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
-			goto out;
-		r = -E2BIG;
-		if (n < msr_list.nmsrs)
-			goto out;
-		r = -EFAULT;
-		if (copy_to_user(user_msr_list->indices, &msrs_to_save,
-				 num_msrs_to_save * sizeof(u32)))
-			goto out;
-		if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
-				 &emulated_msrs,
-				 num_emulated_msrs * sizeof(u32)))
-			goto out;
-		r = 0;
+	case KVM_GET_MSR_INDEX_LIST:
+		r = kvm_get_msr_index_list(argp);
 		break;
-	}
 	case KVM_GET_SUPPORTED_CPUID:
 	case KVM_GET_EMULATED_CPUID: {
 		struct kvm_cpuid2 __user *cpuid_arg = argp;
@@ -4662,30 +4694,11 @@ long kvm_arch_dev_ioctl(struct file *filp,
 			goto out;
 		r = 0;
 		break;
-	case KVM_GET_MSR_FEATURE_INDEX_LIST: {
-		struct kvm_msr_list __user *user_msr_list = argp;
-		struct kvm_msr_list msr_list;
-		unsigned int n;
-
-		r = -EFAULT;
-		if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
-			goto out;
-		n = msr_list.nmsrs;
-		msr_list.nmsrs = num_msr_based_features;
-		if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
-			goto out;
-		r = -E2BIG;
-		if (n < msr_list.nmsrs)
-			goto out;
-		r = -EFAULT;
-		if (copy_to_user(user_msr_list->indices, &msr_based_features,
-				 num_msr_based_features * sizeof(u32)))
-			goto out;
-		r = 0;
+	case KVM_GET_MSR_FEATURE_INDEX_LIST:
+		r = kvm_get_feature_msr_index_list(argp);
 		break;
-	}
 	case KVM_GET_MSRS:
-		r = msr_io(NULL, argp, do_get_feature_msr, 1);
+		r = kvm_get_feature_msrs(argp);
 		break;
 #ifdef CONFIG_KVM_HYPERV
 	case KVM_GET_SUPPORTED_HV_CPUID:
@@ -5719,6 +5732,20 @@ static int kvm_get_reg_list(struct kvm_vcpu *vcpu,
 	return 0;
 }
 
+static int kvm_get_msrs(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs)
+{
+	guard(srcu)(&vcpu->kvm->srcu);
+
+	return msr_io(vcpu, user_msrs, do_get_msr, 1);
+}
+
+static int kvm_set_msrs(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs)
+{
+	guard(srcu)(&vcpu->kvm->srcu);
+
+	return msr_io(vcpu, user_msrs, do_set_msr, 0);
+}
+
 long kvm_arch_vcpu_ioctl(struct file *filp,
 			 unsigned int ioctl, unsigned long arg)
 {
@@ -5823,18 +5850,12 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
 		r = 0;
 		break;
 	}
-	case KVM_GET_MSRS: {
-		int idx = srcu_read_lock(&vcpu->kvm->srcu);
-		r = msr_io(vcpu, argp, do_get_msr, 1);
-		srcu_read_unlock(&vcpu->kvm->srcu, idx);
+	case KVM_GET_MSRS:
+		r = kvm_get_msrs(vcpu, argp);
 		break;
-	}
-	case KVM_SET_MSRS: {
-		int idx = srcu_read_lock(&vcpu->kvm->srcu);
-		r = msr_io(vcpu, argp, do_set_msr, 0);
-		srcu_read_unlock(&vcpu->kvm->srcu, idx);
+	case KVM_SET_MSRS:
+		r = kvm_set_msrs(vcpu, argp);
 		break;
-	}
 	case KVM_GET_ONE_REG:
 	case KVM_SET_ONE_REG:
 		r = kvm_get_set_one_reg(vcpu, ioctl, argp);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#58 lore raw

PATCH v3 25/40 KVM: x86: Expose several TSC helpers via x86.h for use by MSR code

In reply to Sean Christopherson

Begrudgingly move adjust_tsc_offset_{guest,host}() to x86.h as inlines, and expose several other TSC helpers in anticipation of moving KVM's MSR code to a dedicated msrs.c. Unfortunately for KVM, several MSRs that KVM emulates can affect TSC state.

Opportunistically drop a superfluous local "tsc_offset" variable, whose existence causes checkpatch to complain about lack of a blank line.

No functional change intended.

---
 arch/x86/kvm/x86.c | 22 +++-------------------
 arch/x86/kvm/x86.h | 19 +++++++++++++++++++
 2 files changed, 22 insertions(+), 19 deletions(-)
arch/x86/kvm/x86.c +3 -19
index 64c3680d889b..bf15c122f837 100644
@@ -2225,7 +2225,7 @@ u64 kvm_scale_tsc(u64 tsc, u64 ratio)
 	return _tsc;
 }
 
-static u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
+u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc)
 {
 	u64 tsc;
 
@@ -2266,7 +2266,7 @@ u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier)
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_calc_nested_tsc_multiplier);
 
-static void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
+void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset)
 {
 	if (vcpu->arch.guest_tsc_protected)
 		return;
@@ -2380,7 +2380,7 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 offset, u64 tsc,
 	kvm_track_tsc_matching(vcpu, !matched);
 }
 
-static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
+void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
 {
 	u64 data = user_value ? *user_value : 0;
 	struct kvm *kvm = vcpu->kvm;
@@ -2448,22 +2448,6 @@ static void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value)
 	raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
 }
 
-static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
-					   s64 adjustment)
-{
-	u64 tsc_offset = vcpu->arch.l1_tsc_offset;
-	kvm_vcpu_write_tsc_offset(vcpu, tsc_offset + adjustment);
-}
-
-static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
-{
-	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
-		WARN_ON(adjustment < 0);
-	adjustment = kvm_scale_tsc((u64) adjustment,
-				   vcpu->arch.l1_tsc_scaling_ratio);
-	adjust_tsc_offset_guest(vcpu, adjustment);
-}
-
 #ifdef CONFIG_X86_64
 
 static u64 read_tsc(void)
arch/x86/kvm/x86.h +19 -0
index 635a21bfa681..31e67b060148 100644
@@ -345,6 +345,25 @@ uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm);
 bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp);
 int kvm_guest_time_update(struct kvm_vcpu *v);
 
+void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value);
+u64 kvm_compute_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc);
+void kvm_vcpu_write_tsc_offset(struct kvm_vcpu *vcpu, u64 l1_offset);
+
+static inline void adjust_tsc_offset_guest(struct kvm_vcpu *vcpu,
+					   s64 adjustment)
+{
+	kvm_vcpu_write_tsc_offset(vcpu, vcpu->arch.l1_tsc_offset + adjustment);
+}
+
+static inline void adjust_tsc_offset_host(struct kvm_vcpu *vcpu, s64 adjustment)
+{
+	if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio)
+		WARN_ON(adjustment < 0);
+	adjustment = kvm_scale_tsc((u64) adjustment,
+				   vcpu->arch.l1_tsc_scaling_ratio);
+	adjust_tsc_offset_guest(vcpu, adjustment);
+}
+
 int kvm_read_guest_virt(struct kvm_vcpu *vcpu,
 	gva_t addr, void *val, unsigned int bytes,
 	struct x86_exception *exception);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#60 lore raw

PATCH v3 26/40 KVM: x86: Move the bulk of MSR specific code from x86.c to msrs.{c,h}

In reply to Sean Christopherson

Introduce msrs.{c,h}, and move the vast majority of MSR specific code out of x86.{c,h}. Use a plural "msrs" instead of just "msr" to be consistent with regs.{c,h}, and to make it easier to differentiate KVM's code from the other 5+ msr.c files in the kernel.

No functional change intended.

---
 arch/x86/kvm/Makefile |    2 +-
 arch/x86/kvm/msrs.c   | 2732 +++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/msrs.h   |  128 ++
 arch/x86/kvm/mtrr.c   |    1 +
 arch/x86/kvm/x86.c    | 2711 +---------------------------------------
 arch/x86/kvm/x86.h    |   87 +-
 6 files changed, 2867 insertions(+), 2794 deletions(-)
 create mode 100644 arch/x86/kvm/msrs.c
 create mode 100644 arch/x86/kvm/msrs.h
arch/x86/kvm/Makefile +1 -1
index f39c311fd756..0474604ab8a1 100644
@@ -5,7 +5,7 @@ ccflags-$(CONFIG_KVM_WERROR) += -Werror
 
 include $(srctree)/virt/kvm/Makefile.kvm
 
-kvm-y			+= x86.o emulate.o irq.o lapic.o cpuid.o pmu.o regs.o \
+kvm-y			+= x86.o emulate.o irq.o lapic.o cpuid.o msrs.o pmu.o regs.o \
 			   mtrr.o debugfs.o mmu/mmu.o mmu/page_track.o mmu/spte.o
 
 kvm-$(CONFIG_X86_64) += mmu/tdp_iter.o mmu/tdp_mmu.o
arch/x86/kvm/msrs.c new file +2732 -0

2,732 lines not on this page · raw message

arch/x86/kvm/msrs.h new file +128 -0

129 lines not on this page · raw message

arch/x86/kvm/mtrr.c +1 -0
index 6f74e2b27c1e..4f3b7b0f6565 100644
@@ -19,6 +19,7 @@
 #include <asm/mtrr.h>
 
 #include "cpuid.h"
+#include "msrs.h"
 #include "x86.h"
 
 static u64 *find_mtrr(struct kvm_vcpu *vcpu, unsigned int msr)
arch/x86/kvm/x86.c +3 -2708

124 lines not on this page · raw message

arch/x86/kvm/x86.h +2 -85

87 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog

Part of the diff is not shown here. View the raw message.

author maintainer
#62 lore raw

PATCH v3 27/40 KVM: x86: Move register helper declarations from kvm_host.h => regs.h

In reply to Sean Christopherson

Relocate declarations of Control/Debug Register, EFLAGS and RIP helpers from x86's kvm_host.h to regs.h, to continue trimming down kvm_host.h.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 17 -----------------
 arch/x86/kvm/regs.h             | 17 +++++++++++++++++
 2 files changed, 17 insertions(+), 17 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -17
index 19091d89d3cc..0f4b16b26a27 100644
@@ -2186,8 +2186,6 @@ void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
 
-int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);
-
 /*
  * EMULTYPE_NO_DECODE - Set when re-emulating an instruction (after completing
  *			userspace I/O) to indicate that the emulation context
@@ -2313,24 +2311,12 @@ void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
 		    int reason, bool has_error_code, u32 error_code);
 
-void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0);
-void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4);
-int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
-int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
-int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
-int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8);
-int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val);
-unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr);
-unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu);
-void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw);
 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr);
 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu);
 
 int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr);
 int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr);
 
-unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu);
-void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu);
 
 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr);
@@ -2520,9 +2506,6 @@ u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc);
 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier);
 u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier);
 
-unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu);
-bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip);
-
 void kvm_make_scan_ioapic_request(struct kvm *kvm);
 void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
 				       unsigned long *vcpu_bitmap);
arch/x86/kvm/regs.h +17 -0
index c224874bbdde..30ef08d60a74 100644
@@ -16,6 +16,18 @@
 
 static_assert(!(KVM_POSSIBLE_CR0_GUEST_BITS & X86_CR0_PDPTR_BITS));
 
+void kvm_post_set_cr0(struct kvm_vcpu *vcpu, unsigned long old_cr0, unsigned long cr0);
+void kvm_post_set_cr4(struct kvm_vcpu *vcpu, unsigned long old_cr4, unsigned long cr4);
+int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
+int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3);
+int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
+int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8);
+int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val);
+unsigned long kvm_get_dr(struct kvm_vcpu *vcpu, int dr);
+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);
+
 static inline bool is_long_mode(struct kvm_vcpu *vcpu)
 {
 #ifdef CONFIG_X86_64
@@ -425,7 +437,12 @@ static inline unsigned long kvm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
 	return kvm_x86_call(get_segment_base)(vcpu, seg);
 }
 
+unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu);
+bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip);
+
+unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu);
 void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
+void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
 
 void kvm_x86_vcpu_ioctl_get_sregs2(struct kvm_vcpu *vcpu,
 				   struct kvm_sregs2 *sregs2);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#68 lore raw

PATCH v3 28/40 KVM: x86: Move kvm_{g,s}et_segment() to inline helpers in regs.h

In reply to Sean Christopherson

Define kvm_{g,s}et_segment() as inline functions in regs.h, as they are literally one-line wrappers to invoke vendor code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h |  2 --
 arch/x86/kvm/regs.h             | 12 ++++++++++++
 arch/x86/kvm/x86.c              | 12 ------------
 3 files changed, 12 insertions(+), 14 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -2
index 0f4b16b26a27..ca2e69c80a8d 100644
@@ -2303,8 +2303,6 @@ int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu);
 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu);
 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu);
 
-void kvm_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
-void kvm_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg);
 int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector, int seg);
 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
 
arch/x86/kvm/regs.h +12 -0
index 30ef08d60a74..7a823422d78e 100644
@@ -437,6 +437,18 @@ static inline unsigned long kvm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
 	return kvm_x86_call(get_segment_base)(vcpu, seg);
 }
 
+static inline void kvm_set_segment(struct kvm_vcpu *vcpu,
+				   struct kvm_segment *var, int seg)
+{
+	kvm_x86_call(set_segment)(vcpu, var, seg);
+}
+
+static inline void kvm_get_segment(struct kvm_vcpu *vcpu,
+				   struct kvm_segment *var, int seg)
+{
+	kvm_x86_call(get_segment)(vcpu, var, seg);
+}
+
 unsigned long kvm_get_linear_rip(struct kvm_vcpu *vcpu);
 bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip);
 
arch/x86/kvm/x86.c +0 -12
index c648fac802f6..660ba27c76ec 100644
@@ -4719,18 +4719,6 @@ static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
 	return handled;
 }
 
-void kvm_set_segment(struct kvm_vcpu *vcpu,
-		     struct kvm_segment *var, int seg)
-{
-	kvm_x86_call(set_segment)(vcpu, var, seg);
-}
-
-void kvm_get_segment(struct kvm_vcpu *vcpu,
-		     struct kvm_segment *var, int seg)
-{
-	kvm_x86_call(get_segment)(vcpu, var, seg);
-}
-
 gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
 			      struct x86_exception *exception)
 {
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#71 lore raw

PATCH v3 29/40 KVM: x86: Remove defunct kvm_load_segment_descriptor() declaration.

In reply to Sean Christopherson

Remove a dead kvm_load_segment_descriptor() declaration, no functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 1 -
 1 file changed, 1 deletion(-)
arch/x86/include/asm/kvm_host.h +0 -1
index ca2e69c80a8d..a861c0d70be0 100644
@@ -2303,7 +2303,6 @@ int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu);
 int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu);
 int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu);
 
-int kvm_load_segment_descriptor(struct kvm_vcpu *vcpu, u16 selector, int seg);
 void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
 
 int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#74 lore raw

PATCH v3 30/40 KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h

In reply to Sean Christopherson

Relocate declarations of MSR helpers (and kvm_nr_uret_msrs) from x86's x86's kvm_host.h to msrs, to continue trimming down kvm_host.h.

Deliberately leave the funky read_msr() where it is, as it will hopefully be removed entirely as part of a broader kernel-API cleanup.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 26 -------------------------
 arch/x86/kvm/msrs.h             | 34 ++++++++++++++++++++++++++++++---
 2 files changed, 31 insertions(+), 29 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -26
index a861c0d70be0..1143140592df 100644
@@ -2094,7 +2094,6 @@ struct kvm_arch_async_pf {
 	u64 error_code;
 };
 
-extern u32 __read_mostly kvm_nr_uret_msrs;
 extern bool __read_mostly allow_smaller_maxphyaddr;
 extern bool __read_mostly enable_apicv;
 extern bool __read_mostly enable_ipiv;
@@ -2278,18 +2277,6 @@ void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu);
 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa);
 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason);
 
-void kvm_enable_efer_bits(u64);
-bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer);
-int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data);
-int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data);
-int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data);
-int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data);
-int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data);
-int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data);
-int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu);
-int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg);
-int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu);
-int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg);
 int kvm_emulate_as_nop(struct kvm_vcpu *vcpu);
 int kvm_emulate_invd(struct kvm_vcpu *vcpu);
 int kvm_emulate_mwait(struct kvm_vcpu *vcpu);
@@ -2311,9 +2298,6 @@ int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
 int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr);
 int kvm_emulate_xsetbv(struct kvm_vcpu *vcpu);
 
-int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr);
-int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr);
-
 int kvm_emulate_rdpmc(struct kvm_vcpu *vcpu);
 
 void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr);
@@ -2488,16 +2472,6 @@ int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
 		    unsigned long ipi_bitmap_high, u32 min,
 		    unsigned long icr, int op_64_bit);
 
-int kvm_add_user_return_msr(u32 msr);
-int kvm_find_user_return_msr(u32 msr);
-int kvm_set_user_return_msr(unsigned index, u64 val, u64 mask);
-u64 kvm_get_user_return_msr(unsigned int slot);
-
-static inline bool kvm_is_supported_user_return_msr(u32 msr)
-{
-	return kvm_find_user_return_msr(msr) >= 0;
-}
-
 u64 kvm_scale_tsc(u64 tsc, u64 ratio);
 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc);
 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier);
arch/x86/kvm/msrs.h +31 -3
index c34f0411ced6..5c8362a8fd97 100644
@@ -11,6 +11,8 @@
 extern bool report_ignored_msrs;
 extern bool ignore_msrs;
 
+extern u32 __read_mostly kvm_nr_uret_msrs;
+
 static inline void kvm_pr_unimpl_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 {
 	if (report_ignored_msrs)
@@ -56,13 +58,39 @@ int kvm_get_set_one_reg(struct kvm_vcpu *vcpu, unsigned int ioctl,
 int kvm_get_reg_list(struct kvm_vcpu *vcpu,
 		     struct kvm_reg_list __user *user_list);
 
+void kvm_enable_efer_bits(u64);
+bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer);
+int kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data);
+int kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data);
+int __kvm_emulate_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data);
+int __kvm_emulate_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data);
+int kvm_msr_read(struct kvm_vcpu *vcpu, u32 index, u64 *data);
+int kvm_msr_write(struct kvm_vcpu *vcpu, u32 index, u64 data);
+int kvm_emulate_rdmsr(struct kvm_vcpu *vcpu);
+int kvm_emulate_rdmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg);
+int kvm_emulate_wrmsr(struct kvm_vcpu *vcpu);
+int kvm_emulate_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg);
+
+fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu);
+fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg);
+
+int kvm_get_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr);
+int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr);
+
+int kvm_add_user_return_msr(u32 msr);
+int kvm_find_user_return_msr(u32 msr);
+int kvm_set_user_return_msr(unsigned index, u64 val, u64 mask);
+u64 kvm_get_user_return_msr(unsigned int slot);
+
+static inline bool kvm_is_supported_user_return_msr(u32 msr)
+{
+	return kvm_find_user_return_msr(msr) >= 0;
+}
+
 void kvm_user_return_msr_cpu_online(void);
 void drop_user_return_notifiers(void);
 void kvm_destroy_user_return_msrs(void);
 
-fastpath_t handle_fastpath_wrmsr(struct kvm_vcpu *vcpu);
-fastpath_t handle_fastpath_wrmsr_imm(struct kvm_vcpu *vcpu, u32 msr, int reg);
-
 int kvm_emulator_get_msr_with_filter(struct kvm_vcpu *vcpu, u32 msr_index,
 				     u64 *pdata);
 int kvm_emulator_set_msr_with_filter(struct kvm_vcpu *vcpu, u32 msr_index,
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#80 lore raw

PATCH v3 31/40 KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

In reply to Sean Christopherson

Move a pile of MMU helper declarations into mmu.h, as they are very much KVM x86 internal APIs and not intended to be exposed to arch-neutral KVM, and certainly not to the broader kernel.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 70 --------------------------------
 arch/x86/kvm/mmu.h              | 71 +++++++++++++++++++++++++++++++++
 2 files changed, 71 insertions(+), 70 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -70
index 1143140592df..f217403e18fc 100644
@@ -161,12 +161,6 @@
 #define KVM_HPAGE_MASK(x)	(~(KVM_HPAGE_SIZE(x) - 1))
 #define KVM_PAGES_PER_HPAGE(x)	(KVM_HPAGE_SIZE(x) / PAGE_SIZE)
 
-#define KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO 50
-#define KVM_MIN_ALLOC_MMU_PAGES 64UL
-#define KVM_MMU_HASH_SHIFT 12
-#define KVM_NUM_MMU_PAGES (1 << KVM_MMU_HASH_SHIFT)
-#define KVM_MIN_FREE_MMU_PAGES 5
-#define KVM_REFILL_PAGES 25
 #define KVM_MAX_CPUID_ENTRIES 256
 #define KVM_NR_VAR_MTRR 8
 
@@ -2153,38 +2147,6 @@ enum kvm_intr_type {
 	((vcpu) && (vcpu)->arch.handling_intr_from_guest && \
 	 (!!in_nmi() == ((vcpu)->arch.handling_intr_from_guest == KVM_HANDLING_NMI)))
 
-void __init kvm_mmu_x86_module_init(void);
-int kvm_mmu_vendor_module_init(void);
-void kvm_mmu_vendor_module_exit(void);
-
-void kvm_mmu_destroy(struct kvm_vcpu *vcpu);
-int kvm_mmu_create(struct kvm_vcpu *vcpu);
-int kvm_mmu_init_vm(struct kvm *kvm);
-void kvm_mmu_uninit_vm(struct kvm *kvm);
-
-void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
-					    struct kvm_memory_slot *slot);
-
-void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu);
-void kvm_mmu_reset_context(struct kvm_vcpu *vcpu);
-void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
-				      const struct kvm_memory_slot *memslot,
-				      int start_level);
-void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
-				       const struct kvm_memory_slot *memslot,
-				       int target_level);
-void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
-				  const struct kvm_memory_slot *memslot,
-				  u64 start, u64 end,
-				  int target_level);
-void kvm_mmu_recover_huge_pages(struct kvm *kvm,
-				const struct kvm_memory_slot *memslot);
-void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
-				   const struct kvm_memory_slot *memslot);
-void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
-void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
-void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
-
 /*
  * EMULTYPE_NO_DECODE - Set when re-emulating an instruction (after completing
  *			userspace I/O) to indicate that the emulation context
@@ -2334,25 +2296,6 @@ static inline int __kvm_irq_line_state(unsigned long *irq_state,
 void kvm_inject_nmi(struct kvm_vcpu *vcpu);
 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu);
 
-bool __kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
-				       bool always_retry);
-
-static inline bool kvm_mmu_unprotect_gfn_and_retry(struct kvm_vcpu *vcpu,
-						   gpa_t cr2_or_gpa)
-{
-	return __kvm_mmu_unprotect_gfn_and_retry(vcpu, cr2_or_gpa, false);
-}
-
-void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
-			ulong roots_to_free);
-void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu);
-gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
-			      struct x86_exception *exception);
-gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
-			       struct x86_exception *exception);
-gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
-				struct x86_exception *exception);
-
 bool kvm_apicv_activated(struct kvm *kvm);
 bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu);
 void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu);
@@ -2385,19 +2328,6 @@ static inline void kvm_dec_apicv_irq_window_req(struct kvm *kvm)
 	kvm_inc_or_dec_irq_window_inhibit(kvm, false);
 }
 
-int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
-		       void *insn, int insn_len);
-void kvm_mmu_print_sptes(struct kvm_vcpu *vcpu, gpa_t gpa, const char *msg);
-void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva);
-void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
-			     u64 addr, unsigned long roots);
-void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid);
-void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd);
-
-void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
-		       int tdp_max_root_level, int tdp_huge_page_level);
-
-
 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
 #define kvm_arch_has_private_mem(kvm) ((kvm)->arch.has_private_mem)
 #endif
arch/x86/kvm/mmu.h +71 -0

95 lines not on this page · raw message

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#87 lore raw

PATCH v3 32/40 KVM: x86: Move LLDT assembly wrappers into VMX

In reply to Sean Christopherson

Move kvm_{load,read}_ldt() into vmx.c, as they are exclusively used by VMX to save/restore host state, and have no business being globally visible.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 12 ------------
 arch/x86/kvm/vmx/vmx.c          | 12 ++++++++++++
 2 files changed, 12 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -12
index f217403e18fc..3e0884a862d7 100644
@@ -2334,18 +2334,6 @@ static inline void kvm_dec_apicv_irq_window_req(struct kvm *kvm)
 
 #define kvm_arch_has_readonly_mem(kvm) (!(kvm)->arch.has_protected_state)
 
-static inline u16 kvm_read_ldt(void)
-{
-	u16 ldt;
-	asm("sldt %0" : "=g"(ldt));
-	return ldt;
-}
-
-static inline void kvm_load_ldt(u16 sel)
-{
-	asm("lldt %0" : : "rm"(sel));
-}
-
 #ifdef CONFIG_X86_64
 static inline unsigned long read_msr(unsigned long msr)
 {
arch/x86/kvm/vmx/vmx.c +12 -0
index bb19f6df921b..c8ff787d330d 100644
@@ -1186,6 +1186,18 @@ static void vmx_remove_autostore_msr(struct vcpu_vmx *vmx, u32 msr)
 	vmx_remove_auto_msr(&vmx->msr_autostore, msr, VM_EXIT_MSR_STORE_COUNT);
 }
 
+static u16 kvm_read_ldt(void)
+{
+	u16 ldt;
+	asm("sldt %0" : "=g"(ldt));
+	return ldt;
+}
+
+static void kvm_load_ldt(u16 sel)
+{
+	asm("lldt %0" : : "rm"(sel));
+}
+
 #ifdef CONFIG_X86_32
 /*
  * On 32-bit kernels, VM exits still load the FS and GS bases from the
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#91 lore raw

PATCH v3 33/40 KVM: x86: Move kvm_cpu_get_apicid() from kvm_host.h => avic.c

In reply to Sean Christopherson

Opportunistically drop the CONFIG_X86_LOCAL_APIC=n stub, as KVM hard depends on CONFIG_X86_LOCAL_APIC=y (the stub was there purely to deal with kvm_host.h being included by non-KVM code).

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 10 ----------
 arch/x86/kvm/svm/avic.c         |  5 +++++
 2 files changed, 5 insertions(+), 10 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -10
index 3e0884a862d7..989294c7501b 100644
@@ -2427,16 +2427,6 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
 	kvm_x86_call(vcpu_unblocking)(vcpu);
 }
 
-static inline int kvm_cpu_get_apicid(int mps_cpu)
-{
-#ifdef CONFIG_X86_LOCAL_APIC
-	return default_cpu_present_to_apicid(mps_cpu);
-#else
-	WARN_ON_ONCE(1);
-	return BAD_APICID;
-#endif
-}
-
 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages);
 
 #define KVM_CLOCK_VALID_FLAGS						\
arch/x86/kvm/svm/avic.c +5 -0
index b7083cd692ad..9264c8ef1fa1 100644
@@ -146,6 +146,11 @@ static void avic_set_x2apic_msr_interception(struct vcpu_svm *svm,
 	svm->x2avic_msrs_intercepted = intercept;
 }
 
+static int kvm_cpu_get_apicid(int mps_cpu)
+{
+	return default_cpu_present_to_apicid(mps_cpu);
+}
+
 static u32 __avic_get_max_physical_id(struct kvm *kvm, struct kvm_vcpu *vcpu)
 {
 	u32 arch_max;
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#95 lore raw

PATCH v3 34/40 KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c

In reply to Sean Christopherson

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the hardcoded defines are often massaged at runtime, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 34 ---------------------------------
 arch/x86/kvm/x86.c              | 33 ++++++++++++++++++++++++++++++++
 2 files changed, 33 insertions(+), 34 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -34
index 989294c7501b..53994b8292fc 100644
@@ -78,12 +78,6 @@
 #define KVM_DIRTY_LOG_MANUAL_CAPS   (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE | \
 					KVM_DIRTY_LOG_INITIALLY_SET)
 
-#define KVM_BUS_LOCK_DETECTION_VALID_MODE	(KVM_BUS_LOCK_DETECTION_OFF | \
-						 KVM_BUS_LOCK_DETECTION_EXIT)
-
-#define KVM_X86_NOTIFY_VMEXIT_VALID_BITS	(KVM_X86_NOTIFY_VMEXIT_ENABLED | \
-						 KVM_X86_NOTIFY_VMEXIT_USER)
-
 /* x86-specific vcpu->requests bit members */
 #define KVM_REQ_MIGRATE_TIMER		KVM_ARCH_REQ(0)
 #define KVM_REQ_REPORT_TPR_ACCESS	KVM_ARCH_REQ(1)
@@ -2429,34 +2423,6 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
 
 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages);
 
-#define KVM_CLOCK_VALID_FLAGS						\
-	(KVM_CLOCK_TSC_STABLE | KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC)
-
-#define KVM_X86_VALID_QUIRKS			\
-	(KVM_X86_QUIRK_LINT0_REENABLED |	\
-	 KVM_X86_QUIRK_CD_NW_CLEARED |		\
-	 KVM_X86_QUIRK_LAPIC_MMIO_HOLE |	\
-	 KVM_X86_QUIRK_OUT_7E_INC_RIP |		\
-	 KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT |	\
-	 KVM_X86_QUIRK_FIX_HYPERCALL_INSN |	\
-	 KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS |	\
-	 KVM_X86_QUIRK_SLOT_ZAP_ALL |		\
-	 KVM_X86_QUIRK_STUFF_FEATURE_MSRS |	\
-	 KVM_X86_QUIRK_IGNORE_GUEST_PAT |	\
-	 KVM_X86_QUIRK_VMCS12_ALLOW_FREEZE_IN_SMM |	\
-	 KVM_X86_QUIRK_NESTED_SVM_SHARED_PAT)
-
-#define KVM_X86_CONDITIONAL_QUIRKS		\
-	(KVM_X86_QUIRK_CD_NW_CLEARED |		\
-	 KVM_X86_QUIRK_IGNORE_GUEST_PAT)
-
-/*
- * KVM previously used a u32 field in kvm_run to indicate the hypercall was
- * initiated from long mode. KVM now sets bit 0 to indicate long mode, but the
- * remaining 31 lower bits must be 0 to preserve ABI.
- */
-#define KVM_EXIT_HYPERCALL_MBZ		GENMASK_ULL(31, 1)
-
 static inline bool kvm_arch_has_irq_bypass(void)
 {
 	return enable_device_posted_irqs;
arch/x86/kvm/x86.c +33 -0
index 660ba27c76ec..a854b83e9881 100644
@@ -105,6 +105,12 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
 #define emul_to_vcpu(ctxt) \
 	((struct kvm_vcpu *)(ctxt)->vcpu)
 
+/*
+ * KVM previously used a u32 field in kvm_run to indicate the hypercall was
+ * initiated from long mode. KVM now sets bit 0 to indicate long mode, but the
+ * remaining 31 lower bits must be 0 to preserve ABI.
+ */
+#define KVM_EXIT_HYPERCALL_MBZ		GENMASK_ULL(31, 1)
 #define KVM_EXIT_HYPERCALL_VALID_MASK (1 << KVM_HC_MAP_GPA_RANGE)
 
 #define KVM_CAP_PMU_VALID_MASK KVM_PMU_CAP_DISABLE
@@ -114,6 +120,33 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_host);
 				    KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST	| \
 				    KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST)
 
+#define KVM_CLOCK_VALID_FLAGS						\
+	(KVM_CLOCK_TSC_STABLE | KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC)
+
+#define KVM_X86_VALID_QUIRKS			\
+	(KVM_X86_QUIRK_LINT0_REENABLED |	\
+	 KVM_X86_QUIRK_CD_NW_CLEARED |		\
+	 KVM_X86_QUIRK_LAPIC_MMIO_HOLE |	\
+	 KVM_X86_QUIRK_OUT_7E_INC_RIP |		\
+	 KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT |	\
+	 KVM_X86_QUIRK_FIX_HYPERCALL_INSN |	\
+	 KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS |	\
+	 KVM_X86_QUIRK_SLOT_ZAP_ALL |		\
+	 KVM_X86_QUIRK_STUFF_FEATURE_MSRS |	\
+	 KVM_X86_QUIRK_IGNORE_GUEST_PAT |	\
+	 KVM_X86_QUIRK_VMCS12_ALLOW_FREEZE_IN_SMM |	\
+	 KVM_X86_QUIRK_NESTED_SVM_SHARED_PAT)
+
+#define KVM_X86_CONDITIONAL_QUIRKS		\
+	(KVM_X86_QUIRK_CD_NW_CLEARED |		\
+	 KVM_X86_QUIRK_IGNORE_GUEST_PAT)
+
+#define KVM_BUS_LOCK_DETECTION_VALID_MODE	(KVM_BUS_LOCK_DETECTION_OFF | \
+						 KVM_BUS_LOCK_DETECTION_EXIT)
+
+#define KVM_X86_NOTIFY_VMEXIT_VALID_BITS	(KVM_X86_NOTIFY_VMEXIT_ENABLED | \
+						 KVM_X86_NOTIFY_VMEXIT_USER)
+
 static void process_nmi(struct kvm_vcpu *vcpu);
 static void store_regs(struct kvm_vcpu *vcpu);
 static int sync_regs(struct kvm_vcpu *vcpu);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#100 lore raw

PATCH v3 35/40 KVM: x86: Move __kvm_irq_line_state() from kvm_host.h => ioapic.h

In reply to Sean Christopherson

Bury __kvm_irq_line_state() in CONFIG_KVM_IOAPIC=y code, as it's only used by PIC and I/O APIC code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 12 ------------
 arch/x86/kvm/ioapic.h           | 12 ++++++++++++
 2 files changed, 12 insertions(+), 12 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -12
index 53994b8292fc..866d33abaee0 100644
@@ -2275,18 +2275,6 @@ static inline void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 
 bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr);
 
-static inline int __kvm_irq_line_state(unsigned long *irq_state,
-				       int irq_source_id, int level)
-{
-	/* Logical OR for level trig interrupt */
-	if (level)
-		__set_bit(irq_source_id, irq_state);
-	else
-		__clear_bit(irq_source_id, irq_state);
-
-	return !!(*irq_state);
-}
-
 void kvm_inject_nmi(struct kvm_vcpu *vcpu);
 int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu);
 
arch/x86/kvm/ioapic.h +12 -0
index 3dadae093690..81b576513116 100644
@@ -113,6 +113,18 @@ void kvm_get_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state);
 void kvm_set_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state);
 void kvm_ioapic_scan_entry(struct kvm_vcpu *vcpu,
 			   ulong *ioapic_handled_vectors);
+
+static inline int __kvm_irq_line_state(unsigned long *irq_state,
+				       int irq_source_id, int level)
+{
+	/* Logical OR for level trig interrupt */
+	if (level)
+		__set_bit(irq_source_id, irq_state);
+	else
+		__clear_bit(irq_source_id, irq_state);
+
+	return !!(*irq_state);
+}
 #endif /* CONFIG_KVM_IOAPIC */
 
 static inline int ioapic_in_kernel(struct kvm *kvm)
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#103 lore raw

PATCH v3 36/40 KVM: x86: Move IRQ-related helper declarations from kvm_host.h => irq.h

In reply to Sean Christopherson

Move the function declaration for APIs to get/query pending IRQs from kvm_host.h to irq.h, as the APIs are only used by KVM x86 code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 5 -----
 arch/x86/kvm/irq.h              | 6 ++++++
 arch/x86/kvm/svm/nested.c       | 1 +
 arch/x86/kvm/vmx/nested.c       | 1 +
 4 files changed, 8 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -5
index 866d33abaee0..38de6c0dc743 100644
@@ -2360,12 +2360,7 @@ enum {
 # define kvm_memslots_for_spte_role(kvm, role) __kvm_memslots(kvm, 0)
 #endif
 
-int kvm_cpu_has_injectable_intr(struct kvm_vcpu *v);
-int kvm_cpu_has_interrupt(struct kvm_vcpu *vcpu);
-int kvm_cpu_has_extint(struct kvm_vcpu *v);
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);
-int kvm_cpu_get_extint(struct kvm_vcpu *v);
-int kvm_cpu_get_interrupt(struct kvm_vcpu *v);
 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
 
 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
arch/x86/kvm/irq.h +6 -0
index 34f4a78a7a01..1a84ea31e7fd 100644
@@ -112,6 +112,12 @@ static inline int irqchip_in_kernel(struct kvm *kvm)
 	return mode != KVM_IRQCHIP_NONE;
 }
 
+int kvm_cpu_has_injectable_intr(struct kvm_vcpu *v);
+int kvm_cpu_has_interrupt(struct kvm_vcpu *vcpu);
+int kvm_cpu_has_extint(struct kvm_vcpu *v);
+int kvm_cpu_get_extint(struct kvm_vcpu *v);
+int kvm_cpu_get_interrupt(struct kvm_vcpu *v);
+
 void kvm_inject_pending_timer_irqs(struct kvm_vcpu *vcpu);
 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu);
 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu);
arch/x86/kvm/svm/nested.c +1 -0
index 1ab8b95975a4..ef10298cb320 100644
@@ -23,6 +23,7 @@
 
 #include "kvm_emulate.h"
 #include "trace.h"
+#include "irq.h"
 #include "mmu.h"
 #include "x86.h"
 #include "smm.h"
arch/x86/kvm/vmx/nested.c +1 -0
index b2c851cc7d5c..adbb8358ade7 100644
@@ -11,6 +11,7 @@
 #include "x86.h"
 #include "cpuid.h"
 #include "hyperv.h"
+#include "irq.h"
 #include "mmu.h"
 #include "nested.h"
 #include "pmu.h"
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#107 lore raw

PATCH v3 37/40 KVM: x86: Move kvm_pv_send_ipi() declaration from kvm_host.h => lapic.h

In reply to Sean Christopherson

Move the declaration of kvm_pv_send_ipi() into lapic.h, as its implementation is provided by lapic.c (sending PV IPIs relies on the optimized APIC map provided by the in-kernel local APIC), and it's only used by KVM x86 code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 4 ----
 arch/x86/kvm/lapic.h            | 3 +++
 2 files changed, 3 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -4
index 38de6c0dc743..a3c1ff784e5c 100644
@@ -2363,10 +2363,6 @@ enum {
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);
 void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
 
-int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
-		    unsigned long ipi_bitmap_high, u32 min,
-		    unsigned long icr, int op_64_bit);
-
 u64 kvm_scale_tsc(u64 tsc, u64 ratio);
 u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc);
 u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier);
arch/x86/kvm/lapic.h +3 -0
index 32f09b25884a..58dbb94f980d 100644
@@ -131,6 +131,9 @@ static inline int kvm_irq_delivery_to_apic(struct kvm *kvm,
 }
 
 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high);
+int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
+		    unsigned long ipi_bitmap_high, u32 min,
+		    unsigned long icr, int op_64_bit);
 
 int kvm_apic_set_base(struct kvm_vcpu *vcpu, u64 value, bool host_initiated);
 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s);
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#110 lore raw

PATCH v3 38/40 KVM: x86/mmu: Move kvm_arch_async_page_ready() below kvm_tdp_page_fault()

In reply to Sean Christopherson

Move the implementation of kvm_arch_async_page_ready() "down" in mmu.c so that it lives below kvm_tdp_page_fault(). This will allow moving kvm_mmu_do_page_fault() into mmu.c without needing a forward declaration.

No functional change intended.

---
 arch/x86/kvm/mmu/mmu.c | 62 +++++++++++++++++++++---------------------
 1 file changed, 31 insertions(+), 31 deletions(-)
arch/x86/kvm/mmu/mmu.c +31 -31
index e4d971d42f0e..f217e71c3af0 100644
@@ -4571,37 +4571,6 @@ static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu,
 				  kvm_vcpu_gfn_to_hva(vcpu, fault->gfn), &arch);
 }
 
-void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
-{
-	int r;
-
-	if (WARN_ON_ONCE(work->arch.error_code & PFERR_PRIVATE_ACCESS))
-		return;
-
-	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
-	      work->wakeup_all)
-		return;
-
-	r = kvm_mmu_reload(vcpu);
-	if (unlikely(r))
-		return;
-
-	if (!vcpu->arch.mmu->root_role.direct &&
-	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
-		return;
-
-	r = kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, work->arch.error_code,
-				  true, NULL, NULL);
-
-	/*
-	 * Account fixed page faults, otherwise they'll never be counted, but
-	 * ignore stats for all other return times.  Page-ready "faults" aren't
-	 * truly spurious and never trigger emulation
-	 */
-	if (r == RET_PF_FIXED)
-		vcpu->stat.pf_fixed++;
-}
-
 static void kvm_mmu_finish_page_fault(struct kvm_vcpu *vcpu,
 				      struct kvm_page_fault *fault, int r)
 {
@@ -5058,6 +5027,37 @@ long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
 	return min(range->size, end - range->gpa);
 }
 
+void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
+{
+	int r;
+
+	if (WARN_ON_ONCE(work->arch.error_code & PFERR_PRIVATE_ACCESS))
+		return;
+
+	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
+	      work->wakeup_all)
+		return;
+
+	r = kvm_mmu_reload(vcpu);
+	if (unlikely(r))
+		return;
+
+	if (!vcpu->arch.mmu->root_role.direct &&
+	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
+		return;
+
+	r = kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, work->arch.error_code,
+				  true, NULL, NULL);
+
+	/*
+	 * Account fixed page faults, otherwise they'll never be counted, but
+	 * ignore stats for all other return times.  Page-ready "faults" aren't
+	 * truly spurious and never trigger emulation
+	 */
+	if (r == RET_PF_FIXED)
+		vcpu->stat.pf_fixed++;
+}
+
 #ifdef CONFIG_KVM_GUEST_MEMFD
 static void kvm_assert_gmem_invalidate_lock_held(struct kvm_memory_slot *slot)
 {
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#113 lore raw

PATCH v3 39/40 KVM: x86/mmu: Move kvm_mmu_do_page_fault() from mmu_internal.h => mmu.c

In reply to Sean Christopherson

Move kvm_mmu_do_page_fault() into mmu.c, as there are no users outside of mmu.c, and the function typically isn't inlined by the compiler anyways. This will allow moving the EMULTYPE_xxx definitions into x86.h without having to include x86.h in mmu_internal.h, i.e. will help preserve the goal of making x86.h KVM x86's "top-level" include.

No functional change intended.

---
 arch/x86/kvm/mmu/mmu.c          | 67 ++++++++++++++++++++++++++++++++-
 arch/x86/kvm/mmu/mmu_internal.h | 66 --------------------------------
 2 files changed, 66 insertions(+), 67 deletions(-)
arch/x86/kvm/mmu/mmu.c +66 -1
index f217e71c3af0..2796230ec398 100644
@@ -4927,7 +4927,7 @@ static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
 }
 #endif
 
-int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
+static int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 {
 #ifdef CONFIG_X86_64
 	if (tdp_mmu_enabled)
@@ -4937,6 +4937,71 @@ int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 	return direct_page_fault(vcpu, fault);
 }
 
+static int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
+				 u64 err, bool prefetch, int *emulation_type,
+				 u8 *level)
+{
+	struct kvm_page_fault fault = {
+		.addr = cr2_or_gpa,
+		.error_code = err,
+		.exec = err & PFERR_FETCH_MASK,
+		.write = err & PFERR_WRITE_MASK,
+		.present = err & PFERR_PRESENT_MASK,
+		.rsvd = err & PFERR_RSVD_MASK,
+		.user = err & PFERR_USER_MASK,
+		.prefetch = prefetch,
+		.is_tdp = likely(vcpu->arch.mmu->page_fault == kvm_tdp_page_fault),
+		.nx_huge_page_workaround_enabled =
+			is_nx_huge_page_enabled(vcpu->kvm),
+
+		.max_level = KVM_MAX_HUGEPAGE_LEVEL,
+		.req_level = PG_LEVEL_4K,
+		.goal_level = PG_LEVEL_4K,
+		.is_private = err & PFERR_PRIVATE_ACCESS,
+
+		.pfn = KVM_PFN_ERR_FAULT,
+	};
+	int r;
+
+	if (vcpu->arch.mmu->root_role.direct) {
+		/*
+		 * Things like memslots don't understand the concept of a shared
+		 * bit. Strip it so that the GFN can be used like normal, and the
+		 * fault.addr can be used when the shared bit is needed.
+		 */
+		fault.gfn = gpa_to_gfn(fault.addr) & ~kvm_gfn_direct_bits(vcpu->kvm);
+		fault.slot = kvm_vcpu_gfn_to_memslot(vcpu, fault.gfn);
+	}
+
+	/*
+	 * With retpoline being active an indirect call is rather expensive,
+	 * so do a direct call in the most common case.
+	 */
+	if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && fault.is_tdp)
+		r = kvm_tdp_page_fault(vcpu, &fault);
+	else
+		r = vcpu->arch.mmu->page_fault(vcpu, &fault);
+
+	/*
+	 * Not sure what's happening, but punt to userspace and hope that
+	 * they can fix it by changing memory to shared, or they can
+	 * provide a better error.
+	 */
+	if (r == RET_PF_EMULATE && fault.is_private) {
+		pr_warn_ratelimited("kvm: unexpected emulation request on private memory\n");
+		kvm_mmu_prepare_memory_fault_exit(vcpu, &fault);
+		return -EFAULT;
+	}
+
+	if (fault.write_fault_to_shadow_pgtable && emulation_type)
+		*emulation_type |= EMULTYPE_WRITE_PF_TO_SP;
+	if (level)
+		*level = fault.goal_level;
+
+	return r;
+}
+
+
 static int kvm_tdp_page_prefault(struct kvm_vcpu *vcpu, gpa_t gpa,
 				 u64 error_code, u8 *level)
 {
arch/x86/kvm/mmu/mmu_internal.h +0 -66

78 lines not on this page · raw message

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
author maintainer
#116 lore raw

PATCH v3 40/40 KVM: x86: Move a pile of stuff from kvm_host.h => x86.h

In reply to Sean Christopherson

Move the majority of remaining KVM-internal declarations and defines in kvm_host.h to x86.h, so that kvm_host.h only holds structure and function definitions that need to be visible to arch-neutral KVM.

Land the emulator interfaces in x86.h, even though kvm_emulate.h *seems* like a good home, as the interfaces and defines being moved are provided by x86.c. I.e. keep kvm_emulate.h as an interface to the emulator proper.

Note, any "misses" are likely unintentional.

---
 arch/x86/include/asm/kvm_host.h | 197 --------------------------------
 arch/x86/kvm/ioapic.c           |   1 +
 arch/x86/kvm/x86.h              | 195 +++++++++++++++++++++++++++++++
 3 files changed, 196 insertions(+), 197 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -197
index a3c1ff784e5c..4efad65e53e2 100644
@@ -2096,9 +2096,6 @@ extern struct kvm_x86_ops kvm_x86_ops;
 #define KVM_X86_OP_OPTIONAL_RET0 KVM_X86_OP
 #include <asm/kvm-x86-ops.h>
 
-int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops);
-void kvm_x86_vendor_exit(void);
-
 #define __KVM_HAVE_ARCH_VM_ALLOC
 static inline struct kvm *kvm_arch_alloc_vm(void)
 {
@@ -2141,175 +2138,6 @@ enum kvm_intr_type {
 	((vcpu) && (vcpu)->arch.handling_intr_from_guest && \
 	 (!!in_nmi() == ((vcpu)->arch.handling_intr_from_guest == KVM_HANDLING_NMI)))
 
-/*
- * EMULTYPE_NO_DECODE - Set when re-emulating an instruction (after completing
- *			userspace I/O) to indicate that the emulation context
- *			should be reused as is, i.e. skip initialization of
- *			emulation context, instruction fetch and decode.
- *
- * EMULTYPE_TRAP_UD - Set when emulating an intercepted #UD from hardware.
- *		      Indicates that only select instructions (tagged with
- *		      EmulateOnUD) should be emulated (to minimize the emulator
- *		      attack surface).  See also EMULTYPE_TRAP_UD_FORCED.
- *
- * EMULTYPE_SKIP - Set when emulating solely to skip an instruction, i.e. to
- *		   decode the instruction length.  For use *only* by
- *		   kvm_x86_ops.skip_emulated_instruction() implementations if
- *		   EMULTYPE_COMPLETE_USER_EXIT is not set.
- *
- * EMULTYPE_ALLOW_RETRY_PF - Set when the emulator should resume the guest to
- *			     retry native execution under certain conditions,
- *			     Can only be set in conjunction with EMULTYPE_PF.
- *
- * EMULTYPE_TRAP_UD_FORCED - Set when emulating an intercepted #UD that was
- *			     triggered by KVM's magic "force emulation" prefix,
- *			     which is opt in via module param (off by default).
- *			     Bypasses EmulateOnUD restriction despite emulating
- *			     due to an intercepted #UD (see EMULTYPE_TRAP_UD).
- *			     Used to test the full emulator from userspace.
- *
- * EMULTYPE_VMWARE_GP - Set when emulating an intercepted #GP for VMware
- *			backdoor emulation, which is opt in via module param.
- *			VMware backdoor emulation handles select instructions
- *			and reinjects the #GP for all other cases.
- *
- * EMULTYPE_PF - Set when an intercepted #PF triggers the emulation, in which case
- *		 the CR2/GPA value pass on the stack is valid.
- *
- * EMULTYPE_COMPLETE_USER_EXIT - Set when the emulator should update interruptibility
- *				 state and inject single-step #DBs after skipping
- *				 an instruction (after completing userspace I/O).
- *
- * EMULTYPE_WRITE_PF_TO_SP - Set when emulating an intercepted page fault that
- *			     is attempting to write a gfn that contains one or
- *			     more of the PTEs used to translate the write itself,
- *			     and the owning page table is being shadowed by KVM.
- *			     If emulation of the faulting instruction fails and
- *			     this flag is set, KVM will exit to userspace instead
- *			     of retrying emulation as KVM cannot make forward
- *			     progress.
- *
- *			     If emulation fails for a write to guest page tables,
- *			     KVM unprotects (zaps) the shadow page for the target
- *			     gfn and resumes the guest to retry the non-emulatable
- *			     instruction (on hardware).  Unprotecting the gfn
- *			     doesn't allow forward progress for a self-changing
- *			     access because doing so also zaps the translation for
- *			     the gfn, i.e. retrying the instruction will hit a
- *			     !PRESENT fault, which results in a new shadow page
- *			     and sends KVM back to square one.
- *
- * EMULTYPE_SKIP_SOFT_INT - Set in combination with EMULTYPE_SKIP to only skip
- *                          an instruction if it could generate a given software
- *                          interrupt, which must be encoded via
- *                          EMULTYPE_SET_SOFT_INT_VECTOR().
- */
-#define EMULTYPE_NO_DECODE	    (1 << 0)
-#define EMULTYPE_TRAP_UD	    (1 << 1)
-#define EMULTYPE_SKIP		    (1 << 2)
-#define EMULTYPE_ALLOW_RETRY_PF	    (1 << 3)
-#define EMULTYPE_TRAP_UD_FORCED	    (1 << 4)
-#define EMULTYPE_VMWARE_GP	    (1 << 5)
-#define EMULTYPE_PF		    (1 << 6)
-#define EMULTYPE_COMPLETE_USER_EXIT (1 << 7)
-#define EMULTYPE_WRITE_PF_TO_SP	    (1 << 8)
-#define EMULTYPE_SKIP_SOFT_INT	    (1 << 9)
-
-#define EMULTYPE_SET_SOFT_INT_VECTOR(v)	((u32)((v) & 0xff) << 16)
-#define EMULTYPE_GET_SOFT_INT_VECTOR(e)	(((e) >> 16) & 0xff)
-
-static inline bool kvm_can_emulate_event_vectoring(int emul_type)
-{
-	return !(emul_type & EMULTYPE_PF);
-}
-
-int kvm_emulate_instruction(struct kvm_vcpu *vcpu, int emulation_type);
-int kvm_emulate_instruction_from_buffer(struct kvm_vcpu *vcpu,
-					void *insn, int insn_len);
-void __kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu,
-					  u64 *data, u8 ndata);
-void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu);
-
-void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa);
-void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason);
-
-int kvm_emulate_as_nop(struct kvm_vcpu *vcpu);
-int kvm_emulate_invd(struct kvm_vcpu *vcpu);
-int kvm_emulate_mwait(struct kvm_vcpu *vcpu);
-int kvm_handle_invalid_op(struct kvm_vcpu *vcpu);
-int kvm_emulate_monitor(struct kvm_vcpu *vcpu);
-
-int kvm_fast_pio(struct kvm_vcpu *vcpu, int size, unsigned short port, int in);
-int kvm_emulate_cpuid(struct kvm_vcpu *vcpu);
-int kvm_emulate_halt(struct kvm_vcpu *vcpu);
-int kvm_emulate_halt_noskip(struct kvm_vcpu *vcpu);
-int kvm_emulate_ap_reset_hold(struct kvm_vcpu *vcpu);
-int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu);
-
-void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector);
-
-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_rdpmc(struct kvm_vcpu *vcpu);
-
-void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr);
-void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
-void kvm_queue_exception_p(struct kvm_vcpu *vcpu, unsigned nr, unsigned long payload);
-void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
-			   bool has_error_code, u32 error_code);
-void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault,
-			   bool from_hardware);
-void __kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
-				      struct x86_exception *fault,
-				      bool from_hardware);
-
-static inline void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
-						  struct x86_exception *fault)
-{
-	__kvm_inject_emulated_page_fault(vcpu, fault, false);
-}
-
-bool kvm_require_dr(struct kvm_vcpu *vcpu, int dr);
-
-void kvm_inject_nmi(struct kvm_vcpu *vcpu);
-int kvm_get_nr_pending_nmis(struct kvm_vcpu *vcpu);
-
-bool kvm_apicv_activated(struct kvm *kvm);
-bool kvm_vcpu_apicv_activated(struct kvm_vcpu *vcpu);
-void __kvm_vcpu_update_apicv(struct kvm_vcpu *vcpu);
-void __kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
-				      enum kvm_apicv_inhibit reason, bool set);
-void kvm_set_or_clear_apicv_inhibit(struct kvm *kvm,
-				    enum kvm_apicv_inhibit reason, bool set);
-
-static inline void kvm_set_apicv_inhibit(struct kvm *kvm,
-					 enum kvm_apicv_inhibit reason)
-{
-	kvm_set_or_clear_apicv_inhibit(kvm, reason, true);
-}
-
-static inline void kvm_clear_apicv_inhibit(struct kvm *kvm,
-					   enum kvm_apicv_inhibit reason)
-{
-	kvm_set_or_clear_apicv_inhibit(kvm, reason, false);
-}
-
-void kvm_inc_or_dec_irq_window_inhibit(struct kvm *kvm, bool inc);
-
-static inline void kvm_inc_apicv_irq_window_req(struct kvm *kvm)
-{
-	kvm_inc_or_dec_irq_window_inhibit(kvm, true);
-}
-
-static inline void kvm_dec_apicv_irq_window_req(struct kvm *kvm)
-{
-	kvm_inc_or_dec_irq_window_inhibit(kvm, false);
-}
-
 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
 #define kvm_arch_has_private_mem(kvm) ((kvm)->arch.has_private_mem)
 #endif
@@ -2326,11 +2154,6 @@ static inline unsigned long read_msr(unsigned long msr)
 }
 #endif
 
-static inline void kvm_inject_gp(struct kvm_vcpu *vcpu, u32 error_code)
-{
-	kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
-}
-
 #define TSS_IOPB_BASE_OFFSET 0x66
 #define TSS_BASE_SIZE 0x68
 #define TSS_IOPB_SIZE (65536 / 8)
@@ -2361,16 +2184,6 @@ enum {
 #endif
 
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);
-void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
-
-u64 kvm_scale_tsc(u64 tsc, u64 ratio);
-u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc);
-u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multiplier);
-u64 kvm_calc_nested_tsc_multiplier(u64 l1_multiplier, u64 l2_multiplier);
-
-void kvm_make_scan_ioapic_request(struct kvm *kvm);
-void kvm_make_scan_ioapic_request_mask(struct kvm *kvm,
-				       unsigned long *vcpu_bitmap);
 
 bool kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
 				     struct kvm_async_pf *work);
@@ -2382,14 +2195,6 @@ void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu);
 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
 
-int kvm_skip_emulated_instruction(struct kvm_vcpu *vcpu);
-int kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err);
-
-void __user *__x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
-				     u32 size);
-bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu);
-bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu);
-
 static inline void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu)
 {
 	kvm_x86_call(vcpu_blocking)(vcpu);
@@ -2400,8 +2205,6 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
 	kvm_x86_call(vcpu_unblocking)(vcpu);
 }
 
-int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages);
-
 static inline bool kvm_arch_has_irq_bypass(void)
 {
 	return enable_device_posted_irqs;
arch/x86/kvm/ioapic.c +1 -0
index eed96ff6e722..b114f646d798 100644
@@ -33,6 +33,7 @@
 #include "lapic.h"
 #include "irq.h"
 #include "trace.h"
+#include "x86.h"
 
 static int ioapic_service(struct kvm_ioapic *vioapic, int irq,
 		bool line_status);
arch/x86/kvm/x86.h +195 -0

223 lines not on this page · raw message

Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
#5 lore raw

Re: [PATCH v3 04/40] KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode

In reply to Sean Christopherson
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

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

Pre-existing issues:
- [High] Incorrect 32-bit mode segment check emulation in sgx_get_encls_gva violates architectural bounds, alignment, and type rules.
- [High] KVM fails to enforce the architectural requirement that 64-bit pointer fields in memory-based ENCLS structures must have their upper 32 bits set to zero when executing in 32-bit mode. --

commit ca9673f76fcf276ab1d3acd4cb535b328a49e842
Author: Sean Christopherson <[email protected]>

KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode

When getting register values for ENCLS emulation, use kvm_register_read() instead of kvm_<reg>_read() so that bits 63:32 of the register are dropped if the guest is in 32-bit mode.

arch/x86/kvm/vmx/sgx.c static int handle_encls_ecreate(struct kvm_vcpu *vcpu) · line 230

Quoted 13 lines
arch/x86/kvm/vmx/sgx.c +2 -2
index df1d0cf769475..4c61fc33f7648 100644
@@ -225,8 +225,8 @@ static int handle_encls_ecreate(struct kvm_vcpu *vcpu)
 	struct x86_exception ex;
 	int r;
 
-	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 32, 32, &pageinfo_gva) ||
-	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva))
+	if (sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RBX), 32, 32, &pageinfo_gva) ||
+	    sgx_get_encls_gva(vcpu, kvm_register_read(vcpu, VCPU_REGS_RCX), 4096, 4096, &secs_gva))
 		return 1;

[Severity: High]
This isn't a bug introduced by this patch, but while reviewing the 32-bit mode fixes for ENCLS, does the existing 32-bit segment check emulation in sgx_get_encls_gva() violate architectural bounds, alignment, and type rules?

In sgx_get_encls_gva():

	} else {
		*gva &= 0xffffffff;
		fault = (s.unusable) ||
			(s.type != 2 && s.type != 3) ||
			(*gva > s.limit) ||
			((s.base != 0 || s.limit != 0xffffffff) &&
			(((u64)*gva + size - 1) > s.limit + 1));
	}

Is it correct that this calculates the linear address (*gva = offset + s.base) and then evaluates the segment limit against it (*gva > s.limit), rather than checking against the effective address? A non-zero s.base could cause limits to be evaluated incorrectly.

Also, does the check (((u64)*gva + size - 1) > s.limit + 1) allow an access to exceed the inclusive segment limit by 1 byte without faulting?

Finally, by requiring s.type == 2 || s.type == 3 (Read/Write data segments), does this reject valid Read-Only data segments (types 0, 1), even though ENCLS structures being read (like PAGEINFO) only require read access?

[Severity: High]
This is a pre-existing issue, but does KVM fail to enforce the architectural requirement that 64-bit pointer fields in memory-based ENCLS structures must have their upper 32 bits set to zero when executing in 32-bit mode?

According to the Intel SDM for ENCLS, "Any 64-bit pointer field within the data structures must have its upper 32 bits zero in 32-bit mode, or else #GP(0) is generated."

Looking at handle_encls_ecreate(), KVM extracts 64-bit pointers from the guest PAGEINFO structure:

	if (sgx_get_encls_gva(vcpu, pageinfo.metadata, 64, 64, &metadata_gva) ||
	    sgx_get_encls_gva(vcpu, pageinfo.contents, 4096, 4096,
			      &contents_gva))

And passes them to sgx_get_encls_gva(). However, in 32-bit mode, sgx_get_encls_gva() just silently masks the upper 32 bits:

	} else {
		*gva &= 0xffffffff;

Should this instead validate that the upper 32 bits are zero and inject a #GP(0) to prevent invalid guest structures from being successfully processed?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Reviewed-by on v3 13/40
#16 lore raw

Re: [PATCH v3 13/40] KVM: x86: Move update_cr8_intercept() to lapic.c

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson

Move update_cr8_intercept() to lapic.c so that it's globally visible in anticipation of extracting most of the register-specific code out of x86.c and into a new compilation unit. Opportunistically prefix the helper kvm_lapic_ to make its role/scope more obvious.

No functional change intended.

#19 lore raw

Re: [PATCH v3 14/40] KVM: x86: Move async #PF helpers to x86.h (as inlines)

In reply to Sean Christopherson
Quoted 3 lines · Sean Christopherson

Move kvm_pv_async_pf_enabled() and kvm_async_pf_hash_reset() to x86.h in anticipation of extracting the majority of register and MSR specific code out of x86.c.

Not sure how these things are relevant?

author maintainer
#20 lore raw

Re: [PATCH v3 14/40] KVM: x86: Move async #PF helpers to x86.h (as inlines)

In reply to Yosry Ahmed
Quoted 6 lines · Yosry Ahmed
Quoted 3 lines · Sean Christopherson

Move kvm_pv_async_pf_enabled() and kvm_async_pf_hash_reset() to x86.h in anticipation of extracting the majority of register and MSR specific code out of x86.c.

Not sure how these things are relevant?

Oh, I should have explained that. The PV async #PF stuff is controlled via MSR, so kvm_async_pf_hash_reset() will also be called from msrs.c. And there are fun CR0.PG interactions that need to be handled, so kvm_pv_async_pf_enabled() will be called from regs.c.

But they also need to be called from x86.c where the core PV async #PF support lives.

#24 lore raw

Re: [PATCH v3 15/40] KVM: x86: Move the bulk of register specific code from x86.c to regs.c

In reply to Sean Christopherson
Quoted 9 lines · Sean Christopherson

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code (except for EFER, which can hardly be called an MSR), as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

No functional change intended.

This is not just code movement. You're also renaming and introducing new helpers in the process, making the patch not so easy to review.

A wise mine once told me not to do this:
https://lore.kernel.org/kvm/[email protected]/

I have been waiting a few months for this, so here goes:

Stop. Bundling. Things. Together.

Reviewed-by
#21 lore raw

Re: [PATCH v3 14/40] KVM: x86: Move async #PF helpers to x86.h (as inlines)

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson
Quoted 6 lines · Yosry Ahmed
Quoted 3 lines · Sean Christopherson

Move kvm_pv_async_pf_enabled() and kvm_async_pf_hash_reset() to x86.h in anticipation of extracting the majority of register and MSR specific code out of x86.c.

Not sure how these things are relevant?

Quoted 7 lines

Oh, I should have explained that. The PV async #PF stuff is controlled via MSR, so kvm_async_pf_hash_reset() will also be called from msrs.c. And there are fun CR0.PG interactions that need to be handled, so kvm_pv_async_pf_enabled() will be called from regs.c.

But they also need to be called from x86.c where the core PV async #PF support lives.

Makes sense.

With the changelog updated:

Reviewed-by on v3 18/40
#35 lore raw

Re: [PATCH v3 18/40] KVM: x86: Move kvm_caps and kvm_host_values to asm/kvm_host.h

In reply to Sean Christopherson
Quoted 25 lines · Sean Christopherson

Relocate the kvm_caps and kvm_host_values struct definitions and their associated global variable declarations to asm/kvm_host.h to allow for a variety of cleanups in x86.h and mmu.h, and to establish a (hopefully) maintainable rule that asm/kvm_host.h's role is to define common structures (and declare any associated globals), and anything needed by arch-neutral KVM.

While it would be lovely to trim kvm_host.h down to the point where it *only* holds things needed by arch-neutral and/or non-KVM code, multiple attempts to do just that have failed miserably. Trying to "hide" code from arch-neutral KVM is too restrictive (and ultimately pointless), and KVM x86 itself also needs a place to define common structures and their globals, e.g. to avoid inconsistent header include chains and/or misplaced helpers.

E.g. as pointed out by Kai, it's weird that x86.h, which is a kitchen sink of sorts, includes regs.h, but not mmu.h. Literally the only reason that x86.h doesn't include mmu.h is that mmu.h references struct kvm_host, which is currently defined in x86.h. As a result of odd include ordering, the very clearly MMU-specific helper mmu_is_nested() lives in x86.h, not mmu.h

"Fix" the kvm_host dependency so that x86.h can be the "central" include everyone expects it to be, and set KVM x86 on the path to having somewhat sensible "rules" for what goes where:

Quoted 7 lines

- asm/kvm_host.h holds "common" structure definitions and associated key global variables, and things that are referenced by arch-neutral KVM.
- <thing>.{c,h} holds relevant declarations and definitions.
- x86.{c,h} is the kitchen sink for everything else.

#38 lore raw

Re: [PATCH v3 19/40] KVM: x86: Swap the include order between x86.h and mmu.h

In reply to Sean Christopherson
Quoted 2 lines · Sean Christopherson

Invert the include ordering between x86.h and mmu.h, so that x86.h is the "top-level" include for KVM x86.

You're also silently moving mmu_is_nested().

Aside from that, I thought top-level include means that other headers will include it, and it will include fewer headers. Seems like this is doing the opposite?

Quoted 60 lines

No functional change intended.

---
 arch/x86/kvm/mmu.h | 6 +++++-
 arch/x86/kvm/x86.h | 6 +-----
 2 files changed, 6 insertions(+), 6 deletions(-)
arch/x86/kvm/mmu.h +5 -1
index e1bb663ebbd5..28fca48dcf64 100644
@@ -4,7 +4,6 @@
 
 #include <linux/kvm_host.h>
 #include "regs.h"
-#include "x86.h"
 #include "cpuid.h"
 
 extern bool __read_mostly enable_mmio_caching;
@@ -300,6 +299,11 @@ static inline void kvm_update_page_stats(struct kvm *kvm, int level, int count)
 	atomic64_add(count, &kvm->stat.pages[level - 1]);
 }
 
+static inline bool mmu_is_nested(struct kvm_vcpu *vcpu)
+{
+	return vcpu->arch.walk_mmu == &vcpu->arch.nested_mmu;
+}
+
 static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 				      struct kvm_mmu *mmu,
 				      gpa_t gpa, u64 access,
arch/x86/kvm/x86.h +1 -5
index b7d3b54cde15..a0e68eaf1f80 100644
@@ -6,6 +6,7 @@
 #include <asm/fpu/xstate.h>
 #include <asm/mce.h>
 #include <asm/pvclock.h>
+#include "mmu.h"
 #include "regs.h"
 #include "kvm_emulate.h"
 #include "cpuid.h"
@@ -210,11 +211,6 @@ static inline bool x86_exception_has_error_code(unsigned int vector)
 	return (1U << vector) & exception_has_error_code;
 }
 
-static inline bool mmu_is_nested(struct kvm_vcpu *vcpu)
-{
-	return vcpu->arch.walk_mmu == &vcpu->arch.nested_mmu;
-}
-
 static inline u8 vcpu_virt_addr_bits(struct kvm_vcpu *vcpu)
 {
 	return kvm_is_cr4_bit_set(vcpu, X86_CR4_LA57) ? 57 : 48;
Signature · 1 line
2.54.0.823.g6e5bcc1fc9-goog
Reviewed-by on v3 23/40
#52 lore raw

Re: [PATCH v3 23/40] KVM: x86: Move kvm_{load,put}_guest_fpu() to fpu.h

In reply to Sean Christopherson
Quoted 6 lines · Sean Christopherson

Move the kvm_{load,put}_guest_fpu() helpers to fpu.h in anticipation of moving the bulk of KVM's register specific code out of x86.c.

No functional change intended.

Quoted 10 lines
---
 arch/x86/kvm/fpu.h | 26 ++++++++++++++++++++++++++
 arch/x86/kvm/x86.c | 24 ------------------------
 2 files changed, 26 insertions(+), 24 deletions(-)
arch/x86/kvm/fpu.h +0 -0
index f898781b6a06..6b7b628f530d 100644

arch/x86/kvm/fpu.h line 12

Quoted 10 lines
arch/x86/kvm/fpu.h +5 -0
@@ -3,8 +3,34 @@
 #ifndef __KVM_FPU_H_
 #define __KVM_FPU_H_
 
+#include <linux/kvm_host.h>
+
+#include <trace/events/kvm.h>
+
 #include <asm/fpu/api.h>
 
+/* Swap (qemu) user FPU context for the guest FPU context. */

I didn't know KVM was allowed to break the fourth wall like this?

Quoted 9 lines
arch/x86/kvm/fpu.h +9 -0
+static inline void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
+	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
+	trace_kvm_fpu(1);
+}
Reviewed-by on v3 24/40
#56 lore raw

Re: [PATCH v3 24/40] KVM: x86: Extract get/set MSR (list) ioctl logic to helpers

In reply to Sean Christopherson
Quoted 6 lines · Sean Christopherson

Extract the code for getting/setting MSRs and MSR lists to dedicated helpers in anticipation of moving the MSR code to a new msrs.c.

No functional change intended.

This is nice. Aside from the spring cleaning, it makes parsing the return values easier for KVM_GET_MSR_INDEX_LIST and KVM_GET_MSRS.

#63 lore raw

Re: [PATCH v3 27/40] KVM: x86: Move register helper declarations from kvm_host.h => regs.h

In reply to Sean Christopherson
Quoted 16 lines · Sean Christopherson

Relocate declarations of Control/Debug Register, EFLAGS and RIP helpers from x86's kvm_host.h to regs.h, to continue trimming down kvm_host.h.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 17 -----------------
 arch/x86/kvm/regs.h             | 17 +++++++++++++++++
 2 files changed, 17 insertions(+), 17 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 19091d89d3cc..0f4b16b26a27 100644

arch/x86/include/asm/kvm_host.h void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen); · line 2189

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +0 -1
@@ -2186,8 +2186,6 @@ void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
 
-int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);

Why are pdptrs helpers bundled with register helpers?

#75 lore raw

Re: [PATCH v3 30/40] KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h

In reply to Sean Christopherson
Quoted 27 lines · Sean Christopherson

Relocate declarations of MSR helpers (and kvm_nr_uret_msrs) from x86's x86's kvm_host.h to msrs, to continue trimming down kvm_host.h.

Deliberately leave the funky read_msr() where it is, as it will hopefully be removed entirely as part of a broader kernel-API cleanup.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 26 -------------------------
 arch/x86/kvm/msrs.h             | 34 ++++++++++++++++++++++++++++++---
 2 files changed, 31 insertions(+), 29 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -1
index a861c0d70be0..1143140592df 100644
@@ -2094,7 +2094,6 @@ struct kvm_arch_async_pf {
 	u64 error_code;
 };
 
-extern u32 __read_mostly kvm_nr_uret_msrs;
 extern bool __read_mostly allow_smaller_maxphyaddr;
 extern bool __read_mostly enable_apicv;
 extern bool __read_mostly enable_ipiv;

arch/x86/include/asm/kvm_host.h void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu); · line 2282

Quoted 5 lines
arch/x86/include/asm/kvm_host.h +0 -2
@@ -2278,18 +2277,6 @@ void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu);
 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa);
 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason);
 
-void kvm_enable_efer_bits(u64);
-bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer);

Patch 15's changelog makes me thing EFER will belong to regs.[hc] not msrs.[hc]. Did you change your mind?

Reviewed-by on v3 31/40
#81 lore raw

Re: [PATCH v3 31/40] KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson

Move a pile of MMU helper declarations into mmu.h, as they are very much KVM x86 internal APIs and not intended to be exposed to arch-neutral KVM, and certainly not to the broader kernel.

No functional change intended.

#88 lore raw

Re: [PATCH v3 32/40] KVM: x86: Move LLDT assembly wrappers into VMX

In reply to Sean Christopherson
Quoted 2 lines · Sean Christopherson

Move kvm_{load,read}_ldt() into vmx.c, as they are exclusively used by VMX to save/restore host state, and have no business being globally visible.

But they are generic helpers. I agree with mvoing them out of kvm_host.h, but maybe into another header? They don't fit in regs.h or msrs.h, so maybe x86.h? *ducks*

Reviewed-by on v3 33/40
#92 lore raw

Re: [PATCH v3 33/40] KVM: x86: Move kvm_cpu_get_apicid() from kvm_host.h => avic.c

In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson

Opportunistically drop the CONFIG_X86_LOCAL_APIC=n stub, as KVM hard depends on CONFIG_X86_LOCAL_APIC=y (the stub was there purely to deal with kvm_host.h being included by non-KVM code).

No functional change intended.

Reviewed-by on v3 34/40
#96 lore raw

Re: [PATCH v3 34/40] KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c

In reply to Sean Christopherson
Quoted 9 lines · Sean Christopherson

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the hardcoded defines are often massaged at runtime, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

No functional change intended.

Reviewed-by on v3 36/40
#104 lore raw

Re: [PATCH v3 36/40] KVM: x86: Move IRQ-related helper declarations from kvm_host.h => irq.h

In reply to Sean Christopherson
Quoted 18 lines · Sean Christopherson

Move the function declaration for APIs to get/query pending IRQs from kvm_host.h to irq.h, as the APIs are only used by KVM x86 code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 5 -----
 arch/x86/kvm/irq.h              | 6 ++++++
 arch/x86/kvm/svm/nested.c       | 1 +
 arch/x86/kvm/vmx/nested.c       | 1 +
 4 files changed, 8 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 866d33abaee0..38de6c0dc743 100644

arch/x86/include/asm/kvm_host.h enum { · line 2363

Quoted 7 lines
arch/x86/include/asm/kvm_host.h +0 -3
@@ -2360,12 +2360,7 @@ enum {
 # define kvm_memslots_for_spte_role(kvm, role) __kvm_memslots(kvm, 0)
 #endif
 
-int kvm_cpu_has_injectable_intr(struct kvm_vcpu *v);
-int kvm_cpu_has_interrupt(struct kvm_vcpu *vcpu);
-int kvm_cpu_has_extint(struct kvm_vcpu *v);
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);

kvm_arch_interrupt_allowed() is only used in x86.c. Probably it wasn't used outside of x86 code after a1b37100d9e29c1f8dc3e2f5490a205c80180e01.

It should probably be renamed and moved, maybe separately.

Anyway:

Reviewed-by on v3 37/40
#108 lore raw

Re: [PATCH v3 37/40] KVM: x86: Move kvm_pv_send_ipi() declaration from kvm_host.h => lapic.h

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson

Move the declaration of kvm_pv_send_ipi() into lapic.h, as its implementation is provided by lapic.c (sending PV IPIs relies on the optimized APIC map provided by the in-kernel local APIC), and it's only used by KVM x86 code.

No functional change intended.

Reviewed-by on v3 38/40
#111 lore raw

Re: [PATCH v3 38/40] KVM: x86/mmu: Move kvm_arch_async_page_ready() below kvm_tdp_page_fault()

In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson

Move the implementation of kvm_arch_async_page_ready() "down" in mmu.c so that it lives below kvm_tdp_page_fault(). This will allow moving kvm_mmu_do_page_fault() into mmu.c without needing a forward declaration.

No functional change intended.

Reviewed-by on v3 39/40
#114 lore raw

Re: [PATCH v3 39/40] KVM: x86/mmu: Move kvm_mmu_do_page_fault() from mmu_internal.h => mmu.c

In reply to Sean Christopherson
Quoted 9 lines · Sean Christopherson

Move kvm_mmu_do_page_fault() into mmu.c, as there are no users outside of mmu.c, and the function typically isn't inlined by the compiler anyways. This will allow moving the EMULTYPE_xxx definitions into x86.h without having to include x86.h in mmu_internal.h, i.e. will help preserve the goal of making x86.h KVM x86's "top-level" include.

No functional change intended.

[..]

arch/x86/kvm/mmu/mmu.c int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault) · line 4989

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+	/*
+	 * Not sure what's happening, but punt to userspace and hope that
+	 * they can fix it by changing memory to shared, or they can
+	 * provide a better error.
+	 */

LOL

Quoted 13 lines
arch/x86/kvm/mmu/mmu.c +13 -0
+	if (r == RET_PF_EMULATE && fault.is_private) {
+		pr_warn_ratelimited("kvm: unexpected emulation request on private memory\n");
+		kvm_mmu_prepare_memory_fault_exit(vcpu, &fault);
+		return -EFAULT;
+	}
+
+	if (fault.write_fault_to_shadow_pgtable && emulation_type)
+		*emulation_type |= EMULTYPE_WRITE_PF_TO_SP;
+	if (level)
+		*level = fault.goal_level;
+
+	return r;
+}
#117 lore raw

Re: [PATCH v3 40/40] KVM: x86: Move a pile of stuff from kvm_host.h => x86.h

In reply to Sean Christopherson
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Several x86 KVM-internal declarations and definitions were unintentionally left in `kvm_host.h`…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Several x86 KVM-internal declarations and definitions were unintentionally left in kvm_host.h despite the commit's goal to move them to x86.h. --

commit 6fbb37590b9a07586090f255933e9452d592518d
Author: Sean Christopherson <[email protected]>

KVM: x86: Move a pile of stuff from kvm_host.h => x86.h

Move the majority of remaining KVM-internal declarations and defines in kvm_host.h to x86.h, so that kvm_host.h only holds structure and function definitions that need to be visible to arch-neutral KVM.

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +0 -0
index a3c1ff784e5c0..4efad65e53e24 100644

[ ... ]

arch/x86/include/asm/kvm_host.h static inline unsigned long read_msr(unsigned long msr) · line 2159

Quoted 12 lines
arch/x86/include/asm/kvm_host.h +0 -5
@@ -2326,11 +2154,6 @@ static inline unsigned long read_msr(unsigned long msr)
 }
 #endif
 
-static inline void kvm_inject_gp(struct kvm_vcpu *vcpu, u32 error_code)
-{
-	kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
-}
-
 #define TSS_IOPB_BASE_OFFSET 0x66
 #define TSS_BASE_SIZE 0x68
 #define TSS_IOPB_SIZE (65536 / 8)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: Medium]
The commit message notes that any "misses" are likely unintentional. Should TSS_IOPB_BASE_OFFSET and related constants also be moved to x86.h?

There are a few other x86-specific definitions still left in this file that might have been missed, such as struct kvm_host_values (earlier in the file).

arch/x86/include/asm/kvm_host.h enum { · line 2186

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +0 -0
@@ -2361,16 +2184,6 @@ enum {
 #endif
 
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: Medium]
Similarly, should kvm_arch_interrupt_allowed() and the preceding enum containing TASK_SWITCH_CALL also be moved to x86.h?

Quoted 2 lines
arch/x86/include/asm/kvm_host.h +0 -2
-void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
-

[ ... ]

arch/x86/include/asm/kvm_host.h void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu); · line 2196

Quoted 3 lines
arch/x86/include/asm/kvm_host.h +0 -0
@@ -2382,14 +2195,6 @@ void kvm_arch_async_page_present_queued(struct kvm_vcpu *vcpu);
 bool kvm_arch_can_dequeue_async_page_present(struct kvm_vcpu *vcpu);
 extern bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: Medium]
Are kvm_find_async_pf_gfn() and the other async page fault prototypes missed here as well?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=40
maintainer
#118 lore raw
In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson

The first half of this series adds proper, explicit "raw" versions of kvm_<reg>_{read,write}(), along with "e" versions (for hardcoded 32-bit accesses), and converts the existing kvm_<reg>_{read,write}() APIs into mode-aware variants.

At the end of that journey, introduce regs.{c,h} to avoid moving _more_ code into x86.h, especially since the resulting code split would be super arbitrary.

What about getting everything up to patch 14 into 7.2, and then starting 7.3 development with these, the MMU split series, and possibly the pfncache cleanups?

I'll be away starting June 28th, so we probably want to get those three merged into kvm/next already towards the end of the merge window.

Paolo

Quoted 131 lines

The second half of the series runs with the regs.{c,h} changes and performs spring cleaning on x86.{c,h} and asm/kvm_host.h (in case it wasn't already obvious, I have poor impulse control when it comes to cleaning up code).

I'm most intersted in getting feedback on the file names (regs.{c,h} and msrs.{c,h}. I'm quite confident the actual code split is the way to go, and pulling stuff out of asm/kvm_host.h has been on my wish/todo list for years.

I'll grab these fixes for 7.2 no matter what:

KVM: x86: Trace hypercall register *after* truncating values for 32-bit
KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode
KVM: x86/xen: Don't truncate RAX when handling hypercall from protected guest
KVM: x86/xen: Bug the VM if 32-bit KVM observes a 64-bit mode hypercall

Depending on how people feel about the names and cleanups, I'll either send the big cleanups as a separate pull request after the initial for-7.2 pull requests (if there's overwhelming consensus on the names/splits), or wait for 7.3 (if more discussion is needed).

v3:
- Collect more tags. [David, Binbin, Yosry]
- Use kvm_run_sync_regs_{from,to}_user() instead of kvm_run_{g,s}et_regs().

    [Kai]

- Fix a variety of typos. [Binbin]
- Everything beyond patch 15...

v2:
- https://lore.kernel.org/all/[email protected]
- Collect tags. [Yosry, Kai]
- Fix some truly egregious goofs. [Binbin]
- Rename kvm_cache_regs.h => regs.h, add regs.c. [Yosry, because he complained, not because he actually suggested this :-D ]
- Drop superfluous casting/masking of e*x() usage. [Kai]

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

Sean Christopherson (40):
KVM: SVM: Truncate INVLPGA address in compatibility mode
KVM: x86/xen: Bug the VM if 32-bit KVM observes a 64-bit mode
hypercall
KVM: x86/xen: Don't truncate RAX when handling hypercall from
protected guest
KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of

     64-bit mode
   KVM: x86: Trace hypercall register *after* truncating values for
     32-bit

KVM: x86: Rename kvm_cache_regs.h => regs.h
KVM: x86: Move inlined GPR, CR, and DR helpers from x86.h to regs.h
KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers
KVM: x86: Drop non-raw kvm_<reg>_write() helpers
KVM: nSVM: Use kvm_rax_read() now that it's mode-aware Revert "KVM: VMX: Read 32-bit GPR values for ENCLS instructions
outside of 64-bit mode"
KVM: x86: Harden is_64_bit_hypercall() against bugs on 32-bit kernels
KVM: x86: Move update_cr8_intercept() to lapic.c
KVM: x86: Move async #PF helpers to x86.h (as inlines)
KVM: x86: Move the bulk of register specific code from x86.c to regs.c
KVM: x86: Move local APIC specific helpers out of asm/kvm_host.h
KVM: x86: Drop defunct vcpu_tsc_khz() declaration
KVM: x86: Move kvm_caps and kvm_host_values to asm/kvm_host.h
KVM: x86: Swap the include order between x86.h and mmu.h
KVM: x86: Move tdp_enabled from kvm_host.h to mmu.h
KVM: x86: Move eager_page_split to mmu.{c,h}
KVM: x86/hyperv: Eliminate an unnecessary include of x86.h in hyperv.h
KVM: x86: Move kvm_{load,put}_guest_fpu() to fpu.h
KVM: x86: Extract get/set MSR (list) ioctl logic to helpers
KVM: x86: Expose several TSC helpers via x86.h for use by MSR code
KVM: x86: Move the bulk of MSR specific code from x86.c to msrs.{c,h}
KVM: x86: Move register helper declarations from kvm_host.h => regs.h
KVM: x86: Move kvm_{g,s}et_segment() to inline helpers in regs.h
KVM: x86: Remove defunct kvm_load_segment_descriptor() declaration.
KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h
KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h
KVM: x86: Move LLDT assembly wrappers into VMX
KVM: x86: Move kvm_cpu_get_apicid() from kvm_host.h => avic.c
KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c
KVM: x86: Move __kvm_irq_line_state() from kvm_host.h => ioapic.h
KVM: x86: Move IRQ-related helper declarations from kvm_host.h =>
irq.h
KVM: x86: Move kvm_pv_send_ipi() declaration from kvm_host.h =>
lapic.h
KVM: x86/mmu: Move kvm_arch_async_page_ready() below
kvm_tdp_page_fault()
KVM: x86/mmu: Move kvm_mmu_do_page_fault() from mmu_internal.h =>
mmu.c
KVM: x86: Move a pile of stuff from kvm_host.h => x86.h

  arch/x86/include/asm/kvm_host.h           |  452 +--
  arch/x86/kvm/Makefile                     |    4 +-
  arch/x86/kvm/cpuid.c                      |   13 +-
  arch/x86/kvm/emulate.c                    |    2 +-
  arch/x86/kvm/fpu.h                        |   26 +
  arch/x86/kvm/hyperv.c                     |   21 +-
  arch/x86/kvm/hyperv.h                     |    7 +-
  arch/x86/kvm/ioapic.c                     |    1 +
  arch/x86/kvm/ioapic.h                     |   12 +
  arch/x86/kvm/irq.c                        |    7 +
  arch/x86/kvm/irq.h                        |    6 +
  arch/x86/kvm/lapic.c                      |   28 +-
  arch/x86/kvm/lapic.h                      |    9 +
  arch/x86/kvm/mmu.h                        |   92 +-
  arch/x86/kvm/mmu/mmu.c                    |  134 +-
  arch/x86/kvm/mmu/mmu_internal.h           |   66 -
  arch/x86/kvm/msrs.c                       | 2732 +++++++++++++++
  arch/x86/kvm/msrs.h                       |  156 +
  arch/x86/kvm/mtrr.c                       |    1 +
  arch/x86/kvm/regs.c                       |  875 +++++
  arch/x86/kvm/{kvm_cache_regs.h => regs.h} |  258 +-
  arch/x86/kvm/smm.c                        |    2 +-
  arch/x86/kvm/svm/avic.c                   |    5 +
  arch/x86/kvm/svm/nested.c                 |    9 +-
  arch/x86/kvm/svm/svm.c                    |   19 +-
  arch/x86/kvm/svm/svm.h                    |    2 +-
  arch/x86/kvm/vmx/nested.c                 |    9 +-
  arch/x86/kvm/vmx/nested.h                 |    2 +-
  arch/x86/kvm/vmx/sgx.c                    |    6 +-
  arch/x86/kvm/vmx/tdx.c                    |   18 +-
  arch/x86/kvm/vmx/vmx.c                    |   14 +-
  arch/x86/kvm/vmx/vmx.h                    |    2 +-
  arch/x86/kvm/x86.c                        | 3789 +--------------------
  arch/x86/kvm/x86.h                        |  480 ++-
  arch/x86/kvm/xen.c                        |   39 +-
  35 files changed, 4722 insertions(+), 4576 deletions(-)

create mode 100644 arch/x86/kvm/msrs.c
create mode 100644 arch/x86/kvm/msrs.h
create mode 100644 arch/x86/kvm/regs.c
rename arch/x86/kvm/{kvm_cache_regs.h => regs.h} (50%)

base-commit: d1568b1332b6b3b36b222c2868fc102727c12a34

author maintainer
#25 lore raw

Re: [PATCH v3 15/40] KVM: x86: Move the bulk of register specific code from x86.c to regs.c

In reply to Yosry Ahmed
Quoted 14 lines · Yosry Ahmed
Quoted 9 lines · Sean Christopherson

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code (except for EFER, which can hardly be called an MSR), as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

No functional change intended.

This is not just code movement. You're also renaming and introducing new helpers in the process, making the patch not so easy to review.

Quoted 6 lines

A wise mine once told me not to do this:
https://lore.kernel.org/kvm/[email protected]/

I have been waiting a few months for this, so here goes:

Stop. Bundling. Things. Together.

Gooood. Use your aggressive feelings, boy. Let the hate flow through you!

author maintainer
#64 lore raw

Re: [PATCH v3 27/40] KVM: x86: Move register helper declarations from kvm_host.h => regs.h

In reply to Yosry Ahmed
Quoted 20 lines · Yosry Ahmed
Quoted 19 lines · Sean Christopherson

Relocate declarations of Control/Debug Register, EFLAGS and RIP helpers from x86's kvm_host.h to regs.h, to continue trimming down kvm_host.h.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 17 -----------------
 arch/x86/kvm/regs.h             | 17 +++++++++++++++++
 2 files changed, 17 insertions(+), 17 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 19091d89d3cc..0f4b16b26a27 100644
@@ -2186,8 +2186,6 @@ void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
 
Quoted 3 lines

arch/x86/include/asm/kvm_host.h void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen); · line 2189

Quoted 1 line
arch/x86/include/asm/kvm_host.h +0 -1
-int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);

Why are pdptrs helpers bundled with register helpers?

Page Directory Pointer Table Registers

                             ^^^^^^^^^

Or as the SDM initially describes them, "5.4.1 PDPTE Registers". When using PAE paging (not 64-bit paging), they really are CPU registers, and their lifecycle is tied to CR{0,3,4}. I.e. I was thinking of them as an extension of Control Registers. I can explicitly call that out in the changelog?

author maintainer
#76 lore raw

Re: [PATCH v3 30/40] KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h

In reply to Yosry Ahmed
Quoted 31 lines · Yosry Ahmed
Quoted 30 lines · Sean Christopherson

Relocate declarations of MSR helpers (and kvm_nr_uret_msrs) from x86's x86's kvm_host.h to msrs, to continue trimming down kvm_host.h.

Deliberately leave the funky read_msr() where it is, as it will hopefully be removed entirely as part of a broader kernel-API cleanup.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 26 -------------------------
 arch/x86/kvm/msrs.h             | 34 ++++++++++++++++++++++++++++++---
 2 files changed, 31 insertions(+), 29 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -1
index a861c0d70be0..1143140592df 100644
@@ -2094,7 +2094,6 @@ struct kvm_arch_async_pf {
 	u64 error_code;
 };
 
-extern u32 __read_mostly kvm_nr_uret_msrs;
 extern bool __read_mostly allow_smaller_maxphyaddr;
 extern bool __read_mostly enable_apicv;
 extern bool __read_mostly enable_ipiv;
@@ -2278,18 +2277,6 @@ void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu);
 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa);
 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason);
 
Quoted 5 lines

arch/x86/include/asm/kvm_host.h void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu); · line 2282

Quoted 2 lines
arch/x86/include/asm/kvm_host.h +0 -2
-void kvm_enable_efer_bits(u64);
-bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer);

Patch 15's changelog makes me thing EFER will belong to regs.[hc] not msrs.[hc]. Did you change your mind?

Not really, patch 15's changelog was always "bad", even in the previous version, before msrs.{c,h} was added. The bulk of EFER handling was left behind in x86.c, only the {G,S}ET_SREGS accessor/mutator logic gets moved.

I updated patch 07's changelog between v2 and v3 to better reflect reality:

Move *very* select EFER functionality as well, but leave behind the bulk of EFER handling and all other MSR handling.

But I missed patch 15. For patch 15, how about this?

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code, as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

Note, "struct kvm_sregs" has fields for EFER and MSR_IA32_APICBASE, and so the {G,S}ET_REGS flows technically contain a tiny amount of MSR code. MSR_IA32_APICBASE is already managed by lapic.c, and so doesn't require a "placement decision". As for EFER, leave all other EFER handling in x86.c (later to be moved to msrs.c), as the primary interface to EFER, set_efer(), is very much MSR specific, even though EFER is arguably more of a Control Register than an MSR.

No functional change intended.

author maintainer
#39 lore raw

Re: [PATCH v3 19/40] KVM: x86: Swap the include order between x86.h and mmu.h

In reply to Yosry Ahmed
Quoted 5 lines · Yosry Ahmed
Quoted 2 lines · Sean Christopherson

Invert the include ordering between x86.h and mmu.h, so that x86.h is the "top-level" include for KVM x86.

You're also silently moving mmu_is_nested().

I'll explicitly call that out.

Quoted 3 lines

Aside from that, I thought top-level include means that other headers will include it, and it will include fewer headers. Seems like this is doing the opposite?

Yeah, I'm probably using confusing terminology. I could quite figure out how to concisely describe this. I like my pyramid visualation, so about:

Invert the include ordering between x86.h and mmu.h, and move mmu_is_nested() to mmu.h where it belongs (mmu_is_nested()'s placement in x86.h was solely responsible for the existing ordering), so that x86.h is the top of KVM x86's "include pyramid".

author maintainer
#89 lore raw

Re: [PATCH v3 32/40] KVM: x86: Move LLDT assembly wrappers into VMX

In reply to Yosry Ahmed
Quoted 6 lines · Yosry Ahmed
Quoted 2 lines · Sean Christopherson

Move kvm_{load,read}_ldt() into vmx.c, as they are exclusively used by VMX to save/restore host state, and have no business being globally visible.

But they are generic helpers. I agree with mvoing them out of kvm_host.h, but maybe into another header?

No, absolutely not. The fact that KVM has to manually save, and conditionally restore, LDT is a quirk of the VMX architecture. If it weren't for the fact that VMX's segment_base() also needs to query the LDT, I would just open code the asm().

If it's a naming concern, I'll happily rename them to vmx_{load,store}_ldt().

Hmm, arch/x86/include/asm/desc.h provides {load,store}_ldt(), but load_ldt() is only available for CONFIG_PARAVIRT_XXL=n builds, and both #define unnecessarily constrain the output to memory. Those are both fixable, e.g. load_ldt() isn't used _anywhere_ AFAICT, so burying it under CONFIG_PARAVIRT_XXL=n is just some weird historical quirk, and I can't show_fault_oops() would care store_ldt() were allowed to store to a register.

So after the dust settles, it probably makes sense to improve desc.h's versions and then use those in KVM. But I don't want to do that in this series, because it will be challenging enough to land all of this code movement without also having to coordinate with the tip tree.

author maintainer
#105 lore raw

Re: [PATCH v3 36/40] KVM: x86: Move IRQ-related helper declarations from kvm_host.h => irq.h

In reply to Yosry Ahmed
Quoted 22 lines · Yosry Ahmed
Quoted 21 lines · Sean Christopherson

Move the function declaration for APIs to get/query pending IRQs from kvm_host.h to irq.h, as the APIs are only used by KVM x86 code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 5 -----
 arch/x86/kvm/irq.h              | 6 ++++++
 arch/x86/kvm/svm/nested.c       | 1 +
 arch/x86/kvm/vmx/nested.c       | 1 +
 4 files changed, 8 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 866d33abaee0..38de6c0dc743 100644
@@ -2360,12 +2360,7 @@ enum {
 # define kvm_memslots_for_spte_role(kvm, role) __kvm_memslots(kvm, 0)
 #endif
 
Quoted 7 lines

arch/x86/include/asm/kvm_host.h enum { · line 2363

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +0 -3
-int kvm_cpu_has_injectable_intr(struct kvm_vcpu *v);
-int kvm_cpu_has_interrupt(struct kvm_vcpu *vcpu);
-int kvm_cpu_has_extint(struct kvm_vcpu *v);
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);

kvm_arch_interrupt_allowed() is only used in x86.c. Probably it wasn't used outside of x86 code after a1b37100d9e29c1f8dc3e2f5490a205c80180e01.

Oof, and it has x86-specific semantics (KVM x86 very much relies on 0/1/-EBUSY return values).

Quoted 1 line

It should probably be renamed and moved, maybe separately.

Yeah, I'll slot in a patch to bury it in x86.c as kvm_is_interrupt_allowed().

#40 lore raw

Re: [PATCH v3 19/40] KVM: x86: Swap the include order between x86.h and mmu.h

In reply to Sean Christopherson
Quoted 13 lines · Sean Christopherson
Quoted 5 lines · Yosry Ahmed
Quoted 2 lines · Sean Christopherson

Invert the include ordering between x86.h and mmu.h, so that x86.h is the "top-level" include for KVM x86.

You're also silently moving mmu_is_nested().

I'll explicitly call that out.

Quoted 3 lines

Aside from that, I thought top-level include means that other headers will include it, and it will include fewer headers. Seems like this is doing the opposite?

Quoted 7 lines

Yeah, I'm probably using confusing terminology. I could quite figure out how to concisely describe this. I like my pyramid visualation, so about:

Invert the include ordering between x86.h and mmu.h, and move mmu_is_nested() to mmu.h where it belongs (mmu_is_nested()'s placement in x86.h was solely responsible for the existing ordering), so that x86.h is the top of KVM x86's "include pyramid".

Not to be pedantic, but I still can't quite figure out this analogy/visualization.

How about just spelling it out:

so that x86.h is not included by most headers (but includes them).

author maintainer
#41 lore raw

Re: [PATCH v3 19/40] KVM: x86: Swap the include order between x86.h and mmu.h

Quoted 22 lines · Yosry Ahmed
Quoted 13 lines · Sean Christopherson
Quoted 5 lines · Yosry Ahmed
Quoted 2 lines · Sean Christopherson

Invert the include ordering between x86.h and mmu.h, so that x86.h is the "top-level" include for KVM x86.

You're also silently moving mmu_is_nested().

I'll explicitly call that out.

Quoted 3 lines

Aside from that, I thought top-level include means that other headers will include it, and it will include fewer headers. Seems like this is doing the opposite?

Quoted 7 lines

Yeah, I'm probably using confusing terminology. I could quite figure out how to concisely describe this. I like my pyramid visualation, so about:

Invert the include ordering between x86.h and mmu.h, and move mmu_is_nested() to mmu.h where it belongs (mmu_is_nested()'s placement in x86.h was solely responsible for the existing ordering), so that x86.h is the top of KVM x86's "include pyramid".

Quoted 6 lines

Not to be pedantic, but I still can't quite figure out this analogy/visualization.

How about just spelling it out:

so that x86.h is not included by most headers (but includes them).

Works for me.

#26 lore raw

Re: [PATCH v3 15/40] KVM: x86: Move the bulk of register specific code from x86.c to regs.c

In reply to Sean Christopherson
Quoted 15 lines · Sean Christopherson
Quoted 14 lines · Yosry Ahmed
Quoted 9 lines · Sean Christopherson

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code (except for EFER, which can hardly be called an MSR), as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

No functional change intended.

This is not just code movement. You're also renaming and introducing new helpers in the process, making the patch not so easy to review.

Quoted 8 lines
Quoted 6 lines

A wise mine once told me not to do this:
https://lore.kernel.org/kvm/[email protected]/

I have been waiting a few months for this, so here goes:

Stop. Bundling. Things. Together.

Gooood. Use your aggressive feelings, boy. Let the hate flow through you!

I guess I did turn to the dark side after all.

#65 lore raw

Re: [PATCH v3 27/40] KVM: x86: Move register helper declarations from kvm_host.h => regs.h

In reply to Sean Christopherson
Quoted 21 lines · Sean Christopherson
Quoted 20 lines · Yosry Ahmed
Quoted 19 lines · Sean Christopherson

Relocate declarations of Control/Debug Register, EFLAGS and RIP helpers from x86's kvm_host.h to regs.h, to continue trimming down kvm_host.h.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 17 -----------------
 arch/x86/kvm/regs.h             | 17 +++++++++++++++++
 2 files changed, 17 insertions(+), 17 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 19091d89d3cc..0f4b16b26a27 100644
@@ -2186,8 +2186,6 @@ void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
 
Quoted 6 lines
Quoted 3 lines

arch/x86/include/asm/kvm_host.h void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen); · line 2189

Quoted 1 line
arch/x86/include/asm/kvm_host.h +0 -1
-int load_pdptrs(struct kvm_vcpu *vcpu, unsigned long cr3);

Why are pdptrs helpers bundled with register helpers?

Page Directory Pointer Table Registers

                             ^^^^^^^^^

LOL I assumed PDPTR is just Page Directory Pointer (i.e. PTR is pointer). Never mind then.

Quoted 5 lines

Or as the SDM initially describes them, "5.4.1 PDPTE Registers". When using PAE paging (not 64-bit paging), they really are CPU registers, and their lifecycle is tied to CR{0,3,4}. I.e. I was thinking of them as an extension of Control Registers. I can explicitly call that out in the changelog?

I don't think that's needed, it was just me being uneducated.

#77 lore raw

Re: [PATCH v3 30/40] KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h

In reply to Sean Christopherson
Quoted 42 lines · Sean Christopherson
Quoted 31 lines · Yosry Ahmed
Quoted 30 lines · Sean Christopherson

Relocate declarations of MSR helpers (and kvm_nr_uret_msrs) from x86's x86's kvm_host.h to msrs, to continue trimming down kvm_host.h.

Deliberately leave the funky read_msr() where it is, as it will hopefully be removed entirely as part of a broader kernel-API cleanup.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 26 -------------------------
 arch/x86/kvm/msrs.h             | 34 ++++++++++++++++++++++++++++++---
 2 files changed, 31 insertions(+), 29 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -1
index a861c0d70be0..1143140592df 100644
@@ -2094,7 +2094,6 @@ struct kvm_arch_async_pf {
 	u64 error_code;
 };
 
-extern u32 __read_mostly kvm_nr_uret_msrs;
 extern bool __read_mostly allow_smaller_maxphyaddr;
 extern bool __read_mostly enable_apicv;
 extern bool __read_mostly enable_ipiv;
@@ -2278,18 +2277,6 @@ void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu);
 void kvm_prepare_event_vectoring_exit(struct kvm_vcpu *vcpu, gpa_t gpa);
 void kvm_prepare_unexpected_reason_exit(struct kvm_vcpu *vcpu, u64 exit_reason);
 
Quoted 5 lines

arch/x86/include/asm/kvm_host.h void kvm_prepare_emulation_failure_exit(struct kvm_vcpu *vcpu); · line 2282

Quoted 2 lines
arch/x86/include/asm/kvm_host.h +0 -2
-void kvm_enable_efer_bits(u64);
-bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer);

Patch 15's changelog makes me thing EFER will belong to regs.[hc] not msrs.[hc]. Did you change your mind?

Not really, patch 15's changelog was always "bad", even in the previous version, before msrs.{c,h} was added. The bulk of EFER handling was left behind in x86.c, only the {G,S}ET_SREGS accessor/mutator logic gets moved.

Quoted 6 lines

I updated patch 07's changelog between v2 and v3 to better reflect reality:

Move *very* select EFER functionality as well, but leave behind the bulk of EFER handling and all other MSR handling.

But I missed patch 15. For patch 15, how about this?

LGTM.

Quoted 15 lines

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code, as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

Note, "struct kvm_sregs" has fields for EFER and MSR_IA32_APICBASE, and so the {G,S}ET_REGS flows technically contain a tiny amount of MSR code. MSR_IA32_APICBASE is already managed by lapic.c, and so doesn't require a "placement decision". As for EFER, leave all other EFER handling in x86.c (later to be moved to msrs.c), as the primary interface to EFER, set_efer(), is very much MSR specific, even though EFER is arguably more of a Control Register than an MSR.

No functional change intended.

#90 lore raw

Re: [PATCH v3 32/40] KVM: x86: Move LLDT assembly wrappers into VMX

In reply to Sean Christopherson
Quoted 5 lines · Sean Christopherson
Quoted 4 lines · Yosry Ahmed
Quoted 2 lines · Sean Christopherson

Move kvm_{load,read}_ldt() into vmx.c, as they are exclusively used by VMX to save/restore host state, and have no business being globally visible.

Quoted 8 lines
Quoted 2 lines

But they are generic helpers. I agree with mvoing them out of kvm_host.h, but maybe into another header?

No, absolutely not. The fact that KVM has to manually save, and conditionally restore, LDT is a quirk of the VMX architecture. If it weren't for the fact that VMX's segment_base() also needs to query the LDT, I would just open code the asm().

If it's a naming concern, I'll happily rename them to vmx_{load,store}_ldt().

I was actually going to suggest those exact names initially, so yeah this looks better.

Quoted 8 lines

Hmm, arch/x86/include/asm/desc.h provides {load,store}_ldt(), but load_ldt() is only available for CONFIG_PARAVIRT_XXL=n builds, and both #define unnecessarily constrain the output to memory. Those are both fixable, e.g. load_ldt() isn't used _anywhere_ AFAICT, so burying it under CONFIG_PARAVIRT_XXL=n is just some weird historical quirk, and I can't show_fault_oops() would care store_ldt() were allowed to store to a register.

Quoted 4 lines

So after the dust settles, it probably makes sense to improve desc.h's versions and then use those in KVM. But I don't want to do that in this series, because it will be challenging enough to land all of this code movement without also having to coordinate with the tip tree.

Even better, makes sense for a separate cleanup. Thanks.

#106 lore raw

Re: [PATCH v3 36/40] KVM: x86: Move IRQ-related helper declarations from kvm_host.h => irq.h

In reply to Sean Christopherson
Quoted 31 lines · Sean Christopherson
Quoted 22 lines · Yosry Ahmed
Quoted 21 lines · Sean Christopherson

Move the function declaration for APIs to get/query pending IRQs from kvm_host.h to irq.h, as the APIs are only used by KVM x86 code.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 5 -----
 arch/x86/kvm/irq.h              | 6 ++++++
 arch/x86/kvm/svm/nested.c       | 1 +
 arch/x86/kvm/vmx/nested.c       | 1 +
 4 files changed, 8 insertions(+), 5 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 866d33abaee0..38de6c0dc743 100644
@@ -2360,12 +2360,7 @@ enum {
 # define kvm_memslots_for_spte_role(kvm, role) __kvm_memslots(kvm, 0)
 #endif
 
Quoted 7 lines

arch/x86/include/asm/kvm_host.h enum { · line 2363

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +0 -3
-int kvm_cpu_has_injectable_intr(struct kvm_vcpu *v);
-int kvm_cpu_has_interrupt(struct kvm_vcpu *vcpu);
-int kvm_cpu_has_extint(struct kvm_vcpu *v);
 int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu);

kvm_arch_interrupt_allowed() is only used in x86.c. Probably it wasn't used outside of x86 code after a1b37100d9e29c1f8dc3e2f5490a205c80180e01.

Quoted 6 lines

Oof, and it has x86-specific semantics (KVM x86 very much relies on 0/1/-EBUSY return values).

Quoted 1 line

It should probably be renamed and moved, maybe separately.

Yeah, I'll slot in a patch to bury it in x86.c as kvm_is_interrupt_allowed().

Thank you!

Reviewed-by on v3 8/40
#10 lore raw

Re: [PATCH v3 08/40] KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson

Make kvm_<reg>_{read,write}() mode-aware (where the value is truncated to 32 bits if the vCPU isn't in 64-bit mode), and convert all the intentional "raw" accesses to kvm_<reg>_{read,write}_raw() versions. To avoid confusion and bikeshedding over whether or not explicit 32-bit accesses should use the "raw" or mode-aware variants, add and use "e" versions, e.g. for things like RDMSR, WRMSR, and CPUID, where the instruction uses only bits 31:0, regardless of mode.

Quoted 8 lines

No functional change intended (all use of "e" versions is for cases where the value is already truncated due to bouncing through a u32).

Reviewed-by on v3 13/40
#17 lore raw

Re: [PATCH v3 13/40] KVM: x86: Move update_cr8_intercept() to lapic.c

In reply to Sean Christopherson
Quoted 9 lines · Sean Christopherson

Move update_cr8_intercept() to lapic.c so that it's globally visible in anticipation of extracting most of the register-specific code out of x86.c and into a new compilation unit. Opportunistically prefix the helper kvm_lapic_ to make its role/scope more obvious.

No functional change intended.

Reviewed-by on v3 14/40
#22 lore raw

Re: [PATCH v3 14/40] KVM: x86: Move async #PF helpers to x86.h (as inlines)

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson

Move kvm_pv_async_pf_enabled() and kvm_async_pf_hash_reset() to x86.h in anticipation of extracting the majority of register and MSR specific code out of x86.c.

No functional change intended.

Reviewed-by on v3 15/40
#27 lore raw

Re: [PATCH v3 15/40] KVM: x86: Move the bulk of register specific code from x86.c to regs.c

In reply to Sean Christopherson
Quoted 10 lines · Sean Christopherson

Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code (except for EFER, which can hardly be called an MSR), as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.

No functional change intended.

arch/x86/kvm/x86.c static void store_regs(struct kvm_vcpu *vcpu) · line 11883

Quoted 3 lines
arch/x86/kvm/x86.c +0 -0
@@ -12691,11 +11882,7 @@ static void store_regs(struct kvm_vcpu *vcpu)
 {
 	BUILD_BUG_ON(sizeof(struct kvm_sync_regs) > SYNC_REGS_SIZE_BYTES);

This BUILD_BUG_ON() can be removed too since the new kvm_run_sync_regs_to_user() already has it.

Reviewed-by on v3 18/40
#36 lore raw

Re: [PATCH v3 18/40] KVM: x86: Move kvm_caps and kvm_host_values to asm/kvm_host.h

In reply to Sean Christopherson
Quoted 15 lines · Sean Christopherson

Relocate the kvm_caps and kvm_host_values struct definitions and their associated global variable declarations to asm/kvm_host.h to allow for a variety of cleanups in x86.h and mmu.h, and to establish a (hopefully) maintainable rule that asm/kvm_host.h's role is to define common structures (and declare any associated globals), and anything needed by arch-neutral KVM.

While it would be lovely to trim kvm_host.h down to the point where it *only* holds things needed by arch-neutral and/or non-KVM code, multiple attempts to do just that have failed miserably. Trying to "hide" code from arch-neutral KVM is too restrictive (and ultimately pointless), and KVM x86 itself also needs a place to define common structures and their globals, e.g. to avoid inconsistent header include chains and/or misplaced helpers.

Quoted 3 lines

E.g. as pointed out by Kai, it's weird that x86.h, which is a kitchen sink of sorts, includes regs.h, but not mmu.h. Literally the only reason that x86.h doesn't include mmu.h is that mmu.h references struct kvm_host, which

							      ^

Nit: it's 'struct kvm_host_values' but not 'struct kvm_host'.

Quoted 9 lines

is currently defined in x86.h. As a result of odd include ordering, the very clearly MMU-specific helper mmu_is_nested() lives in x86.h, not mmu.h

"Fix" the kvm_host dependency so that x86.h can be the "central" include everyone expects it to be, and set KVM x86 on the path to having somewhat sensible "rules" for what goes where:

- asm/kvm_host.h holds "common" structure definitions and associated key global variables, and things that are referenced by arch-neutral KVM.

	    ^

Nit: double whitespace.

Quoted 6 lines

- <thing>.{c,h} holds relevant declarations and definitions.
- x86.{c,h} is the kitchen sink for everything else.

author maintainer
#119 lore raw
In reply to Paolo Bonzini
Quoted 6 lines · Paolo Bonzini
Quoted 5 lines · Sean Christopherson

The first half of this series adds proper, explicit "raw" versions of kvm_<reg>_{read,write}(), along with "e" versions (for hardcoded 32-bit accesses), and converts the existing kvm_<reg>_{read,write}() APIs into mode-aware variants.

Quoted 6 lines
Quoted 2 lines

At the end of that journey, introduce regs.{c,h} to avoid moving _more_ code into x86.h, especially since the resulting code split would be super arbitrary.

What about getting everything up to patch 14 into 7.2, and then starting 7.3 development with these, the MMU split series, and possibly the pfncache cleanups?

I like that idea. I'll grab these two as well, no reason not to.

KVM: x86: Remove defunct kvm_load_segment_descriptor() declaration
KVM: x86: Drop defunct vcpu_tsc_khz() declaration

Quoted 2 lines

I'll be away starting June 28th, so we probably want to get those three merged into kvm/next already towards the end of the merge window.

Reviewed-by on v3 22/40
#50 lore raw

Re: [PATCH v3 22/40] KVM: x86/hyperv: Eliminate an unnecessary include of x86.h in hyperv.h

In reply to Sean Christopherson
Quoted 10 lines · Sean Christopherson

Drop an mostly unused include of x86.h from hyperv.h, and instead pull in regs.h, which is need for at least is_guest_mode(). This eliminates the last include of x86.h from a common x86 header, i.e. solidifies that x86.h is the top of the pyramid.

Add a missing x86.h include in cpuid.c to avoid build breakage.

No functional change intended.

Quoted 10 lines
---
 arch/x86/kvm/cpuid.c  | 1 +
 arch/x86/kvm/hyperv.h | 3 ++-
 2 files changed, 3 insertions(+), 1 deletion(-)
arch/x86/kvm/cpuid.c +0 -0
index fd3b02575cd0..db8be9173bd0 100644

arch/x86/kvm/cpuid.c line 31

Quoted 4 lines
arch/x86/kvm/cpuid.c +1 -0
@@ -28,6 +28,7 @@
 #include "trace.h"
 #include "pmu.h"
 #include "xen.h"
+#include "x86.h"

FWIW:

This made me think whether we should just add "x86.h" inclusion in patch

KVM: x86: Swap the include order between x86.h and mmu.h

.. due to the fact that cpuid.c includes "mmu.h" but not "x86.h" directly, and that patch removed "x86.h" inclusion in "mmu.h".

But that patch doesn't break the build (I also tried at my side), because cpuid.c also includes "lapic.h", which includes "hyperv.h", which includes "x86.h".

So cpuid.c actually has "x86.h" included indirectly, until this patch.

From this perspective, it makes sense to make cpuid.c explicitly include "x86.h" in this patch.

A side thing:

I also spotted that cpuid.c uses "double quote" way to include linux/lockdep.h:

#include "linux/lockdep.h"

After couple of minutes thinking why, I concluded we should just use

#include <linux/lockdep.h>

For that I sent a patch to fix, assuming I am not missing anything.

Reviewed-by on v3 23/40
#53 lore raw

Re: [PATCH v3 23/40] KVM: x86: Move kvm_{load,put}_guest_fpu() to fpu.h

In reply to Sean Christopherson
Quoted 6 lines · Sean Christopherson

Move the kvm_{load,put}_guest_fpu() helpers to fpu.h in anticipation of moving the bulk of KVM's register specific code out of x86.c.

No functional change intended.

Quoted 31 lines
---
 arch/x86/kvm/fpu.h | 26 ++++++++++++++++++++++++++
 arch/x86/kvm/x86.c | 24 ------------------------
 2 files changed, 26 insertions(+), 24 deletions(-)
arch/x86/kvm/fpu.h +16 -0
index f898781b6a06..6b7b628f530d 100644
@@ -3,8 +3,34 @@
 #ifndef __KVM_FPU_H_
 #define __KVM_FPU_H_
 
+#include <linux/kvm_host.h>
+
+#include <trace/events/kvm.h>
+
 #include <asm/fpu/api.h>
 
+/* Swap (qemu) user FPU context for the guest FPU context. */
+static inline void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
+	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
+	trace_kvm_fpu(1);
+}
+
+/* When vcpu_run ends, restore user space FPU context. */

arch/x86/kvm/fpu.h line 33

Quoted 10 lines
arch/x86/kvm/fpu.h +10 -0
+static inline void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
+	++vcpu->stat.fpu_reload;
+	trace_kvm_fpu(0);
+}
+

Nit: to me it's a little bit weird to put the two functions before the typedefs and macro defines below, though.

Quoted 3 lines
arch/x86/kvm/fpu.h +0 -0
 typedef u32		__attribute__((vector_size(16))) sse128_t;
 #define __sse128_u	union { sse128_t vec; u64 as_u64[2]; u32 as_u32[4]; }
 #define sse128_lo(x)	({ __sse128_u t; t.vec = x; t.as_u64[0]; })
Reviewed-by on v3 24/40
#57 lore raw

Re: [PATCH v3 24/40] KVM: x86: Extract get/set MSR (list) ioctl logic to helpers

In reply to Sean Christopherson
Quoted 6 lines · Sean Christopherson

Extract the code for getting/setting MSRs and MSR lists to dedicated helpers in anticipation of moving the MSR code to a new msrs.c.

No functional change intended.

Quoted 20 lines
---
 arch/x86/kvm/x86.c | 135 ++++++++++++++++++++++++++-------------------
 1 file changed, 78 insertions(+), 57 deletions(-)
arch/x86/kvm/x86.c +8 -0
index 56ccb6b77abb..64c3680d889b 100644
@@ -4602,6 +4602,61 @@ static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr)
 	return __kvm_x86_dev_get_attr(attr, &val);
 }
 
+static int kvm_get_msr_index_list(struct kvm_msr_list __user *user_msr_list)
+{
+	struct kvm_msr_list msr_list;
+	unsigned int n;
+
+	if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
+		return -EFAULT;
+

arch/x86/kvm/x86.c static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr) · line 4622

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+	n = msr_list.nmsrs;
+	msr_list.nmsrs = num_msrs_to_save + num_emulated_msrs;
+	if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
+		return -EFAULT;
+
+	if (n < msr_list.nmsrs)
+		return -E2BIG;
+
+	if (copy_to_user(user_msr_list->indices, &msrs_to_save,
+				num_msrs_to_save * sizeof(u32)))

Nit: apparent misaligned function call argument.

Quoted 17 lines
arch/x86/kvm/x86.c +17 -0
+		return -EFAULT;
+
+	if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
+			 &emulated_msrs, num_emulated_msrs * sizeof(u32)))
+		return -EFAULT;
+
+	return 0;
+}
+
+static int kvm_get_feature_msr_index_list(struct kvm_msr_list __user *user_msr_list)
+{
+	struct kvm_msr_list msr_list;
+	unsigned int n;
+
+	if (copy_from_user(&msr_list, user_msr_list, sizeof(msr_list)))
+		return -EFAULT;
+

arch/x86/kvm/x86.c static int kvm_x86_dev_has_attr(struct kvm_device_attr *attr) · line 4649

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+	n = msr_list.nmsrs;
+	msr_list.nmsrs = num_msr_based_features;
+	if (copy_to_user(user_msr_list, &msr_list, sizeof(msr_list)))
+		return -EFAULT;
+
+	if (n < msr_list.nmsrs)
+		return -E2BIG;
+
+	if (copy_to_user(user_msr_list->indices, &msr_based_features,
+				num_msr_based_features * sizeof(u32)))

Ditto.

Reviewed-by on v3 25/40
#59 lore raw

Re: [PATCH v3 25/40] KVM: x86: Expose several TSC helpers via x86.h for use by MSR code

In reply to Sean Christopherson
Quoted 5 lines · Sean Christopherson

Begrudgingly move adjust_tsc_offset_{guest,host}() to x86.h as inlines, and expose several other TSC helpers in anticipation of moving KVM's MSR code to a dedicated msrs.c. Unfortunately for KVM, several MSRs that KVM emulates can affect TSC state.

Quoted 7 lines

Opportunistically drop a superfluous local "tsc_offset" variable, whose existence causes checkpatch to complain about lack of a blank line.

No functional change intended.

Reviewed-by on v3 26/40
#61 lore raw

Re: [PATCH v3 26/40] KVM: x86: Move the bulk of MSR specific code from x86.c to msrs.{c,h}

In reply to Sean Christopherson
Quoted 8 lines · Sean Christopherson

Introduce msrs.{c,h}, and move the vast majority of MSR specific code out of x86.{c,h}. Use a plural "msrs" instead of just "msr" to be consistent with regs.{c,h}, and to make it easier to differentiate KVM's code from the other 5+ msr.c files in the kernel.

No functional change intended.

Tried best to review, seems fine:

[...]

Quoted 8 lines
arch/x86/kvm/msrs.h new file +8 -0
+static inline bool kvm_is_valid_u_s_cet(struct kvm_vcpu *vcpu, u64 data)
+{
+	if (data & CET_US_RESERVED_BITS)
+		return false;
+	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK) &&
+	    (data & CET_US_SHSTK_MASK_BITS))
+		return false;
+	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_IBT) &&

arch/x86/kvm/msrs.h line 126

Quoted 10 lines
arch/x86/kvm/msrs.h new file +10 -0
+	    (data & CET_US_IBT_MASK_BITS))
+		return false;
+	if (!IS_ALIGNED(CET_US_LEGACY_BITMAP_BASE(data), 4))
+		return false;
+	/* IBT can be suppressed iff the TRACKER isn't WAIT_ENDBR. */
+	if ((data & CET_SUPPRESS) && (data & CET_WAIT_ENDBR))
+		return false;
+
+	return true;
+}

Nit: AFAICT the purpose of this being in msrs.h is it is also used by vmx/nested.c. Not sure whether you want to explicitly include "msrs.h" in vmx/nested.c

Review

Quoted 3 lines
(quoted diff) +2 -0
+
+#endif
\ No newline at end of file

No newline at end of file

arch/x86/kvm/mtrr.c line 23

Quoted 10 lines
arch/x86/kvm/mtrr.c +1 -0
index 6f74e2b27c1e..4f3b7b0f6565 100644
@@ -19,6 +19,7 @@
 #include <asm/mtrr.h>
 
 #include "cpuid.h"
+#include "msrs.h"
 #include "x86.h"

Seems "x86.h" is not needed anymore.

[...]

arch/x86/kvm/mtrr.c

Quoted 4 lines
arch/x86/kvm/mtrr.c +0 -1
 static DEFINE_MUTEX(vendor_module_lock);
-
 struct kvm_x86_ops kvm_x86_ops __read_mostly;

Nit of nit: seems unintended change.

Reviewed-by on v3 27/40
#66 lore raw

Re: [PATCH v3 27/40] KVM: x86: Move register helper declarations from kvm_host.h => regs.h

In reply to Sean Christopherson
Quoted 6 lines · Sean Christopherson

Relocate declarations of Control/Debug Register, EFLAGS and RIP helpers from x86's kvm_host.h to regs.h, to continue trimming down kvm_host.h.

No functional change intended.

Quoted 3 lines

void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
+void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);

:-)

Seems a candidate of making kvm_set_rflags() a 'static inline' ?

Reviewed-by on v3 30/40
#78 lore raw

Re: [PATCH v3 30/40] KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h

In reply to Sean Christopherson
Quoted 2 lines · Sean Christopherson

Relocate declarations of MSR helpers (and kvm_nr_uret_msrs) from x86's x86's kvm_host.h to msrs, to continue trimming down kvm_host.h.

Double x86's

Quoted 7 lines

Deliberately leave the funky read_msr() where it is, as it will hopefully be removed entirely as part of a broader kernel-API cleanup.

No functional change intended.

Btw, not sure whether you like:

We can also move the body of 'struct msr_bitmap_range' and 'struct kvm_x86_msr_filter' to "msrs.h" too, if we put one

struct kvm_x86_msr_filter;

to <asm/kvm_host.h> before 'struct kvm_arch'.

The below diff passed build at my side:

arch/x86/include/asm/kvm_host.h +2 -13
index 1143140592df..f87b839fd3a4 100644
@@ -1291,13 +1291,6 @@ struct kvm_hv {
 };
 #endif
 
-struct msr_bitmap_range {
-       u32 flags;
-       u32 nmsrs;
-       u32 base;
-       unsigned long *bitmap;
-};
-
 #ifdef CONFIG_KVM_XEN
 /* Xen emulation context */
 struct kvm_xen {
@@ -1328,12 +1321,6 @@ enum kvm_suppress_eoi_broadcast_mode {
        KVM_SUPPRESS_EOI_BROADCAST_DISABLED /* Disable Suppress EOI broadcast */
 };
 
-struct kvm_x86_msr_filter {
-       u8 count;
-       bool default_allow:1;
-       struct msr_bitmap_range ranges[16];
-};
-
 struct kvm_x86_pmu_event_filter {
        __u32 action;
        __u32 nevents;
@@ -1478,6 +1465,8 @@ enum kvm_mmu_type {
        KVM_NR_MMU_TYPES,
 };
 
+struct kvm_x86_msr_filter;
+
 struct kvm_arch {
        unsigned long n_used_mmu_pages;
        unsigned long n_requested_mmu_pages;
arch/x86/kvm/msrs.h +13 -0
index 5c8362a8fd97..7a690a515947 100644
@@ -13,6 +13,19 @@ extern bool ignore_msrs;
 
 extern u32 __read_mostly kvm_nr_uret_msrs;
 
+struct msr_bitmap_range {
+       u32 flags;
+       u32 nmsrs;
+       u32 base;
+       unsigned long *bitmap;
+};
+
+struct kvm_x86_msr_filter {
+       u8 count;
+       bool default_allow:1;
+       struct msr_bitmap_range ranges[16];
+};
+
 static inline void kvm_pr_unimpl_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64

data)
{
if (report_ignored_msrs)
@@ -153,4 +166,4 @@ static inline bool kvm_is_valid_u_s_cet(struct kvm_vcpu *vcpu, u64 data)

        return true;

}

-#endif
\ No newline at end of file
+#endif

Reviewed-by on v3 31/40
#82 lore raw

Re: [PATCH v3 31/40] KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson

Move a pile of MMU helper declarations into mmu.h, as they are very much KVM x86 internal APIs and not intended to be exposed to arch-neutral KVM, and certainly not to the broader kernel.

No functional change intended.

#93 lore raw

Re: [PATCH v3 33/40] KVM: x86: Move kvm_cpu_get_apicid() from kvm_host.h => avic.c

In reply to Sean Christopherson
Quoted 3 lines · Sean Christopherson

Opportunistically drop the CONFIG_X86_LOCAL_APIC=n stub, as KVM hard depends on CONFIG_X86_LOCAL_APIC=y (the stub was there purely to deal with kvm_host.h being included by non-KVM code).

Seems you forgot to mention the code movement part?

Quoted 35 lines

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h | 10 ----------
 arch/x86/kvm/svm/avic.c         |  5 +++++
 2 files changed, 5 insertions(+), 10 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -10
index 3e0884a862d7..989294c7501b 100644
@@ -2427,16 +2427,6 @@ static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu)
 	kvm_x86_call(vcpu_unblocking)(vcpu);
 }
 
-static inline int kvm_cpu_get_apicid(int mps_cpu)
-{
-#ifdef CONFIG_X86_LOCAL_APIC
-	return default_cpu_present_to_apicid(mps_cpu);
-#else
-	WARN_ON_ONCE(1);
-	return BAD_APICID;
-#endif
-}
-
 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages);
 
 #define KVM_CLOCK_VALID_FLAGS						\
arch/x86/kvm/svm/avic.c +0 -0
index b7083cd692ad..9264c8ef1fa1 100644

arch/x86/kvm/svm/avic.c static void avic_set_x2apic_msr_interception(struct vcpu_svm *svm, · line 154

Quoted 9 lines
arch/x86/kvm/svm/avic.c +5 -0
@@ -146,6 +146,11 @@ static void avic_set_x2apic_msr_interception(struct vcpu_svm *svm,
 	svm->x2avic_msrs_intercepted = intercept;
 }
 
+static int kvm_cpu_get_apicid(int mps_cpu)
+{
+	return default_cpu_present_to_apicid(mps_cpu);
+}
+
 

Looks it is only used by AMD (svm/avic.c). I don't know why, but it would be nice if you can mention this in changelog, since this function seems pretty common to both Intel and AMD.

That being said, since you are moving it to svm/avic.c (not lapic.h), and it's just a wrapper of calling default_cpu_present_to_apicid(). Should we just remove this and make avic.c call default_cpu_present_to_apicid() directly?

Reviewed-by on v3 34/40
#97 lore raw

Re: [PATCH v3 34/40] KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c

In reply to Sean Christopherson
Quoted 5 lines · Sean Christopherson

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the hardcoded defines are often massaged at runtime, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

I am bit confused about what do you mean by "hardcoded defines are ofen massaged at runtime". Do you mean the supported flags can be changed at runtime via ioctl? But if we are talking about ioctl, then the flags must be part of uABI, which shouldn't change?

Quoted 5 lines

No functional change intended.

Anyway:

#83 lore raw

Re: [PATCH v3 31/40] KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

In reply to Sean Christopherson
Quoted 16 lines
arch/x86/include/asm/kvm_host.h +0 -6
index 1143140592df..f217403e18fc 100644
@@ -161,12 +161,6 @@
 #define KVM_HPAGE_MASK(x)	(~(KVM_HPAGE_SIZE(x) - 1))
 #define KVM_PAGES_PER_HPAGE(x)	(KVM_HPAGE_SIZE(x) / PAGE_SIZE)
 
-#define KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO 50
-#define KVM_MIN_ALLOC_MMU_PAGES 64UL
-#define KVM_MMU_HASH_SHIFT 12
-#define KVM_NUM_MMU_PAGES (1 << KVM_MMU_HASH_SHIFT)
-#define KVM_MIN_FREE_MMU_PAGES 5
-#define KVM_REFILL_PAGES 25 
 

[...]

Quoted 5 lines
arch/x86/kvm/mmu.h +0 -0
index d30676935fff..a6b871253bd7 100644

arch/x86/kvm/mmu.h extern bool tdp_mmu_enabled; · line 24

Quoted 10 lines
arch/x86/kvm/mmu.h +7 -0
@@ -15,6 +15,13 @@ extern bool tdp_mmu_enabled;
 extern bool __read_mostly enable_mmio_caching;
 extern bool eager_page_split;
 
+#define KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO 50
+#define KVM_MIN_ALLOC_MMU_PAGES 64UL
+#define KVM_MMU_HASH_SHIFT 12
+#define KVM_NUM_MMU_PAGES (1 << KVM_MMU_HASH_SHIFT)
+#define KVM_MIN_FREE_MMU_PAGES 5
+#define KVM_REFILL_PAGES 25
+

Btw, I found below defines can be moved to "mmu.h" too:

#define INVALID_PAGE (~(hpa_t)0)
#define VALID_PAGE(x) ((x) != INVALID_PAGE)

#define KVM_MMU_ROOT_INFO_INVALID \
((struct kvm_mmu_root_info) { .pgd = INVALID_PAGE, .hpa = INVALID_PAGE
})

And even below can be moved to "mmu.h", but perhaps you won't like that:

#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)

#define KVM_HPAGE_SHIFT(x)     (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
#define KVM_HPAGE_SIZE(x)      (1UL << KVM_HPAGE_SHIFT(x))
#define KVM_HPAGE_MASK(x)      (~(KVM_HPAGE_SIZE(x) - 1))

#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)

#define KVM_MMU_ROOT_CURRENT           BIT(0)
#define KVM_MMU_ROOT_PREVIOUS(i)       BIT(1+i)
#define KVM_MMU_ROOTS_ALL              (BIT(1 + KVM_MMU_NUM_PREV_ROOTS) - 1)

(I tried moving all of them to "mmu.h" and build test passed).

Reviewed-by on v3 37/40
#109 lore raw

Re: [PATCH v3 37/40] KVM: x86: Move kvm_pv_send_ipi() declaration from kvm_host.h => lapic.h

In reply to Sean Christopherson
Quoted 9 lines · Sean Christopherson

Move the declaration of kvm_pv_send_ipi() into lapic.h, as its implementation is provided by lapic.c (sending PV IPIs relies on the optimized APIC map provided by the in-kernel local APIC), and it's only used by KVM x86 code.

No functional change intended.

Reviewed-by on v3 38/40
#112 lore raw

Re: [PATCH v3 38/40] KVM: x86/mmu: Move kvm_arch_async_page_ready() below kvm_tdp_page_fault()

In reply to Sean Christopherson
Quoted 7 lines · Sean Christopherson

Move the implementation of kvm_arch_async_page_ready() "down" in mmu.c so that it lives below kvm_tdp_page_fault(). This will allow moving kvm_mmu_do_page_fault() into mmu.c without needing a forward declaration.

No functional change intended.

Reviewed-by on v3 39/40
#115 lore raw

Re: [PATCH v3 39/40] KVM: x86/mmu: Move kvm_mmu_do_page_fault() from mmu_internal.h => mmu.c

In reply to Sean Christopherson
Quoted 10 lines · Sean Christopherson

Move kvm_mmu_do_page_fault() into mmu.c, as there are no users outside of mmu.c, and the function typically isn't inlined by the compiler anyways. This will allow moving the EMULTYPE_xxx definitions into x86.h without having to include x86.h in mmu_internal.h, i.e. will help preserve the goal of making x86.h KVM x86's "top-level" include.

No functional change intended.

author maintainer
#120 lore raw
In reply to Sean Christopherson
Quoted 9 lines · Sean Christopherson

The first half of this series adds proper, explicit "raw" versions of kvm_<reg>_{read,write}(), along with "e" versions (for hardcoded 32-bit accesses), and converts the existing kvm_<reg>_{read,write}() APIs into mode-aware variants.

At the end of that journey, introduce regs.{c,h} to avoid moving _more_ code into x86.h, especially since the resulting code split would be super arbitrary.

[...]

Applied the cleanups, and two one-off patches, to kvm-x86 misc. I'll send a v4 for the code reshuffling, targeting 7.3.

[01/40] KVM: SVM: Truncate INVLPGA address in compatibility mode

        https://github.com/kvm-x86/linux/commit/42a842f3f6b9
[02/40] KVM: x86/xen: Bug the VM if 32-bit KVM observes a 64-bit mode hypercall
        https://github.com/kvm-x86/linux/commit/09912b8ad22f
[03/40] KVM: x86/xen: Don't truncate RAX when handling hypercall from protected guest
        https://github.com/kvm-x86/linux/commit/9377016c2f9e
[04/40] KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode
        https://github.com/kvm-x86/linux/commit/f43caad54cc0
[05/40] KVM: x86: Trace hypercall register *after* truncating values for 32-bit
        https://github.com/kvm-x86/linux/commit/16b5d193b212
[06/40] KVM: x86: Rename kvm_cache_regs.h => regs.h
        https://github.com/kvm-x86/linux/commit/ece08316ca21
[07/40] KVM: x86: Move inlined GPR, CR, and DR helpers from x86.h to regs.h
        https://github.com/kvm-x86/linux/commit/ed8a7b89c504
[08/40] KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers
        https://github.com/kvm-x86/linux/commit/fc40b1254c32
[09/40] KVM: x86: Drop non-raw kvm_<reg>_write() helpers
        https://github.com/kvm-x86/linux/commit/308851c2d6f8
[10/40] KVM: nSVM: Use kvm_rax_read() now that it's mode-aware
        https://github.com/kvm-x86/linux/commit/a7e6e09b27ca
[11/40] Revert "KVM: VMX: Read 32-bit GPR values for ENCLS instructions outside of 64-bit mode"
        https://github.com/kvm-x86/linux/commit/b6a0fdf2bbf0
[12/40] KVM: x86: Harden is_64_bit_hypercall() against bugs on 32-bit kernels
        https://github.com/kvm-x86/linux/commit/879fffc09474
[13/40] KVM: x86: Move update_cr8_intercept() to lapic.c
        https://github.com/kvm-x86/linux/commit/c7722e5e1dae
[14/40] KVM: x86: Move async #PF helpers to x86.h (as inlines)
        https://github.com/kvm-x86/linux/commit/bc87aec39399

...

[17/40] KVM: x86: Drop defunct vcpu_tsc_khz() declaration

        https://github.com/kvm-x86/linux/commit/e688ca78589d

...

[29/40] KVM: x86: Remove defunct kvm_load_segment_descriptor() declaration.

        https://github.com/kvm-x86/linux/commit/5fd25aacdf89

--
https://github.com/kvm-x86/linux/tree/next

author maintainer
#67 lore raw

Re: [PATCH v3 27/40] KVM: x86: Move register helper declarations from kvm_host.h => regs.h

In reply to Huang, Kai
Quoted 8 lines · Kai Huang
Quoted 3 lines · Sean Christopherson

void __kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);
+void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags);

:-)

Seems a candidate of making kvm_set_rflags() a 'static inline' ?

I actually don't want to, even though it seems like a no-brainer at first glance, because it would require exporting __kvm_set_rflags() to vendor code. Which wouldn't be terrible, but it seems like an unnecessary "risk", e.g. of folks trying to micro-optimize vendor flows to avoid the KVM_REQ_EVENT.

author maintainer
#54 lore raw

Re: [PATCH v3 23/40] KVM: x86: Move kvm_{load,put}_guest_fpu() to fpu.h

In reply to Huang, Kai
Quoted 18 lines · Kai Huang
Quoted 17 lines · Sean Christopherson
arch/x86/kvm/fpu.h +17 -0
+/* Swap (qemu) user FPU context for the guest FPU context. */
+static inline void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
+	/* Exclude PKRU, it's restored separately immediately after VM-Exit. */
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, true);
+	trace_kvm_fpu(1);
+}
+
+/* When vcpu_run ends, restore user space FPU context. */
+static inline void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
+{
+	if (KVM_BUG_ON(!vcpu->arch.guest_fpu.fpstate->in_use, vcpu->kvm))
+		return;
+
Quoted 8 lines

arch/x86/kvm/fpu.h line 33

Quoted 5 lines
arch/x86/kvm/fpu.h +5 -0
+	fpu_swap_kvm_fpstate(&vcpu->arch.guest_fpu, false);
+	++vcpu->stat.fpu_reload;
+	trace_kvm_fpu(0);
+}
+

Nit: to me it's a little bit weird to put the two functions before the typedefs and macro defines below, though.

Yeah, I don't disagree. But I think I'd prefer to keep it this way, so that the typedefs are more obviously bundled with the ugly XMM/AVX register helpers.

Quoted 4 lines
Quoted 4 lines

typedef u32 __attribute__((vector_size(16))) sse128_t;
#define __sse128_u union { sse128_t vec; u64 as_u64[2]; u32 as_u32[4]; }
#define sse128_lo(x) ({ __sse128_u t; t.vec = x; t.as_u64[0]; })

author maintainer
#84 lore raw

Re: [PATCH v3 31/40] KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

In reply to Huang, Kai
Quoted 37 lines · Kai Huang
Quoted 16 lines
arch/x86/include/asm/kvm_host.h +0 -6
index 1143140592df..f217403e18fc 100644
@@ -161,12 +161,6 @@
 #define KVM_HPAGE_MASK(x)	(~(KVM_HPAGE_SIZE(x) - 1))
 #define KVM_PAGES_PER_HPAGE(x)	(KVM_HPAGE_SIZE(x) / PAGE_SIZE)
 
-#define KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO 50
-#define KVM_MIN_ALLOC_MMU_PAGES 64UL
-#define KVM_MMU_HASH_SHIFT 12
-#define KVM_NUM_MMU_PAGES (1 << KVM_MMU_HASH_SHIFT)
-#define KVM_MIN_FREE_MMU_PAGES 5
-#define KVM_REFILL_PAGES 25 
 

[...]

Quoted 5 lines
arch/x86/kvm/mmu.h +0 -0
index d30676935fff..a6b871253bd7 100644

arch/x86/kvm/mmu.h extern bool tdp_mmu_enabled; · line 24

Quoted 10 lines
arch/x86/kvm/mmu.h +7 -0
@@ -15,6 +15,13 @@ extern bool tdp_mmu_enabled;
 extern bool __read_mostly enable_mmio_caching;
 extern bool eager_page_split;
 
+#define KVM_MEMSLOT_PAGES_TO_MMU_PAGES_RATIO 50
+#define KVM_MIN_ALLOC_MMU_PAGES 64UL
+#define KVM_MMU_HASH_SHIFT 12
+#define KVM_NUM_MMU_PAGES (1 << KVM_MMU_HASH_SHIFT)
+#define KVM_MIN_FREE_MMU_PAGES 5
+#define KVM_REFILL_PAGES 25
+

Btw, I found below defines can be moved to "mmu.h" too:

Quoted 6 lines

#define INVALID_PAGE (~(hpa_t)0)
#define VALID_PAGE(x) ((x) != INVALID_PAGE)

#define KVM_MMU_ROOT_INFO_INVALID \
((struct kvm_mmu_root_info) { .pgd = INVALID_PAGE, .hpa = INVALID_PAGE
})

I saw this one too, but I don't want to split KVM_MMU_ROOT_INFO_INVALID from the related defs:

  #define KVM_MMU_NUM_PREV_ROOTS 3

  #define KVM_MMU_ROOT_CURRENT		BIT(0)
  #define KVM_MMU_ROOT_PREVIOUS(i)	BIT(1+i)
  #define KVM_MMU_ROOTS_ALL		(BIT(1 + KVM_MMU_NUM_PREV_ROOTS) - 1)

Hrm, but KVM_MMU_ROOT_INFO_INVALID has exactly one user:

	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;

so leaving it in kvm_host.h is silly. Oof, but that's odd, the code above it does:

	mmu->root.hpa = INVALID_PAGE;
	mmu->root.pgd = 0;

as does kvm_mmu_free_roots():

		mmu->root.hpa = INVALID_PAGE;
		mmu->root.pgd = 0;

mmu_alloc_direct_roots() deliberately zeros "pgd" to guarantee matches on the pgd, as guest CR3 is ignored for direct roots, but the "invalidation" code looks wrong.

Let's handle KVM_MMU_ROOT_INFO_INVALID separately, as simply moving it probably isn't what we want to do.

Quoted 7 lines

And even below can be moved to "mmu.h", but perhaps you won't like that:

#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)

#define KVM_HPAGE_SHIFT(x)     (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
#define KVM_HPAGE_SIZE(x)      (1UL << KVM_HPAGE_SHIFT(x))
#define KVM_HPAGE_MASK(x)      (~(KVM_HPAGE_SIZE(x) - 1))

#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)

Huh. Oh, /facepalm. I looked at these, but saw there were references in kvm_host.h and moved on. But they're all "self" references. So yeah, I agree moving these and INVALID_PAGE+VALID_PAGE makes sense.

Quoted 3 lines
#define KVM_MMU_ROOT_CURRENT           BIT(0)
#define KVM_MMU_ROOT_PREVIOUS(i)       BIT(1+i)
#define KVM_MMU_ROOTS_ALL              (BIT(1 + KVM_MMU_NUM_PREV_ROOTS) - 1)

These I want to keep in kvm_host.h because they're tied to KVM_MMU_NUM_PREV_ROOTS, which needs to stay in kvm_host.h.

Thanks so much for the thorough review(s)!

author maintainer
#94 lore raw

Re: [PATCH v3 33/40] KVM: x86: Move kvm_cpu_get_apicid() from kvm_host.h => avic.c

In reply to Huang, Kai
Quoted 10 lines · Kai Huang
Quoted 9 lines · Sean Christopherson

#define KVM_CLOCK_VALID_FLAGS \

arch/x86/kvm/svm/avic.c +0 -0
index b7083cd692ad..9264c8ef1fa1 100644
@@ -146,6 +146,11 @@ static void avic_set_x2apic_msr_interception(struct vcpu_svm *svm,
 	svm->x2avic_msrs_intercepted = intercept;
 }
 
Quoted 10 lines

arch/x86/kvm/svm/avic.c static void avic_set_x2apic_msr_interception(struct vcpu_svm *svm,

Quoted 6 lines
arch/x86/kvm/svm/avic.c +5 -0
+static int kvm_cpu_get_apicid(int mps_cpu)
+{
+	return default_cpu_present_to_apicid(mps_cpu);
+}
+
 

Looks it is only used by AMD (svm/avic.c). I don't know why, but it would be nice if you can mention this in changelog, since this function seems pretty common to both Intel and AMD.

Huh, right, VMX posted interrupts needs the APIC ID too. Gah, posted_intr.c uses cpu_physical_id():

  #define cpu_physical_id(cpu)	per_cpu(x86_cpu_to_apicid, cpu)

which is basically the same thing as default_cpu_present_to_apicid():

u32 default_cpu_present_to_apicid(int mps_cpu)

  {
	if (mps_cpu < nr_cpu_ids && cpu_present(mps_cpu))
		return (int)per_cpu(x86_cpu_to_apicid, mps_cpu);
	else
		return BAD_APICID;

} EXPORT_SYMBOL_FOR_KVM(default_cpu_present_to_apicid);

Given that AVIC uses kvm_cpu_get_apicid() only when getting the pCPU for a loaded vCPU, it darn well should be impossible for the CPU to be offline, let alone not even present.

I'll drop this patch, and instead send a separate patch to have AVIC use cpu_physical_id(), and kill off both kvm_cpu_get_apicid() and the above EXPORT.

Thanks!

author maintainer
#98 lore raw

Re: [PATCH v3 34/40] KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c

In reply to Huang, Kai
Quoted 11 lines · Kai Huang
Quoted 5 lines · Sean Christopherson

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the hardcoded defines are often massaged at runtime, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

I am bit confused about what do you mean by "hardcoded defines are ofen massaged at runtime". Do you mean the supported flags can be changed at runtime via ioctl? But if we are talking about ioctl, then the flags must be part of uABI, which shouldn't change?

Not by ioctl, but by KVM's setup code. Is this more clear?

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the values from the hardcoded #defines are often captured and massaged by KVM's setup code, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

author maintainer
#79 lore raw

Re: [PATCH v3 30/40] KVM: x86: Move MSR helper declarations from kvm_host.h => msrs.h

In reply to Huang, Kai
Quoted 16 lines · Kai Huang
Quoted 2 lines · Sean Christopherson

Relocate declarations of MSR helpers (and kvm_nr_uret_msrs) from x86's x86's kvm_host.h to msrs, to continue trimming down kvm_host.h.

Double x86's

Quoted 7 lines

Deliberately leave the funky read_msr() where it is, as it will hopefully be removed entirely as part of a broader kernel-API cleanup.

No functional change intended.

Quoted 8 lines

Btw, not sure whether you like:

We can also move the body of 'struct msr_bitmap_range' and 'struct kvm_x86_msr_filter' to "msrs.h" too, if we put one

struct kvm_x86_msr_filter;

to <asm/kvm_host.h> before 'struct kvm_arch'.

Even better, we can move it all the way to msrs.c. Same with the PMU event filter, it can be moved to pmu.c. I'll do those in separate patches.

Thanks!

author maintainer
#85 lore raw

Re: [PATCH v3 31/40] KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

In reply to Sean Christopherson
Quoted 10 lines · Sean Christopherson
Quoted 5 lines · Kai Huang

#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)

#define KVM_HPAGE_SHIFT(x)     (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
#define KVM_HPAGE_SIZE(x)      (1UL << KVM_HPAGE_SHIFT(x))
#define KVM_HPAGE_MASK(x)      (~(KVM_HPAGE_SIZE(x) - 1))

#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)

Huh. Oh, /facepalm. I looked at these, but saw there were references in kvm_host.h and moved on. But they're all "self" references. So yeah, I agree moving these and INVALID_PAGE+VALID_PAGE makes sense.

Never mind, I was right the first time. KVM_NR_PAGE_SIZES is used in several locations, and I don't want to isolate that one.

#define KVM_MAX_HUGEPAGE_LEVEL PG_LEVEL_1G
#define KVM_NR_PAGE_SIZES (KVM_MAX_HUGEPAGE_LEVEL - PG_LEVEL_4K + 1) <===
#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)
#define KVM_HPAGE_SHIFT(x) (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
#define KVM_HPAGE_SIZE(x) (1UL << KVM_HPAGE_SHIFT(x))
#define KVM_HPAGE_MASK(x) (~(KVM_HPAGE_SIZE(x) - 1))
#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)

#86 lore raw

Re: [PATCH v3 31/40] KVM: x86: Move MMU helper declarations from kvm_host.h => mmu.h

Quoted 8 lines · Sean Christopherson
Quoted 7 lines · Sean Christopherson
Quoted 5 lines · Kai Huang

#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)

#define KVM_HPAGE_SHIFT(x)     (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
#define KVM_HPAGE_SIZE(x)      (1UL << KVM_HPAGE_SHIFT(x))
#define KVM_HPAGE_MASK(x)      (~(KVM_HPAGE_SIZE(x) - 1))

#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)

Quoted 6 lines
Quoted 3 lines

Huh. Oh, /facepalm. I looked at these, but saw there were references in kvm_host.h and moved on. But they're all "self" references. So yeah, I agree moving these and INVALID_PAGE+VALID_PAGE makes sense.

Never mind, I was right the first time. KVM_NR_PAGE_SIZES is used in several locations, and I don't want to isolate that one.

Right. That's why I thought you probably wouldn't like moving the rest to "mmu.h".

I feel KVM_MMU_ROOT_INFO_INVALID and INVALID_PAGE are not quite tied to KVM_MMU_NUM_PREV_ROOTS and KVM_MMU_ROOT_*, though, but yeah let's handle them in the future.

#99 lore raw

Re: [PATCH v3 34/40] KVM: x86: Move misc "VALID MASK" defines from kvm_host.h => x86.c

In reply to Sean Christopherson
Quoted 13 lines · Sean Christopherson
Quoted 11 lines · Kai Huang
Quoted 5 lines · Sean Christopherson

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the hardcoded defines are often massaged at runtime, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

I am bit confused about what do you mean by "hardcoded defines are ofen massaged at runtime". Do you mean the supported flags can be changed at runtime via ioctl? But if we are talking about ioctl, then the flags must be part of uABI, which shouldn't change?

Quoted 7 lines

Not by ioctl, but by KVM's setup code. Is this more clear?

Move a variety of "VALID MASK" defines, e.g. that capture which flags in a given ioctl are supported by KVM, from kvm_host.h to x86.c. The set of valid flags/bits is very much a KVM-internal detail, as the values from the hardcoded #defines are often captured and massaged by KVM's setup code, i.e. *directly* using the macros outside of KVM x86 would be actively dangerous.

Yes it's clearer to me. Thanks!