Skip to contentSkip to conversation

Enable FRED with KVM VMX

PATCH In review Xin Li 7 participants 95 messages Feb 7, 2024 – Sep 30, 2024 1 message not in the archive

Subsystems (5)
Documentation x86 KVM Kselftest +1 more subsystems

v2 of 5 In review Latest is v5 →

lore
Share & tools
lore

Xin Li

author
#0 lore raw

v2 cover Enable FRED with KVM VMX

This patch set enables the Intel flexible return and event delivery (FRED) architecture with KVM VMX to allow guests to utilize FRED.

The FRED architecture defines simple new transitions that change privilege level (ring transitions). The FRED architecture was designed with the following goals:

1) Improve overall performance and response time by replacing event delivery through the interrupt descriptor table (IDT event delivery) and event return by the IRET instruction with lower latency transitions.

2) Improve software robustness by ensuring that event delivery establishes the full supervisor context and that event return establishes the full user context.

The new transitions defined by the FRED architecture are FRED event delivery and, for returning from events, two FRED return instructions. FRED event delivery can effect a transition from ring 3 to ring 0, but it is used also to deliver events incident to ring 0. One FRED instruction (ERETU) effects a return from ring 0 to ring 3, while the other (ERETS) returns while remaining in ring 0. Collectively, FRED event delivery and the FRED return instructions are FRED transitions.

Intel VMX architecture is extended to run FRED guests, and the major changes are:

1) New VMCS fields for FRED context management, which includes two new event data VMCS fields, eight new guest FRED context VMCS fields and eight new host FRED context VMCS fields.

2) VMX nested-exception support for proper virtualization of stack levels introduced with FRED architecture.

Search for the latest FRED spec in most search engines with this search pattern:

site:intel.com FRED (flexible return and event delivery) specification

As the native FRED patches are committed in the tip tree "x86/fred" branch:
https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git/log/?h=x86/fred,
and we have received a good amount of review comments for v1, it's time to send out v2 based on this branch for further help from the community.

Patch 1-2 are cleanups to VMX basic and misc MSRs, which were sent out earlier as a preparation for FRED changes:
https://lore.kernel.org/kvm/[email protected]/T/#u

Patch 3-15 add FRED support to VMX.
Patch 16-21 add FRED support to nested VMX.
Patch 22 exposes FRED and its baseline features to KVM guests. Patch 23-25 add FRED selftests.

There is also a counterpart qemu patch set for FRED at:
https://lore.kernel.org/qemu-devel/[email protected]/T/,
which works with this patch set to allow KVM to run FRED guests.

Changes since v1:
* Always load the secondary VM exit controls (Sean Christopherson).
* Remove FRED VM entry/exit controls consistency checks in setup_vmcs_config() (Sean Christopherson).
* Clear FRED VM entry/exit controls if FRED is not enumerated (Chao Gao).
* Use guest_can_use() to trace FRED enumeration in a vcpu (Chao Gao).
* Enable FRED MSRs intercept if FRED is no longer enumerated in CPUID (Chao Gao).
* Move guest FRED states init into __vmx_vcpu_reset() (Chao Gao).
* Don't use guest_cpuid_has() in vmx_prepare_switch_to_{host,guest}(), which are called from IRQ-disabled context (Chao Gao).
* Reset msr_guest_fred_rsp0 in __vmx_vcpu_reset() (Chao Gao).
* Fail host requested FRED MSRs access if KVM cannot virtualize FRED (Chao Gao).
* Handle the case FRED MSRs are valid but KVM cannot virtualize FRED (Chao Gao).
* Add sanity checks when writing to FRED MSRs.
* Explain why it is ok to only check CR4.FRED in kvm_is_fred_enabled() (Chao Gao).
* Document event data should be equal to CR2/DR6/IA32_XFD_ERR instead of using WARN_ON() (Chao Gao).
* Zero event data if a #NM was not caused by extended feature disable (Chao Gao).
* Set the nested flag when there is an original interrupt (Chao Gao).
* Dump guest FRED states only if guest has FRED enabled (Nikolay Borisov).
* Add a prerequisite to SHADOW_FIELD_R[OW] macros
* Remove hyperv TLFS related changes (Jeremi Piotrowski).
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() to decouple KVM's capability to virtualize a feature and host's enabling of a feature (Chao Gao).

Xin Li (25):
KVM: VMX: Cleanup VMX basic information defines and usages
KVM: VMX: Cleanup VMX misc information defines and usages
KVM: VMX: Add support for the secondary VM exit controls
KVM: x86: Mark CR4.FRED as not reserved
KVM: VMX: Initialize FRED VM entry/exit controls in vmcs_config
KVM: VMX: Defer enabling FRED MSRs save/load until after set CPUID
KVM: VMX: Set intercept for FRED MSRs
KVM: VMX: Initialize VMCS FRED fields
KVM: VMX: Switch FRED RSP0 between host and guest
KVM: VMX: Add support for FRED context save/restore
KVM: x86: Add kvm_is_fred_enabled()
KVM: VMX: Handle FRED event data
KVM: VMX: Handle VMX nested exception for FRED
KVM: VMX: Disable FRED if FRED consistency checks fail
KVM: VMX: Dump FRED context in dump_vmcs()
KVM: VMX: Invoke vmx_set_cpu_caps() before nested setup
KVM: nVMX: Add support for the secondary VM exit controls
KVM: nVMX: Add a prerequisite to SHADOW_FIELD_R[OW] macros
KVM: nVMX: Add FRED VMCS fields
KVM: nVMX: Add support for VMX FRED controls
KVM: nVMX: Add VMCS FRED states checking
KVM: x86: Allow FRED/LKGS/WRMSRNS to be exposed to guests
KVM: selftests: Run debug_regs test with FRED enabled
KVM: selftests: Add a new VM guest mode to run user level code
KVM: selftests: Add fred exception tests

 Documentation/virt/kvm/x86/nested-vmx.rst     |  19 +
 arch/x86/include/asm/kvm_host.h               |   8 +-
 arch/x86/include/asm/msr-index.h              |  15 +-
 arch/x86/include/asm/vmx.h                    |  59 ++-
 arch/x86/kvm/cpuid.c                          |   4 +-
 arch/x86/kvm/governed_features.h              |   1 +
 arch/x86/kvm/kvm_cache_regs.h                 |  17 +
 arch/x86/kvm/svm/svm.c                        |   4 +-
 arch/x86/kvm/vmx/capabilities.h               |  30 +-
 arch/x86/kvm/vmx/nested.c                     | 329 ++++++++++++---
 arch/x86/kvm/vmx/nested.h                     |   2 +-
 arch/x86/kvm/vmx/vmcs.h                       |   1 +
 arch/x86/kvm/vmx/vmcs12.c                     |  19 +
 arch/x86/kvm/vmx/vmcs12.h                     |  38 ++
 arch/x86/kvm/vmx/vmcs_shadow_fields.h         |  80 ++--
 arch/x86/kvm/vmx/vmx.c                        | 385 +++++++++++++++---
 arch/x86/kvm/vmx/vmx.h                        |  15 +-
 arch/x86/kvm/x86.c                            | 103 ++++-
 arch/x86/kvm/x86.h                            |   5 +-
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/include/kvm_util_base.h     |   1 +
 .../selftests/kvm/include/x86_64/processor.h  |  36 ++
 tools/testing/selftests/kvm/lib/kvm_util.c    |   5 +-
 .../selftests/kvm/lib/x86_64/processor.c      |  15 +-
 tools/testing/selftests/kvm/lib/x86_64/vmx.c  |   4 +-
 .../testing/selftests/kvm/x86_64/debug_regs.c |  50 ++-
 .../testing/selftests/kvm/x86_64/fred_test.c  | 297 ++++++++++++++
 27 files changed, 1320 insertions(+), 223 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86_64/fred_test.c

base-commit: e13841907b8fda0ae0ce1ec03684665f578416a8

Signature · 1 line
2.43.0
author
#1 lore raw

PATCH v2 1/25 KVM: VMX: Cleanup VMX basic information defines and usages

Define VMX basic information fields with BIT_ULL()/GENMASK_ULL(), and replace hardcoded VMX basic numbers with these field macros.

Save the full/raw value of MSR_IA32_VMX_BASIC in the global vmcs_config as type u64 to get rid of the hi/lo crud, and then use VMX_BASIC helpers to extract info as needed.

VMX_EPTP_MT_{WB,UC} values 0x6 and 0x0 are generic x86 memory type values, no need to prefix them with VMX_EPTP_.

---

Changes since v4:
* Do not split VMX_BASIC bit definitions across multiple files (Kai Huang).
* Put some words to the changelog to justify changes around memory type macros (Kai Huang).
* Remove a leftover ';' (Kai Huang).

Changes since v3:
* Remove vmx_basic_vmcs_basic_cap() (Kai Huang).
* Add 2 macros VMX_BASIC_VMCS12_SIZE and VMX_BASIC_MEM_TYPE_WB to avoid keeping 2 their bit shift macros (Kai Huang).

Changes since v2:
* Simply save the full/raw value of MSR_IA32_VMX_BASIC in the global vmcs_config, and then use the helpers to extract info from it as needed (Sean Christopherson).
* Move all VMX_MISC related changes to the second patch (Kai Huang).
* Commonize memory type definitions used in the VMX files, as memory types are architectural.

Changes since v1:
* Don't add field shift macros unless it's really needed, extra layer of indirect makes it harder to read (Sean Christopherson).
* Add a static_assert() to ensure that VMX_BASIC_FEATURES_MASK doesn't overlap with VMX_BASIC_RESERVED_BITS (Sean Christopherson).
* read MSR_IA32_VMX_BASIC into an u64 rather than 2 u32 (Sean Christopherson).
* Add 2 new functions for extracting fields from VMX basic (Sean Christopherson).
* Drop the tools header update (Sean Christopherson).
* Move VMX basic field macros to arch/x86/include/asm/vmx.h.

---
 arch/x86/include/asm/msr-index.h |  9 ---------
 arch/x86/include/asm/vmx.h       | 18 ++++++++++++++++--
 arch/x86/kvm/vmx/capabilities.h  |  6 ++----
 arch/x86/kvm/vmx/nested.c        | 31 ++++++++++++++++++++-----------
 arch/x86/kvm/vmx/vmx.c           | 24 ++++++++++--------------
 5 files changed, 48 insertions(+), 40 deletions(-)
arch/x86/include/asm/msr-index.h +0 -9
index 1f9dc9bd13eb..e8af4cf01e89 100644
@@ -1113,15 +1113,6 @@
 #define MSR_IA32_VMX_VMFUNC             0x00000491
 #define MSR_IA32_VMX_PROCBASED_CTLS3	0x00000492
 
-/* VMX_BASIC bits and bitmasks */
-#define VMX_BASIC_VMCS_SIZE_SHIFT	32
-#define VMX_BASIC_TRUE_CTLS		(1ULL << 55)
-#define VMX_BASIC_64		0x0001000000000000LLU
-#define VMX_BASIC_MEM_TYPE_SHIFT	50
-#define VMX_BASIC_MEM_TYPE_MASK	0x003c000000000000LLU
-#define VMX_BASIC_MEM_TYPE_WB	6LLU
-#define VMX_BASIC_INOUT		0x0040000000000000LLU
-
 /* Resctrl MSRs: */
 /* - Intel: */
 #define MSR_IA32_L3_QOS_CFG		0xc81
arch/x86/include/asm/vmx.h +16 -2
index 4dba17363008..353538b79ce5 100644
@@ -121,6 +121,17 @@
 
 #define VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR	0x000011ff
 
+/* x86 memory types, explicitly used in VMX only */
+#define MEM_TYPE_WB				0x6ULL
+#define MEM_TYPE_UC				0x0ULL
+
+/* VMX_BASIC bits */
+#define VMX_BASIC_32BIT_PHYS_ADDR_ONLY		BIT_ULL(48)
+#define VMX_BASIC_DUAL_MONITOR_TREATMENT	BIT_ULL(49)
+#define VMX_BASIC_INOUT				BIT_ULL(54)
+#define VMX_BASIC_TRUE_CTLS			BIT_ULL(55)
+
+
 #define VMX_MISC_PREEMPTION_TIMER_RATE_MASK	0x0000001f
 #define VMX_MISC_SAVE_EFER_LMA			0x00000020
 #define VMX_MISC_ACTIVITY_HLT			0x00000040
@@ -144,6 +155,11 @@ static inline u32 vmx_basic_vmcs_size(u64 vmx_basic)
 	return (vmx_basic & GENMASK_ULL(44, 32)) >> 32;
 }
 
+static inline u32 vmx_basic_vmcs_mem_type(u64 vmx_basic)
+{
+	return (vmx_basic & GENMASK_ULL(53, 50)) >> 50;
+}
+
 static inline int vmx_misc_preemption_timer_rate(u64 vmx_misc)
 {
 	return vmx_misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
@@ -506,8 +522,6 @@ enum vmcs_field {
 #define VMX_EPTP_PWL_5				0x20ull
 #define VMX_EPTP_AD_ENABLE_BIT			(1ull << 6)
 #define VMX_EPTP_MT_MASK			0x7ull
-#define VMX_EPTP_MT_WB				0x6ull
-#define VMX_EPTP_MT_UC				0x0ull
 #define VMX_EPT_READABLE_MASK			0x1ull
 #define VMX_EPT_WRITABLE_MASK			0x2ull
 #define VMX_EPT_EXECUTABLE_MASK			0x4ull
arch/x86/kvm/vmx/capabilities.h +2 -4
index 41a4533f9989..86ce8bb96bed 100644
@@ -54,9 +54,7 @@ struct nested_vmx_msrs {
 };
 
 struct vmcs_config {
-	int size;
-	u32 basic_cap;
-	u32 revision_id;
+	u64 basic;
 	u32 pin_based_exec_ctrl;
 	u32 cpu_based_exec_ctrl;
 	u32 cpu_based_2nd_exec_ctrl;
@@ -76,7 +74,7 @@ extern struct vmx_capability vmx_capability __ro_after_init;
 
 static inline bool cpu_has_vmx_basic_inout(void)
 {
-	return	(((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
+	return	vmcs_config.basic & VMX_BASIC_INOUT;
 }
 
 static inline bool cpu_has_virtual_nmis(void)
arch/x86/kvm/vmx/nested.c +20 -11
index 6329a306856b..14d0167825dd 100644
@@ -1226,23 +1226,29 @@ static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
 	return (superset | subset) == superset;
 }
 
+#define VMX_BASIC_FEATURES_MASK			\
+	(VMX_BASIC_DUAL_MONITOR_TREATMENT |	\
+	 VMX_BASIC_INOUT |			\
+	 VMX_BASIC_TRUE_CTLS)
+
+#define VMX_BASIC_RESERVED_BITS			\
+	(GENMASK_ULL(63, 56) | GENMASK_ULL(47, 45) | BIT_ULL(31))
+
 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
 {
-	const u64 feature_and_reserved =
-		/* feature (except bit 48; see below) */
-		BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
-		/* reserved */
-		BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
 	u64 vmx_basic = vmcs_config.nested.basic;
 
-	if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
+	static_assert(!(VMX_BASIC_FEATURES_MASK & VMX_BASIC_RESERVED_BITS));
+
+	if (!is_bitwise_subset(vmx_basic, data,
+			       VMX_BASIC_FEATURES_MASK | VMX_BASIC_RESERVED_BITS))
 		return -EINVAL;
 
 	/*
 	 * KVM does not emulate a version of VMX that constrains physical
 	 * addresses of VMX structures (e.g. VMCS) to 32-bits.
 	 */
-	if (data & BIT_ULL(48))
+	if (data & VMX_BASIC_32BIT_PHYS_ADDR_ONLY)
 		return -EINVAL;
 
 	if (vmx_basic_vmcs_revision_id(vmx_basic) !=
@@ -2726,11 +2732,11 @@ static bool nested_vmx_check_eptp(struct kvm_vcpu *vcpu, u64 new_eptp)
 
 	/* Check for memory type validity */
 	switch (new_eptp & VMX_EPTP_MT_MASK) {
-	case VMX_EPTP_MT_UC:
+	case MEM_TYPE_UC:
 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT)))
 			return false;
 		break;
-	case VMX_EPTP_MT_WB:
+	case MEM_TYPE_WB:
 		if (CC(!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT)))
 			return false;
 		break;
@@ -6994,6 +7000,9 @@ static void nested_vmx_setup_misc_data(struct vmcs_config *vmcs_conf,
 	msrs->misc_high = 0;
 }
 
+#define VMX_BSAIC_VMCS12_SIZE	((u64)VMCS12_SIZE << 32)
+#define VMX_BASIC_MEM_TYPE_WB	(MEM_TYPE_WB << 50)
+
 static void nested_vmx_setup_basic(struct nested_vmx_msrs *msrs)
 {
 	/*
@@ -7005,8 +7014,8 @@ static void nested_vmx_setup_basic(struct nested_vmx_msrs *msrs)
 	msrs->basic =
 		VMCS12_REVISION |
 		VMX_BASIC_TRUE_CTLS |
-		((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
-		(VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
+		VMX_BSAIC_VMCS12_SIZE |
+		VMX_BASIC_MEM_TYPE_WB;
 
 	if (cpu_has_vmx_basic_inout())
 		msrs->basic |= VMX_BASIC_INOUT;
arch/x86/kvm/vmx/vmx.c +10 -14
index cce92f701dee..a16b3de01e3f 100644
@@ -2564,13 +2564,13 @@ static u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr)
 static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 			     struct vmx_capability *vmx_cap)
 {
-	u32 vmx_msr_low, vmx_msr_high;
 	u32 _pin_based_exec_control = 0;
 	u32 _cpu_based_exec_control = 0;
 	u32 _cpu_based_2nd_exec_control = 0;
 	u64 _cpu_based_3rd_exec_control = 0;
 	u32 _vmexit_control = 0;
 	u32 _vmentry_control = 0;
+	u64 basic_msr;
 	u64 misc_msr;
 	int i;
 
@@ -2689,29 +2689,25 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		_vmexit_control &= ~x_ctrl;
 	}
 
-	rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
+	rdmsrl(MSR_IA32_VMX_BASIC, basic_msr);
 
 	/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
-	if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
+	if ((vmx_basic_vmcs_size(basic_msr) > PAGE_SIZE))
 		return -EIO;
 
 #ifdef CONFIG_X86_64
 	/* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
-	if (vmx_msr_high & (1u<<16))
+	if (basic_msr & VMX_BASIC_32BIT_PHYS_ADDR_ONLY)
 		return -EIO;
 #endif
 
 	/* Require Write-Back (WB) memory type for VMCS accesses. */
-	if (((vmx_msr_high >> 18) & 15) != 6)
+	if (vmx_basic_vmcs_mem_type(basic_msr) != MEM_TYPE_WB)
 		return -EIO;
 
 	rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
 
-	vmcs_conf->size = vmx_msr_high & 0x1fff;
-	vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
-
-	vmcs_conf->revision_id = vmx_msr_low;
-
+	vmcs_conf->basic = basic_msr;
 	vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
 	vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
 	vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
@@ -2861,13 +2857,13 @@ struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
 	if (!pages)
 		return NULL;
 	vmcs = page_address(pages);
-	memset(vmcs, 0, vmcs_config.size);
+	memset(vmcs, 0, vmx_basic_vmcs_size(vmcs_config.basic));
 
 	/* KVM supports Enlightened VMCS v1 only */
 	if (kvm_is_using_evmcs())
 		vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
 	else
-		vmcs->hdr.revision_id = vmcs_config.revision_id;
+		vmcs->hdr.revision_id = vmx_basic_vmcs_revision_id(vmcs_config.basic);
 
 	if (shadow)
 		vmcs->hdr.shadow_vmcs = 1;
@@ -2960,7 +2956,7 @@ static __init int alloc_kvm_area(void)
 		 * physical CPU.
 		 */
 		if (kvm_is_using_evmcs())
-			vmcs->hdr.revision_id = vmcs_config.revision_id;
+			vmcs->hdr.revision_id = vmx_basic_vmcs_revision_id(vmcs_config.basic);
 
 		per_cpu(vmxarea, cpu) = vmcs;
 	}
@@ -3362,7 +3358,7 @@ static int vmx_get_max_ept_level(void)
 
 u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
 {
-	u64 eptp = VMX_EPTP_MT_WB;
+	u64 eptp = MEM_TYPE_WB;
 
 	eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
 
Signature · 1 line
2.43.0
author
#2 lore raw

PATCH v2 2/25 KVM: VMX: Cleanup VMX misc information defines and usages

In reply to Xin Li

Define VMX misc information fields with BIT_ULL()/GENMASK_ULL(), and move VMX misc field macros to vmx.h if used in multiple files or where they are used only once.

---
 arch/x86/include/asm/msr-index.h |  5 -----
 arch/x86/include/asm/vmx.h       | 12 +++++------
 arch/x86/kvm/vmx/capabilities.h  |  4 ++--
 arch/x86/kvm/vmx/nested.c        | 34 ++++++++++++++++++++++++--------
 arch/x86/kvm/vmx/nested.h        |  2 +-
 arch/x86/kvm/vmx/vmx.c           |  8 +++-----
 6 files changed, 37 insertions(+), 28 deletions(-)
arch/x86/include/asm/msr-index.h +0 -5
index e8af4cf01e89..4fa2b3dd743e 100644
@@ -1129,11 +1129,6 @@
 #define MSR_IA32_SMBA_BW_BASE		0xc0000280
 #define MSR_IA32_EVT_CFG_BASE		0xc0000400
 
-/* MSR_IA32_VMX_MISC bits */
-#define MSR_IA32_VMX_MISC_INTEL_PT                 (1ULL << 14)
-#define MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS (1ULL << 29)
-#define MSR_IA32_VMX_MISC_PREEMPTION_TIMER_SCALE   0x1F
-
 /* AMD-V MSRs */
 #define MSR_VM_CR                       0xc0010114
 #define MSR_VM_IGNNE                    0xc0010115
arch/x86/include/asm/vmx.h +5 -7
index 353538b79ce5..76518e21c54d 100644
@@ -132,12 +132,10 @@
 #define VMX_BASIC_TRUE_CTLS			BIT_ULL(55)
 
 
-#define VMX_MISC_PREEMPTION_TIMER_RATE_MASK	0x0000001f
-#define VMX_MISC_SAVE_EFER_LMA			0x00000020
-#define VMX_MISC_ACTIVITY_HLT			0x00000040
-#define VMX_MISC_ACTIVITY_WAIT_SIPI		0x00000100
-#define VMX_MISC_ZERO_LEN_INS			0x40000000
-#define VMX_MISC_MSR_LIST_MULTIPLIER		512
+/* VMX_MISC bits and bitmasks */
+#define VMX_MISC_INTEL_PT			BIT_ULL(14)
+#define VMX_MISC_VMWRITE_SHADOW_RO_FIELDS	BIT_ULL(29)
+#define VMX_MISC_ZERO_LEN_INS			BIT_ULL(30)
 
 /* VMFUNC functions */
 #define VMFUNC_CONTROL_BIT(x)	BIT((VMX_FEATURE_##x & 0x1f) - 28)
@@ -162,7 +160,7 @@ static inline u32 vmx_basic_vmcs_mem_type(u64 vmx_basic)
 
 static inline int vmx_misc_preemption_timer_rate(u64 vmx_misc)
 {
-	return vmx_misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
+	return vmx_misc & GENMASK_ULL(4, 0);
 }
 
 static inline int vmx_misc_cr3_count(u64 vmx_misc)
arch/x86/kvm/vmx/capabilities.h +2 -2
index 86ce8bb96bed..cb6588238f46 100644
@@ -223,7 +223,7 @@ static inline bool cpu_has_vmx_vmfunc(void)
 static inline bool cpu_has_vmx_shadow_vmcs(void)
 {
 	/* check if the cpu supports writing r/o exit information fields */
-	if (!(vmcs_config.misc & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
+	if (!(vmcs_config.misc & VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
 		return false;
 
 	return vmcs_config.cpu_based_2nd_exec_ctrl &
@@ -365,7 +365,7 @@ static inline bool cpu_has_vmx_invvpid_global(void)
 
 static inline bool cpu_has_vmx_intel_pt(void)
 {
-	return (vmcs_config.misc & MSR_IA32_VMX_MISC_INTEL_PT) &&
+	return (vmcs_config.misc & VMX_MISC_INTEL_PT) &&
 		(vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_PT_USE_GPA) &&
 		(vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_RTIT_CTL);
 }
arch/x86/kvm/vmx/nested.c +26 -8
index 14d0167825dd..8a5fda04e2de 100644
@@ -917,6 +917,8 @@ static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
 	return 0;
 }
 
+#define VMX_MISC_MSR_LIST_MULTIPLIER	512
+
 static u32 nested_vmx_max_atomic_switch_msrs(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
@@ -1315,18 +1317,34 @@ vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
 	return 0;
 }
 
+#define VMX_MISC_SAVE_EFER_LMA		BIT_ULL(5)
+#define VMX_MISC_ACTIVITY_STATE_BITMAP	GENMASK_ULL(8, 6)
+#define VMX_MISC_ACTIVITY_HLT		BIT_ULL(6)
+#define VMX_MISC_ACTIVITY_WAIT_SIPI	BIT_ULL(8)
+#define VMX_MISC_RDMSR_IN_SMM		BIT_ULL(15)
+#define VMX_MISC_VMXOFF_BLOCK_SMI	BIT_ULL(28)
+
+#define VMX_MISC_FEATURES_MASK			\
+	(VMX_MISC_SAVE_EFER_LMA |		\
+	 VMX_MISC_ACTIVITY_STATE_BITMAP |	\
+	 VMX_MISC_INTEL_PT |			\
+	 VMX_MISC_RDMSR_IN_SMM |		\
+	 VMX_MISC_VMXOFF_BLOCK_SMI |		\
+	 VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |	\
+	 VMX_MISC_ZERO_LEN_INS)
+
+#define VMX_MISC_RESERVED_BITS			\
+	(BIT_ULL(31) | GENMASK_ULL(13, 9))
+
 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
 {
-	const u64 feature_and_reserved_bits =
-		/* feature */
-		BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
-		BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
-		/* reserved */
-		GENMASK_ULL(13, 9) | BIT_ULL(31);
 	u64 vmx_misc = vmx_control_msr(vmcs_config.nested.misc_low,
 				       vmcs_config.nested.misc_high);
 
-	if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
+	static_assert(!(VMX_MISC_FEATURES_MASK & VMX_MISC_RESERVED_BITS));
+
+	if (!is_bitwise_subset(vmx_misc, data,
+			       VMX_MISC_FEATURES_MASK | VMX_MISC_RESERVED_BITS))
 		return -EINVAL;
 
 	if ((vmx->nested.msrs.pinbased_ctls_high &
@@ -6993,7 +7011,7 @@ static void nested_vmx_setup_misc_data(struct vmcs_config *vmcs_conf,
 {
 	msrs->misc_low = (u32)vmcs_conf->misc & VMX_MISC_SAVE_EFER_LMA;
 	msrs->misc_low |=
-		MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
+		VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
 		VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
 		VMX_MISC_ACTIVITY_HLT |
 		VMX_MISC_ACTIVITY_WAIT_SIPI;
arch/x86/kvm/vmx/nested.h +1 -1
index cce4e2aa30fb..0782fe599757 100644
@@ -109,7 +109,7 @@ static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
 {
 	return to_vmx(vcpu)->nested.msrs.misc_low &
-		MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
+		VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
 }
 
 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
arch/x86/kvm/vmx/vmx.c +3 -5
index a16b3de01e3f..581967d20659 100644
@@ -2571,7 +2571,6 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	u32 _vmexit_control = 0;
 	u32 _vmentry_control = 0;
 	u64 basic_msr;
-	u64 misc_msr;
 	int i;
 
 	/*
@@ -2705,8 +2704,6 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	if (vmx_basic_vmcs_mem_type(basic_msr) != MEM_TYPE_WB)
 		return -EIO;
 
-	rdmsrl(MSR_IA32_VMX_MISC, misc_msr);
-
 	vmcs_conf->basic = basic_msr;
 	vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
 	vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
@@ -2714,7 +2711,8 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
 	vmcs_conf->vmexit_ctrl         = _vmexit_control;
 	vmcs_conf->vmentry_ctrl        = _vmentry_control;
-	vmcs_conf->misc	= misc_msr;
+
+	rdmsrl(MSR_IA32_VMX_MISC, vmcs_conf->misc);
 
 #if IS_ENABLED(CONFIG_HYPERV)
 	if (enlightened_vmcs)
@@ -8603,7 +8601,7 @@ static __init int hardware_setup(void)
 		u64 use_timer_freq = 5000ULL * 1000 * 1000;
 
 		cpu_preemption_timer_multi =
-			vmcs_config.misc & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
+			vmx_misc_preemption_timer_rate(vmcs_config.misc);
 
 		if (tsc_khz)
 			use_timer_freq = (u64)tsc_khz * 1000;
Signature · 1 line
2.43.0
author
#3 lore raw

PATCH v2 3/25 KVM: VMX: Add support for the secondary VM exit controls

In reply to Xin Li

Enable the secondary VM exit controls to prepare for FRED enabling.

The activation of the secondary VM exit controls is off now, and it will be switched on when a VMX feature needing it is enabled.

---

Change since v1:
* Always load the secondary VM exit controls (Sean Christopherson).

---
 arch/x86/include/asm/msr-index.h |  1 +
 arch/x86/include/asm/vmx.h       |  3 +++
 arch/x86/kvm/vmx/capabilities.h  |  9 ++++++++-
 arch/x86/kvm/vmx/vmcs.h          |  1 +
 arch/x86/kvm/vmx/vmx.c           | 17 ++++++++++++++++-
 arch/x86/kvm/vmx/vmx.h           |  7 ++++++-
 6 files changed, 35 insertions(+), 3 deletions(-)
arch/x86/include/asm/msr-index.h +1 -0
index 4fa2b3dd743e..ab9ec10a3fff 100644
@@ -1112,6 +1112,7 @@
 #define MSR_IA32_VMX_TRUE_ENTRY_CTLS     0x00000490
 #define MSR_IA32_VMX_VMFUNC             0x00000491
 #define MSR_IA32_VMX_PROCBASED_CTLS3	0x00000492
+#define MSR_IA32_VMX_EXIT_CTLS2		0x00000493
 
 /* Resctrl MSRs: */
 /* - Intel: */
arch/x86/include/asm/vmx.h +3 -0
index 76518e21c54d..272af2004111 100644
@@ -105,6 +105,7 @@
 #define VM_EXIT_CLEAR_BNDCFGS                   0x00800000
 #define VM_EXIT_PT_CONCEAL_PIP			0x01000000
 #define VM_EXIT_CLEAR_IA32_RTIT_CTL		0x02000000
+#define VM_EXIT_ACTIVATE_SECONDARY_CONTROLS	0x80000000
 
 #define VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR	0x00036dff
 
@@ -250,6 +251,8 @@ enum vmcs_field {
 	TERTIARY_VM_EXEC_CONTROL_HIGH	= 0x00002035,
 	PID_POINTER_TABLE		= 0x00002042,
 	PID_POINTER_TABLE_HIGH		= 0x00002043,
+	SECONDARY_VM_EXIT_CONTROLS	= 0x00002044,
+	SECONDARY_VM_EXIT_CONTROLS_HIGH	= 0x00002045,
 	GUEST_PHYSICAL_ADDRESS          = 0x00002400,
 	GUEST_PHYSICAL_ADDRESS_HIGH     = 0x00002401,
 	VMCS_LINK_POINTER               = 0x00002800,
arch/x86/kvm/vmx/capabilities.h +8 -1
index cb6588238f46..e8f3ad0f79ee 100644
@@ -59,8 +59,9 @@ struct vmcs_config {
 	u32 cpu_based_exec_ctrl;
 	u32 cpu_based_2nd_exec_ctrl;
 	u64 cpu_based_3rd_exec_ctrl;
-	u32 vmexit_ctrl;
 	u32 vmentry_ctrl;
+	u32 vmexit_ctrl;
+	u64 secondary_vmexit_ctrl;
 	u64 misc;
 	struct nested_vmx_msrs nested;
 };
@@ -136,6 +137,12 @@ static inline bool cpu_has_tertiary_exec_ctrls(void)
 		CPU_BASED_ACTIVATE_TERTIARY_CONTROLS;
 }
 
+static inline bool cpu_has_secondary_vmexit_ctrls(void)
+{
+	return vmcs_config.vmexit_ctrl &
+		VM_EXIT_ACTIVATE_SECONDARY_CONTROLS;
+}
+
 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
 {
 	return vmcs_config.cpu_based_2nd_exec_ctrl &
arch/x86/kvm/vmx/vmcs.h +1 -0
index 7c1996b433e2..7d45a6504200 100644
@@ -47,6 +47,7 @@ struct vmcs_host_state {
 struct vmcs_controls_shadow {
 	u32 vm_entry;
 	u32 vm_exit;
+	u64 secondary_vm_exit;
 	u32 pin;
 	u32 exec;
 	u32 secondary_exec;
arch/x86/kvm/vmx/vmx.c +16 -1
index 581967d20659..4023474ea002 100644
@@ -2569,6 +2569,7 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	u32 _cpu_based_2nd_exec_control = 0;
 	u64 _cpu_based_3rd_exec_control = 0;
 	u32 _vmexit_control = 0;
+	u64 _secondary_vmexit_control = 0;
 	u32 _vmentry_control = 0;
 	u64 basic_msr;
 	int i;
@@ -2688,6 +2689,11 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		_vmexit_control &= ~x_ctrl;
 	}
 
+	if (_vmexit_control & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS)
+		_secondary_vmexit_control =
+			adjust_vmx_controls64(KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS,
+					      MSR_IA32_VMX_EXIT_CTLS2);
+
 	rdmsrl(MSR_IA32_VMX_BASIC, basic_msr);
 
 	/* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
@@ -2709,8 +2715,9 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
 	vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
 	vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control;
-	vmcs_conf->vmexit_ctrl         = _vmexit_control;
 	vmcs_conf->vmentry_ctrl        = _vmentry_control;
+	vmcs_conf->vmexit_ctrl         = _vmexit_control;
+	vmcs_conf->secondary_vmexit_ctrl   = _secondary_vmexit_control;
 
 	rdmsrl(MSR_IA32_VMX_MISC, vmcs_conf->misc);
 
@@ -4421,6 +4428,11 @@ static u32 vmx_vmexit_ctrl(void)
 		~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER);
 }
 
+static u64 vmx_secondary_vmexit_ctrl(void)
+{
+	return vmcs_config.secondary_vmexit_ctrl;
+}
+
 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
@@ -4766,6 +4778,9 @@ static void init_vmcs(struct vcpu_vmx *vmx)
 
 	vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
 
+	if (cpu_has_secondary_vmexit_ctrls())
+		secondary_vm_exit_controls_set(vmx, vmx_secondary_vmexit_ctrl());
+
 	/* 22.2.1, 20.8.1 */
 	vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
 
arch/x86/kvm/vmx/vmx.h +6 -1
index e3b0985bb74a..f470eeb2a5c8 100644
@@ -506,7 +506,11 @@ static inline u8 vmx_get_rvi(void)
 	       VM_EXIT_LOAD_IA32_EFER |					\
 	       VM_EXIT_CLEAR_BNDCFGS |					\
 	       VM_EXIT_PT_CONCEAL_PIP |					\
-	       VM_EXIT_CLEAR_IA32_RTIT_CTL)
+	       VM_EXIT_CLEAR_IA32_RTIT_CTL |				\
+	       VM_EXIT_ACTIVATE_SECONDARY_CONTROLS)
+
+#define KVM_REQUIRED_VMX_SECONDARY_VM_EXIT_CONTROLS (0)
+#define KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS (0)
 
 #define KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL			\
 	(PIN_BASED_EXT_INTR_MASK |					\
@@ -610,6 +614,7 @@ static __always_inline void lname##_controls_clearbit(struct vcpu_vmx *vmx, u##b
 }
 BUILD_CONTROLS_SHADOW(vm_entry, VM_ENTRY_CONTROLS, 32)
 BUILD_CONTROLS_SHADOW(vm_exit, VM_EXIT_CONTROLS, 32)
+BUILD_CONTROLS_SHADOW(secondary_vm_exit, SECONDARY_VM_EXIT_CONTROLS, 64)
 BUILD_CONTROLS_SHADOW(pin, PIN_BASED_VM_EXEC_CONTROL, 32)
 BUILD_CONTROLS_SHADOW(exec, CPU_BASED_VM_EXEC_CONTROL, 32)
 BUILD_CONTROLS_SHADOW(secondary_exec, SECONDARY_VM_EXEC_CONTROL, 32)
Signature · 1 line
2.43.0
author
#5 lore raw

PATCH v2 4/25 KVM: x86: Mark CR4.FRED as not reserved

In reply to Xin Li

The CR4.FRED bit, i.e., CR4[32], is no longer a reserved bit when a guest enumerates FRED, otherwise it is still a reserved bit.

---
 arch/x86/include/asm/kvm_host.h | 2 +-
 arch/x86/kvm/x86.h              | 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +1 -1
index b5b2d0fde579..0d88873eba63 100644
@@ -134,7 +134,7 @@
 			  | X86_CR4_OSXSAVE | X86_CR4_SMEP | X86_CR4_FSGSBASE \
 			  | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_VMXE \
 			  | X86_CR4_SMAP | X86_CR4_PKE | X86_CR4_UMIP \
-			  | X86_CR4_LAM_SUP))
+			  | X86_CR4_LAM_SUP | X86_CR4_FRED))
 
 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
 
arch/x86/kvm/x86.h +2 -0
index 2f7e19166658..9a52016ebf5a 100644
@@ -532,6 +532,8 @@ bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type);
 		__reserved_bits |= X86_CR4_PCIDE;       \
 	if (!__cpu_has(__c, X86_FEATURE_LAM))           \
 		__reserved_bits |= X86_CR4_LAM_SUP;     \
+	if (!__cpu_has(__c, X86_FEATURE_FRED))          \
+		__reserved_bits |= X86_CR4_FRED;        \
 	__reserved_bits;                                \
 })
 
Signature · 1 line
2.43.0
#7 lore raw

Re: [PATCH v2 04/25] KVM: x86: Mark CR4.FRED as not reserved

In reply to Xin Li
Quoted 2 lines · Xin Li

The CR4.FRED bit, i.e., CR4[32], is no longer a reserved bit when a guest enumerates FRED, otherwise it is still a reserved bit.

This isn't quite correct, as __cr4_reserved_bits() is used with kvm_cpu_caps too, i.e. to compute CR4 bits that are reserved from the host's perspective. And that matters, because if this check was done _only_ on guest CPUID, then KVM would allow CR4.FRED=1 before all of KVM support is in place.

Quoted 36 lines
---
 arch/x86/include/asm/kvm_host.h | 2 +-
 arch/x86/kvm/x86.h              | 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +1 -1
index b5b2d0fde579..0d88873eba63 100644
@@ -134,7 +134,7 @@
 			  | X86_CR4_OSXSAVE | X86_CR4_SMEP | X86_CR4_FSGSBASE \
 			  | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_VMXE \
 			  | X86_CR4_SMAP | X86_CR4_PKE | X86_CR4_UMIP \
-			  | X86_CR4_LAM_SUP))
+			  | X86_CR4_LAM_SUP | X86_CR4_FRED))
 
 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
 
arch/x86/kvm/x86.h +2 -0
index 2f7e19166658..9a52016ebf5a 100644
@@ -532,6 +532,8 @@ bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type);
 		__reserved_bits |= X86_CR4_PCIDE;       \
 	if (!__cpu_has(__c, X86_FEATURE_LAM))           \
 		__reserved_bits |= X86_CR4_LAM_SUP;     \
+	if (!__cpu_has(__c, X86_FEATURE_FRED))          \
+		__reserved_bits |= X86_CR4_FRED;        \
 	__reserved_bits;                                \
 })
 
Signature · 1 line
2.43.0
author
#8 lore raw

RE: [PATCH v2 04/25] KVM: x86: Mark CR4.FRED as not reserved

Quoted 9 lines · Xin Li
Quoted 2 lines

The CR4.FRED bit, i.e., CR4[32], is no longer a reserved bit when a guest enumerates FRED, otherwise it is still a reserved bit.

This isn't quite correct, as __cr4_reserved_bits() is used with kvm_cpu_caps too, i.e. to compute CR4 bits that are reserved from the host's perspective. And that matters, because if this check was done _only_ on guest CPUID, then KVM would allow CR4.FRED=1 before all of KVM support is in place.

Ah, that means I didn't dig deep enough.

Thanks!
Xin

author
#9 lore raw

PATCH v2 5/25 KVM: VMX: Initialize FRED VM entry/exit controls in vmcs_config

In reply to Xin Li

Setup the global vmcs_config for FRED:
1) Add VM_ENTRY_LOAD_IA32_FRED to KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS to have a FRED CPU load guest FRED MSRs from VMCS upon VM entry.
2) Add SECONDARY_VM_EXIT_SAVE_IA32_FRED to KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS to have a FRED CPU save guest FRED MSRs to VMCS during VM exit.
3) add SECONDARY_VM_EXIT_LOAD_IA32_FRED to KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS to have a FRED CPU load host FRED MSRs from VMCS during VM exit.

---

Change since v1:
* Remove FRED VM entry/exit controls consistency checks in setup_vmcs_config() (Sean Christopherson).

---
 arch/x86/include/asm/vmx.h | 3 +++
 arch/x86/kvm/vmx/vmx.h     | 7 +++++--
 2 files changed, 8 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +3 -0
index 272af2004111..cb14f7e315f5 100644
@@ -106,6 +106,8 @@
 #define VM_EXIT_PT_CONCEAL_PIP			0x01000000
 #define VM_EXIT_CLEAR_IA32_RTIT_CTL		0x02000000
 #define VM_EXIT_ACTIVATE_SECONDARY_CONTROLS	0x80000000
+#define SECONDARY_VM_EXIT_SAVE_IA32_FRED	0x00000001
+#define SECONDARY_VM_EXIT_LOAD_IA32_FRED	0x00000002
 
 #define VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR	0x00036dff
 
@@ -119,6 +121,7 @@
 #define VM_ENTRY_LOAD_BNDCFGS                   0x00010000
 #define VM_ENTRY_PT_CONCEAL_PIP			0x00020000
 #define VM_ENTRY_LOAD_IA32_RTIT_CTL		0x00040000
+#define VM_ENTRY_LOAD_IA32_FRED			0x00800000
 
 #define VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR	0x000011ff
 
arch/x86/kvm/vmx/vmx.h +5 -2
index f470eeb2a5c8..3ad52437f426 100644
@@ -484,7 +484,8 @@ static inline u8 vmx_get_rvi(void)
 	 VM_ENTRY_LOAD_IA32_EFER |					\
 	 VM_ENTRY_LOAD_BNDCFGS |					\
 	 VM_ENTRY_PT_CONCEAL_PIP |					\
-	 VM_ENTRY_LOAD_IA32_RTIT_CTL)
+	 VM_ENTRY_LOAD_IA32_RTIT_CTL |					\
+	 VM_ENTRY_LOAD_IA32_FRED)
 
 #define __KVM_REQUIRED_VMX_VM_EXIT_CONTROLS				\
 	(VM_EXIT_SAVE_DEBUG_CONTROLS |					\
@@ -510,7 +511,9 @@ static inline u8 vmx_get_rvi(void)
 	       VM_EXIT_ACTIVATE_SECONDARY_CONTROLS)
 
 #define KVM_REQUIRED_VMX_SECONDARY_VM_EXIT_CONTROLS (0)
-#define KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS (0)
+#define KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS			\
+	     (SECONDARY_VM_EXIT_SAVE_IA32_FRED |			\
+	      SECONDARY_VM_EXIT_LOAD_IA32_FRED)
 
 #define KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL			\
 	(PIN_BASED_EXT_INTR_MASK |					\
Signature · 1 line
2.43.0
Reviewed-by on v2 5/25
#10 lore raw

Re: [PATCH v2 05/25] KVM: VMX: Initialize FRED VM entry/exit controls in vmcs_config

Quoted 10 lines · Xin Li

Setup the global vmcs_config for FRED:
1) Add VM_ENTRY_LOAD_IA32_FRED to KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS to have a FRED CPU load guest FRED MSRs from VMCS upon VM entry.
2) Add SECONDARY_VM_EXIT_SAVE_IA32_FRED to KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS to have a FRED CPU save guest FRED MSRs to VMCS during VM exit.
3) add SECONDARY_VM_EXIT_LOAD_IA32_FRED to KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS to have a FRED CPU load host FRED MSRs from VMCS during VM exit.

Quoted 2 lines
author
#11 lore raw

PATCH v2 6/25 KVM: VMX: Defer enabling FRED MSRs save/load until after set CPUID

In reply to Xin Li

Clear FRED VM entry/exit controls when initializing a vCPU, and set these controls only if FRED is enumerated after set CPUID.

FRED VM entry/exit controls need to be set to establish context sufficient to support FRED event delivery immediately after VM entry and exit. However it is not required to save/load FRED MSRs for a non-FRED guest, which aren't supposed to access FRED MSRs.

---

Changes since v1:
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() (Chao Gao).
* Clear FRED VM entry/exit controls if FRED is not enumerated (Chao Gao).
* Use guest_can_use() to trace FRED enumeration in a vcpu (Chao Gao).

---
 arch/x86/kvm/governed_features.h |  1 +
 arch/x86/kvm/vmx/vmx.c           | 32 +++++++++++++++++++++++++++++++-
 2 files changed, 32 insertions(+), 1 deletion(-)
arch/x86/kvm/governed_features.h +1 -0
index ad463b1ed4e4..507ca73e52e9 100644
@@ -17,6 +17,7 @@ KVM_GOVERNED_X86_FEATURE(PFTHRESHOLD)
 KVM_GOVERNED_X86_FEATURE(VGIF)
 KVM_GOVERNED_X86_FEATURE(VNMI)
 KVM_GOVERNED_X86_FEATURE(LAM)
+KVM_GOVERNED_X86_FEATURE(FRED)
 
 #undef KVM_GOVERNED_X86_FEATURE
 #undef KVM_GOVERNED_FEATURE
arch/x86/kvm/vmx/vmx.c +31 -1
index 4023474ea002..34b6676f60d8 100644
@@ -4402,6 +4402,9 @@ static u32 vmx_vmentry_ctrl(void)
 	if (cpu_has_perf_global_ctrl_bug())
 		vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
 
+	/* Whether to load guest FRED MSRs is deferred until after set CPUID */
+	vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_FRED;
+
 	return vmentry_ctrl;
 }
 
@@ -4430,7 +4433,13 @@ static u32 vmx_vmexit_ctrl(void)
 
 static u64 vmx_secondary_vmexit_ctrl(void)
 {
-	return vmcs_config.secondary_vmexit_ctrl;
+	u64 secondary_vmexit_ctrl = vmcs_config.secondary_vmexit_ctrl;
+
+	/* Whether to save/load FRED MSRs is deferred until after set CPUID */
+	secondary_vmexit_ctrl &= ~(SECONDARY_VM_EXIT_SAVE_IA32_FRED |
+				   SECONDARY_VM_EXIT_LOAD_IA32_FRED);
+
+	return secondary_vmexit_ctrl;
 }
 
 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
@@ -7762,10 +7771,31 @@ static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
 		vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4));
 }
 
+static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_vmx *vmx = to_vmx(vcpu);
+
+	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
+
+	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
+		secondary_vm_exit_controls_setbit(vmx,
+						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
+						  SECONDARY_VM_EXIT_LOAD_IA32_FRED);
+	} else {
+		vm_entry_controls_clearbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
+		secondary_vm_exit_controls_clearbit(vmx,
+						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
+						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
+	}
+}
+
 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 
+	vmx_vcpu_config_fred_after_set_cpuid(vcpu);
+
 	/*
 	 * XSAVES is effectively enabled if and only if XSAVE is also exposed
 	 * to the guest.  XSAVES depends on CR4.OSXSAVE, and CR4.OSXSAVE can be
Signature · 1 line
2.43.0
Reviewed-by on v2 6/25
#12 lore raw

Re: [PATCH v2 06/25] KVM: VMX: Defer enabling FRED MSRs save/load until after set CPUID

Quoted 10 lines · Xin Li

Clear FRED VM entry/exit controls when initializing a vCPU, and set these controls only if FRED is enumerated after set CPUID.

FRED VM entry/exit controls need to be set to establish context sufficient to support FRED event delivery immediately after VM entry and exit. However it is not required to save/load FRED MSRs for a non-FRED guest, which aren't supposed to access FRED MSRs.

#13 lore raw

Re: [PATCH v2 06/25] KVM: VMX: Defer enabling FRED MSRs save/load until after set CPUID

In reply to Xin Li
Quoted 7 lines · Xin Li

Clear FRED VM entry/exit controls when initializing a vCPU, and set these controls only if FRED is enumerated after set CPUID.

FRED VM entry/exit controls need to be set to establish context sufficient to support FRED event delivery immediately after VM entry and exit. However it is not required to save/load FRED MSRs for a non-FRED guest, which aren't supposed to access FRED MSRs.

Does this actually provide a measurable performance boost? If not, just do the unnecessary load/store on entry/exit.

Generally speaking, the only time KVM dynamically toggles entry/exit controls is when KVM wants to run the guest with a host value, e.g. with the host's PERF_GLOBAL_CTRL.

author
#14 lore raw

RE: [PATCH v2 06/25] KVM: VMX: Defer enabling FRED MSRs save/load until after set CPUID

Quoted 11 lines · Xin Li
Quoted 7 lines

Clear FRED VM entry/exit controls when initializing a vCPU, and set these controls only if FRED is enumerated after set CPUID.

FRED VM entry/exit controls need to be set to establish context sufficient to support FRED event delivery immediately after VM entry and exit. However it is not required to save/load FRED MSRs for a non-FRED guest, which aren't supposed to access FRED MSRs.

Does this actually provide a measurable performance boost? If not, just do the unnecessary load/store on entry/exit.

No performance measurement yet. Will make the change.

Quoted 4 lines

Generally speaking, the only time KVM dynamically toggles entry/exit controls is when KVM wants to run the guest with a host value, e.g. with the host's PERF_GLOBAL_CTRL.

Simple rule.

Thanks!
Xin

author
#15 lore raw

PATCH v2 7/25 KVM: VMX: Set intercept for FRED MSRs

In reply to Xin Li

Add FRED MSRs to the valid passthrough MSR list and set FRED MSRs intercept based on FRED enumeration.

---

Change since v1:
* Enable FRED MSRs intercept if FRED is no longer enumerated in CPUID (Chao Gao).

---
 arch/x86/kvm/vmx/vmx.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/vmx.c +16 -1
index 34b6676f60d8..d58ed2d3d379 100644
@@ -693,6 +693,9 @@ static bool is_valid_passthrough_msr(u32 msr)
 	case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
 		/* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
 		return true;
+	case MSR_IA32_FRED_RSP0 ... MSR_IA32_FRED_CONFIG:
+		/* FRED MSRs should be passthrough to FRED guests only */
+		return true;
 	}
 
 	r = possible_passthrough_msr_slot(msr) != -ENOENT;
@@ -7774,10 +7777,12 @@ static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
 static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	bool fred_enumerated;
 
 	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);
 
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
 		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
 		secondary_vm_exit_controls_setbit(vmx,
 						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
@@ -7788,6 +7793,16 @@ static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
 						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
 	}
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, !fred_enumerated);
 }
 
 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
Signature · 1 line
2.43.0
Reviewed-by on v2 7/25
#16 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 5 lines · Xin Li

Add FRED MSRs to the valid passthrough MSR list and set FRED MSRs intercept based on FRED enumeration.

two nits below.

Quoted 14 lines

---

Change since v1:
* Enable FRED MSRs intercept if FRED is no longer enumerated in CPUID (Chao Gao).
---
arch/x86/kvm/vmx/vmx.c | 17 ++++++++++++++++-

1 file changed, 16 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/vmx.c +0 -0
index 34b6676f60d8..d58ed2d3d379 100644

arch/x86/kvm/vmx/vmx.c static bool is_valid_passthrough_msr(u32 msr) · line 697

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -693,6 +693,9 @@ static bool is_valid_passthrough_msr(u32 msr)
 	case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
 		/* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
 		return true;
+	case MSR_IA32_FRED_RSP0 ... MSR_IA32_FRED_CONFIG:
+		/* FRED MSRs should be passthrough to FRED guests only */

This comment sounds weird. It sounds like the code will be something like:
if guest supports FRED
return true
else
return false

how about "FRED MSRs are pass-thru'd to guests which enumerate FRED"?

Or to align with above comment for LBR MSRs, just say

/* FRED MSRs. These are handled in vmx_vcpu_config_fred_after_set_cpuid() */

Quoted 22 lines
arch/x86/kvm/vmx/vmx.c +4 -1
+		return true;
 	}
 
 	r = possible_passthrough_msr_slot(msr) != -ENOENT;
@@ -7774,10 +7777,12 @@ static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
 static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	bool fred_enumerated;
 
 	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);
 
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
 		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
 		secondary_vm_exit_controls_setbit(vmx,
 						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
@@ -7788,6 +7793,16 @@ static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
 						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
 	}

arch/x86/kvm/vmx/vmx.c static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu) · line 7805

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, !fred_enumerated);

Use a for-loop here? e.g.,

	for (i = MSR_IA32_FRED_RSP0; i <= MSR_IA32_FRED_CONFIG; i++)
Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +0 -0
 }
 
 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
Signature · 1 line
2.43.0
author
#17 lore raw

RE: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 9 lines

arch/x86/kvm/vmx/vmx.c static bool is_valid_passthrough_msr(u32 msr) · line 697

Quoted 2 lines
arch/x86/kvm/vmx/vmx.c +2 -0
+	case MSR_IA32_FRED_RSP0 ... MSR_IA32_FRED_CONFIG:
+		/* FRED MSRs should be passthrough to FRED guests only */

This comment sounds weird. It sounds like the code will be something like:
if guest supports FRED
return true
else
return false

Quoted 6 lines

how about "FRED MSRs are pass-thru'd to guests which enumerate FRED"?

Or to align with above comment for LBR MSRs, just say

/* FRED MSRs. These are handled in vmx_vcpu_config_fred_after_set_cpuid() */

Maybe both to not confuse people at all 😊

Quoted 40 lines
Quoted 15 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+		return true;
	}

	r = possible_passthrough_msr_slot(msr) != -ENOENT; @@ -7774,10
+7777,12 @@ static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
arch/x86/kvm/vmx/vmx.c +1 -0
+	bool fred_enumerated;
	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
arch/x86/kvm/vmx/vmx.c +2 -1
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);
 
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
Quoted 3 lines
		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
		secondary_vm_exit_controls_setbit(vmx,

SECONDARY_VM_EXIT_SAVE_IA32_FRED | @@ -7788,6 +7793,16 @@

Quoted 2 lines

static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)

SECONDARY_VM_EXIT_SAVE_IA32_FRED |

Quoted 1 line

SECONDARY_VM_EXIT_LOAD_IA32_FRED);

Review

Quoted 3 lines
	}
(quoted diff) +2 -0
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2,

MSR_TYPE_RW, !fred_enumerated);

Quoted 8 lines

Review

Quoted 1 line
(quoted diff) +1 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3,

MSR_TYPE_RW, !fred_enumerated);

Review

Quoted 2 lines
(quoted diff) +2 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW,
+!fred_enumerated);

Use a for-loop here? e.g.,

	for (i = MSR_IA32_FRED_RSP0; i <= MSR_IA32_FRED_CONFIG; i++)
Quoted 1 line

}

Yeah, let me try.

#18 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

In reply to Chao Gao
Quoted 3 lines · Chao Gao
Quoted 2 lines · Xin Li

Add FRED MSRs to the valid passthrough MSR list and set FRED MSRs intercept based on FRED enumeration.

This needs a *much* more verbose explanation. It's pretty darn obvious _what_ KVM is doing, but it's not at all clear _why_ KVM is passing through FRED MSRs. E.g. why is FRED_SSP0 not included in the set of passthrough MSRs?

Quoted 29 lines
Quoted 17 lines

static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)

{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
arch/x86/kvm/vmx/vmx.c +1 -0
+	bool fred_enumerated;
	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
arch/x86/kvm/vmx/vmx.c +2 -1
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);
 
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
		secondary_vm_exit_controls_setbit(vmx,
						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -7788,6 +7793,16 @@ static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
 						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
 	}

arch/x86/kvm/vmx/vmx.c static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu) · line 7805

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, !fred_enumerated);

Use a for-loop here? e.g.,

Quoted 1 line
	for (i = MSR_IA32_FRED_RSP0; i <= MSR_IA32_FRED_CONFIG; i++)

Hmm, I'd prefer to keep the open coded version. It's not pretty, but I don't expect this to have much, if any, maintenance cost. And using a loop makes it harder to both understand _exactly_ what's happening, and to search for relevant code. E.g. it's quite difficult to see that FRED_SSP0 is still intercepted (see my comment regarding the changelog).

#19 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 40 lines · Sean Christopherson
Quoted 3 lines · Chao Gao
Quoted 2 lines · Xin Li

Add FRED MSRs to the valid passthrough MSR list and set FRED MSRs intercept based on FRED enumeration.

This needs a *much* more verbose explanation. It's pretty darn obvious _what_ KVM is doing, but it's not at all clear _why_ KVM is passing through FRED MSRs. E.g. why is FRED_SSP0 not included in the set of passthrough MSRs?

Quoted 29 lines
Quoted 17 lines

static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)

{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
arch/x86/kvm/vmx/vmx.c +1 -0
+	bool fred_enumerated;
	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
arch/x86/kvm/vmx/vmx.c +2 -1
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);
 
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
		secondary_vm_exit_controls_setbit(vmx,
						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -7788,6 +7793,16 @@ static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
 						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
 	}

arch/x86/kvm/vmx/vmx.c static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu) · line 7805

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, !fred_enumerated);

Use a for-loop here? e.g.,

Quoted 1 line
	for (i = MSR_IA32_FRED_RSP0; i <= MSR_IA32_FRED_CONFIG; i++)
Quoted 5 lines

Hmm, I'd prefer to keep the open coded version. It's not pretty, but I don't expect this to have much, if any, maintenance cost. And using a loop makes it harder to both understand _exactly_ what's happening, and to search for relevant code. E.g. it's quite difficult to see that FRED_SSP0 is still intercepted (see my comment regarding the changelog).

I owe you an explanation; I have been thinking about figuring out a way to include FRED SSP0 in the FRED KVM patch set...

MSR_IA32_FRED_SSP0 is an alias of the CET MSR_IA32_PL0_SSP and likely to be used in the same way as FRED RSP0, i.e., host FRED SSP0 _should_ be restored in arch_exit_to_user_mode_prepare(). However as of today Linux has no plan to utilize kernel shadow stack thus no one cares host FRED SSP0 (no?). But lets say anyway it is host's responsibility to manage host FRED SSP0, then KVM only needs to take care of guest FRED SSP0 (just like how KVM should handle guest FRED RSP0) even before the supervisor shadow stack feature is advertised to guest.

Another question is should KVM handle userspace request to set/get FRED SSP0? IMO, it should be part of CET state management.

Your suggestion?

Thanks!
Xin

#20 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 51 lines · Xin Li
Quoted 40 lines · Sean Christopherson
Quoted 3 lines · Chao Gao
Quoted 2 lines · Xin Li

Add FRED MSRs to the valid passthrough MSR list and set FRED MSRs intercept based on FRED enumeration.

This needs a *much* more verbose explanation. It's pretty darn obvious _what_ KVM is doing, but it's not at all clear _why_ KVM is passing through FRED MSRs. E.g. why is FRED_SSP0 not included in the set of passthrough MSRs?

Quoted 29 lines
Quoted 17 lines

static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)

{
	struct vcpu_vmx *vmx = to_vmx(vcpu);
arch/x86/kvm/vmx/vmx.c +1 -0
+	bool fred_enumerated;
	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
arch/x86/kvm/vmx/vmx.c +2 -1
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);
 
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
		secondary_vm_exit_controls_setbit(vmx,
						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -7788,6 +7793,16 @@ static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
 						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
 	}

arch/x86/kvm/vmx/vmx.c static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu) · line 7805

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, !fred_enumerated);

Use a for-loop here? e.g.,

Quoted 1 line
	for (i = MSR_IA32_FRED_RSP0; i <= MSR_IA32_FRED_CONFIG; i++)
Quoted 5 lines

Hmm, I'd prefer to keep the open coded version. It's not pretty, but I don't expect this to have much, if any, maintenance cost. And using a loop makes it harder to both understand _exactly_ what's happening, and to search for relevant code. E.g. it's quite difficult to see that FRED_SSP0 is still intercepted (see my comment regarding the changelog).

I owe you an explanation; I have been thinking about figuring out a way to include FRED SSP0 in the FRED KVM patch set...

Quoted 8 lines

MSR_IA32_FRED_SSP0 is an alias of the CET MSR_IA32_PL0_SSP and likely to be used in the same way as FRED RSP0, i.e., host FRED SSP0 _should_ be restored in arch_exit_to_user_mode_prepare(). However as of today Linux has no plan to utilize kernel shadow stack thus no one cares host FRED SSP0 (no?). But lets say anyway it is host's responsibility to manage host FRED SSP0, then KVM only needs to take care of guest FRED SSP0 (just like how KVM should handle guest FRED RSP0) even before the supervisor shadow stack feature is advertised to guest.

Heh, I'm not sure what your question is, or if there even is a question. KVM needs to context switch FRED SSP0 if FRED is exposed to the guest, but presumably that will be done through XSAVE state? If that's the long term plan, I would prefer to focus on merging CET virtualization first, and then land FRED virtualization on top so that KVM doesn't have to carry intermediate code to deal with the aliased MSR.

Ugh, but what happens if a CPU (or the host kernel) supports FRED but not CET SS? Or is that effectively an illegal combination?

Quoted 2 lines

Another question is should KVM handle userspace request to set/get FRED SSP0? IMO, it should be part of CET state management.

Yes, KVM needs to allow userspace to get/set FRED SSP0. In general, KVM needs to allow reads/writes to MSRs even if they can be saved/restored through some other means. In most cases, including this one, it's a moot point, because KVM needs to have the necessary code anyways, e.g. if KVM encounters a RDMSR/WRMSR while emulating.

#21 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 9 lines
Quoted 8 lines

MSR_IA32_FRED_SSP0 is an alias of the CET MSR_IA32_PL0_SSP and likely to be used in the same way as FRED RSP0, i.e., host FRED SSP0 _should_ be restored in arch_exit_to_user_mode_prepare(). However as of today Linux has no plan to utilize kernel shadow stack thus no one cares host FRED SSP0 (no?). But lets say anyway it is host's responsibility to manage host FRED SSP0, then KVM only needs to take care of guest FRED SSP0 (just like how KVM should handle guest FRED RSP0) even before the supervisor shadow stack feature is advertised to guest.

Quoted 6 lines

Heh, I'm not sure what your question is, or if there even is a question. KVM needs to context switch FRED SSP0 if FRED is exposed to the guest, but presumably that will be done through XSAVE state? If that's the long term plan, I would prefer to focus on merging CET virtualization first, and then land FRED virtualization on top so that KVM doesn't have to carry intermediate code to deal with the aliased MSR.

You mean the following patch set, right?

https://lore.kernel.org/kvm/[email protected]/

I think it's probably better to do so. Otherwise a patch to explicitly save/restore FRED SSP0 would be needed before the CET patch set lands and then reverted immediately after:

arch/x86/kvm/vmx/vmx.c +3 -1
index f828f03d48ab..c790cb7a7d6b 100644
@@ -1343,8 +1343,10 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
 
-       if (cpu_feature_enabled(X86_FEATURE_FRED) && guest_can_use(vcpu, X86_FEATURE_FRED))
+       if (cpu_feature_enabled(X86_FEATURE_FRED) && guest_can_use(vcpu, X86_FEATURE_FRED)) {
                wrmsrns(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
+               wrmsrns(MSR_IA32_FRED_SSP0, vmx->msr_guest_fred_ssp0);
+       }
 #else
        savesegment(fs, fs_sel);
        savesegment(gs, gs_sel);
@@ -1393,6 +1395,8 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
        if (cpu_feature_enabled(X86_FEATURE_FRED) && 
guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
                vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
                fred_sync_rsp0(vmx->msr_guest_fred_rsp0);
+
+               vmx->msr_guest_fred_ssp0 = read_msr(MSR_IA32_FRED_SSP0);
        }
 #endif
        load_fixmap_gdt(raw_smp_processor_id());
arch/x86/kvm/vmx/vmx.h +1 -0
index 9012428984de..d1b9352f56c7 100644
@@ -282,6 +282,7 @@ struct vcpu_vmx {
        u64                   msr_host_kernel_gs_base;
        u64                   msr_guest_kernel_gs_base;
        u64                   msr_guest_fred_rsp0;
+       u64                   msr_guest_fred_ssp0;
 #endif
 
        u64                   spec_ctrl;
Quoted 3 lines

Ugh, but what happens if a CPU (or the host kernel) supports FRED but not CET SS? Or is that effectively an illegal combination?

The FRED Spec says:

IA32_FRED_SSP1, IA32_FRED_SSP2, and IA32_FRED_SSP3 (MSR indices 1D1H–
1D3H). Together with the existing MSR IA32_PL0_SSP (MSR index 6A4H), these are the FRED SSP MSRs.

The FRED SSP MSRs are supported by any processor that enumerates
CPUID.(EAX=7,ECX=1):EAX.FRED[bit 17] as 1. If such a processor does not support CET, FRED transitions will not use the MSRs (because shadow stacks are not enabled), but the MSRs would still be accessible using RDMSR and WRMSR.

So they are independent, just that FRED SSP MSRs are NOT used if supervisor shadow stacks are not enabled (obviously Qemu can be configured to not advertise CET but FRED).

When FRED is advertised to a guest, KVM should allow FRED SSP MSRs accesses through disabling FRED SSP MSRs interception no matter whether supervisor shadow stacks are enabled or not.

Thanks!
Xin

#22 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 9 lines · Xin Li
Quoted 9 lines
Quoted 8 lines

MSR_IA32_FRED_SSP0 is an alias of the CET MSR_IA32_PL0_SSP and likely to be used in the same way as FRED RSP0, i.e., host FRED SSP0 _should_ be restored in arch_exit_to_user_mode_prepare(). However as of today Linux has no plan to utilize kernel shadow stack thus no one cares host FRED SSP0 (no?). But lets say anyway it is host's responsibility to manage host FRED SSP0, then KVM only needs to take care of guest FRED SSP0 (just like how KVM should handle guest FRED RSP0) even before the supervisor shadow stack feature is advertised to guest.

Quoted 8 lines
Quoted 6 lines

Heh, I'm not sure what your question is, or if there even is a question. KVM needs to context switch FRED SSP0 if FRED is exposed to the guest, but presumably that will be done through XSAVE state? If that's the long term plan, I would prefer to focus on merging CET virtualization first, and then land FRED virtualization on top so that KVM doesn't have to carry intermediate code to deal with the aliased MSR.

You mean the following patch set, right?

Yep, and presumably the KVM support as well:

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

Quoted 1 line

https://lore.kernel.org/kvm/[email protected]/

...

Quoted 16 lines
Quoted 2 lines

Ugh, but what happens if a CPU (or the host kernel) supports FRED but not CET SS? Or is that effectively an illegal combination?

The FRED Spec says:

IA32_FRED_SSP1, IA32_FRED_SSP2, and IA32_FRED_SSP3 (MSR indices 1D1H– 1D3H). Together with the existing MSR IA32_PL0_SSP (MSR index 6A4H), these are the FRED SSP MSRs.

The FRED SSP MSRs are supported by any processor that enumerates CPUID.(EAX=7,ECX=1):EAX.FRED[bit 17] as 1. If such a processor does not support CET, FRED transitions will not use the MSRs (because shadow stacks are not enabled), but the MSRs would still be accessible using RDMSR and WRMSR.

Quoted 7 lines

So they are independent, just that FRED SSP MSRs are NOT used if supervisor shadow stacks are not enabled (obviously Qemu can be configured to not advertise CET but FRED).

When FRED is advertised to a guest, KVM should allow FRED SSP MSRs accesses through disabling FRED SSP MSRs interception no matter whether supervisor shadow stacks are enabled or not.

KVM doesn't necessarily need to disabling MSR interception, e.g. if the expectation is that the guest will rarely/never access the MSRs when CET is unsupported, then we're likely better off going with a trap-and-emulate model. KVM needs to emulate RDMSR and WRMSR no matter what, e.g. in case the guest triggers a WRMSR when KVM is emulating, and so that userspace can get/set MSR values.

And this means that yes, FRED virtualization needs to land after CET virtualization, otherwise managing the conflicts/dependencies will be a nightmare.

#23 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 4 lines · Sean Christopherson
Quoted 1 line · Xin Li

You mean the following patch set, right?

Yep, and presumably the KVM support as well:

I assume it's close to KVM upstreaming criteria :)

Quoted 5 lines

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

Quoted 1 line

https://lore.kernel.org/kvm/[email protected]/

...

Quoted 5 lines
Quoted 4 lines

When FRED is advertised to a guest, KVM should allow FRED SSP MSRs accesses through disabling FRED SSP MSRs interception no matter whether supervisor shadow stacks are enabled or not.

Quoted 9 lines

KVM doesn't necessarily need to disabling MSR interception, e.g. if the expectation is that the guest will rarely/never access the MSRs when CET is unsupported, then we're likely better off going with a trap-and-emulate model. KVM needs to emulate RDMSR and WRMSR no matter what, e.g. in case the guest triggers a WRMSR when KVM is emulating, and so that userspace can get/set MSR values.

And this means that yes, FRED virtualization needs to land after CET virtualization, otherwise managing the conflicts/dependencies will be a nightmare.

No argument.

Thanks!
Xin

#24 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 10 lines
Quoted 10 lines
Quoted 3 lines

When FRED is advertised to a guest, KVM should allow FRED SSP MSRs accesses through disabling FRED SSP MSRs interception no matter whether supervisor shadow stacks are enabled or not.

KVM doesn't necessarily need to disabling MSR interception, e.g. if the expectation is that the guest will rarely/never access the MSRs when CET is unsupported, then we're likely better off going with a trap-and-emulate model.  KVM needs to emulate RDMSR and WRMSR no matter what, e.g. in case the guest triggers a WRMSR when KVM is emulating, and so that userspace can get/set MSR values.

Quoted 3 lines
Quoted 3 lines

And this means that yes, FRED virtualization needs to land after CET virtualization, otherwise managing the conflicts/dependencies will be a nightmare.

I still plan to send another iteration of the FRED patch set for review, however I haven't seen your x86 KVM changes land into Linus' tree, it will happen soon, right?

Quoted 2 lines

No argument.

#25 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

Quoted 14 lines · Xin Li
Quoted 14 lines
Quoted 14 lines
Quoted 3 lines

When FRED is advertised to a guest, KVM should allow FRED SSP MSRs accesses through disabling FRED SSP MSRs interception no matter whether supervisor shadow stacks are enabled or not.

KVM doesn't necessarily need to disabling MSR interception, e.g. if the expectation
is that the guest will rarely/never access the MSRs when CET is unsupported, then
we're likely better off going with a trap-and-emulate model.  KVM needs to emulate
RDMSR and WRMSR no matter what, e.g. in case the guest triggers a WRMSR when KVM
is emulating, and so that userspace can get/set MSR values.

Quoted 8 lines
Quoted 4 lines
Quoted 4 lines

And this means that yes, FRED virtualization needs to land after CET virtualization,
otherwise managing the conflicts/dependencies will be a nightmare.

I still plan to send another iteration of the FRED patch set for review, however I haven't seen your x86 KVM changes land into Linus' tree, it will happen soon, right?

Yep, we squeaked into rc1, the pull request to Linus was delayed because of travel and conferences.

#26 lore raw

Re: [PATCH v2 07/25] KVM: VMX: Set intercept for FRED MSRs

In reply to Xin Li

arch/x86/kvm/vmx/vmx.c static void update_intel_pt_cfg(struct kvm_vcpu *vcpu) · line 7783

Quoted 8 lines · Xin Li
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -7774,10 +7777,12 @@ static void update_intel_pt_cfg(struct kvm_vcpu *vcpu)
 static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	bool fred_enumerated;
 
 	kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_FRED);
+	fred_enumerated = guest_can_use(vcpu, X86_FEATURE_FRED);

"enumerated" isn't correct. Userspace can enumerate FRED to the guest even if FRED is unsupported in KVM.

Planning for a future where this becomes guest_cpu_cap_has(), maybe "has_fred"?

Quoted 25 lines
arch/x86/kvm/vmx/vmx.c +11 -1
-	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+	if (fred_enumerated) {
 		vm_entry_controls_setbit(vmx, VM_ENTRY_LOAD_IA32_FRED);
 		secondary_vm_exit_controls_setbit(vmx,
 						  SECONDARY_VM_EXIT_SAVE_IA32_FRED |
@@ -7788,6 +7793,16 @@ static void vmx_vcpu_config_fred_after_set_cpuid(struct kvm_vcpu *vcpu)
 						    SECONDARY_VM_EXIT_SAVE_IA32_FRED |
 						    SECONDARY_VM_EXIT_LOAD_IA32_FRED);
 	}
+
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, !fred_enumerated);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, !fred_enumerated);
 }
 
 static void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
Signature · 1 line
2.43.0
author
#27 lore raw

PATCH v2 8/25 KVM: VMX: Initialize VMCS FRED fields

In reply to Xin Li

Initialize host VMCS FRED fields with host FRED MSRs' value and guest VMCS FRED fields to 0.

FRED CPU states are managed in 9 new FRED MSRs, as well as a few existing CPU registers and MSRs, e.g., CR4.FRED. To support FRED context management, new VMCS fields corresponding to most of FRED CPU state MSRs are added to both the host-state and guest-state areas of VMCS.

Specifically no VMCS fields are added for FRED RSP0 and SSP0 MSRs, because the 2 FRED MSRs are used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely even with guest FRED RSP0 and SSP0. It can be deferred to load host FRED RSP0 and SSP0 until before returning to user level.

---

Changes since v1:
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() to decouple KVM's capability to virtualize a feature and host's enabling of a feature (Chao Gao).
* Move guest FRED states init into __vmx_vcpu_reset() (Chao Gao).

---
 arch/x86/include/asm/vmx.h | 16 ++++++++++++++++
 arch/x86/kvm/vmx/vmx.c     | 34 ++++++++++++++++++++++++++++++++++
 2 files changed, 50 insertions(+)
arch/x86/include/asm/vmx.h +16 -0
index cb14f7e315f5..4889754415b5 100644
@@ -280,12 +280,28 @@ enum vmcs_field {
 	GUEST_BNDCFGS_HIGH              = 0x00002813,
 	GUEST_IA32_RTIT_CTL		= 0x00002814,
 	GUEST_IA32_RTIT_CTL_HIGH	= 0x00002815,
+	GUEST_IA32_FRED_CONFIG		= 0x0000281a,
+	GUEST_IA32_FRED_RSP1		= 0x0000281c,
+	GUEST_IA32_FRED_RSP2		= 0x0000281e,
+	GUEST_IA32_FRED_RSP3		= 0x00002820,
+	GUEST_IA32_FRED_STKLVLS		= 0x00002822,
+	GUEST_IA32_FRED_SSP1		= 0x00002824,
+	GUEST_IA32_FRED_SSP2		= 0x00002826,
+	GUEST_IA32_FRED_SSP3		= 0x00002828,
 	HOST_IA32_PAT			= 0x00002c00,
 	HOST_IA32_PAT_HIGH		= 0x00002c01,
 	HOST_IA32_EFER			= 0x00002c02,
 	HOST_IA32_EFER_HIGH		= 0x00002c03,
 	HOST_IA32_PERF_GLOBAL_CTRL	= 0x00002c04,
 	HOST_IA32_PERF_GLOBAL_CTRL_HIGH	= 0x00002c05,
+	HOST_IA32_FRED_CONFIG		= 0x00002c08,
+	HOST_IA32_FRED_RSP1		= 0x00002c0a,
+	HOST_IA32_FRED_RSP2		= 0x00002c0c,
+	HOST_IA32_FRED_RSP3		= 0x00002c0e,
+	HOST_IA32_FRED_STKLVLS		= 0x00002c10,
+	HOST_IA32_FRED_SSP1		= 0x00002c12,
+	HOST_IA32_FRED_SSP2		= 0x00002c14,
+	HOST_IA32_FRED_SSP3		= 0x00002c16,
 	PIN_BASED_VM_EXEC_CONTROL       = 0x00004000,
 	CPU_BASED_VM_EXEC_CONTROL       = 0x00004002,
 	EXCEPTION_BITMAP                = 0x00004004,
arch/x86/kvm/vmx/vmx.c +34 -0
index d58ed2d3d379..b7b772183ee4 100644
@@ -1470,6 +1470,18 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
 				    (unsigned long)(cpu_entry_stack(cpu) + 1));
 		}
 
+#ifdef CONFIG_X86_64
+		/* Per-CPU FRED MSRs */
+		if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+			vmcs_write64(HOST_IA32_FRED_RSP1, read_msr(MSR_IA32_FRED_RSP1));
+			vmcs_write64(HOST_IA32_FRED_RSP2, read_msr(MSR_IA32_FRED_RSP2));
+			vmcs_write64(HOST_IA32_FRED_RSP3, read_msr(MSR_IA32_FRED_RSP3));
+			vmcs_write64(HOST_IA32_FRED_SSP1, read_msr(MSR_IA32_FRED_SSP1));
+			vmcs_write64(HOST_IA32_FRED_SSP2, read_msr(MSR_IA32_FRED_SSP2));
+			vmcs_write64(HOST_IA32_FRED_SSP3, read_msr(MSR_IA32_FRED_SSP3));
+		}
+#endif
+
 		vmx->loaded_vmcs->cpu = cpu;
 	}
 }
@@ -4321,6 +4333,15 @@ void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
 	 */
 	vmcs_write16(HOST_DS_SELECTOR, 0);
 	vmcs_write16(HOST_ES_SELECTOR, 0);
+
+	/*
+	 * FRED MSRs are per-cpu, however FRED CONFIG and STKLVLS MSRs
+	 * are the same on all CPUs, thus they are initialized here.
+	 */
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmcs_write64(HOST_IA32_FRED_CONFIG, read_msr(MSR_IA32_FRED_CONFIG));
+		vmcs_write64(HOST_IA32_FRED_STKLVLS, read_msr(MSR_IA32_FRED_STKLVLS));
+	}
 #else
 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
@@ -4865,6 +4886,19 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
 	 */
 	vmx->pi_desc.nv = POSTED_INTR_VECTOR;
 	vmx->pi_desc.sn = 1;
+
+#ifdef CONFIG_X86_64
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmcs_write64(GUEST_IA32_FRED_CONFIG, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP1, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP2, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP3, 0);
+		vmcs_write64(GUEST_IA32_FRED_STKLVLS, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP1, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP2, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP3, 0);
+	}
+#endif
 }
 
 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
Signature · 1 line
2.43.0
#28 lore raw

Re: [PATCH v2 08/25] KVM: VMX: Initialize VMCS FRED fields

Quoted 67 lines · Xin Li

Initialize host VMCS FRED fields with host FRED MSRs' value and guest VMCS FRED fields to 0.

FRED CPU states are managed in 9 new FRED MSRs, as well as a few existing CPU registers and MSRs, e.g., CR4.FRED. To support FRED context management, new VMCS fields corresponding to most of FRED CPU state MSRs are added to both the host-state and guest-state areas of VMCS.

Specifically no VMCS fields are added for FRED RSP0 and SSP0 MSRs, because the 2 FRED MSRs are used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely even with guest FRED RSP0 and SSP0. It can be deferred to load host FRED RSP0 and SSP0 until before returning to user level.

---

Changes since v1:
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() to decouple KVM's capability to virtualize a feature and host's enabling of a feature (Chao Gao).
* Move guest FRED states init into __vmx_vcpu_reset() (Chao Gao).
---
arch/x86/include/asm/vmx.h | 16 ++++++++++++++++
arch/x86/kvm/vmx/vmx.c | 34 ++++++++++++++++++++++++++++++++++

2 files changed, 50 insertions(+)
arch/x86/include/asm/vmx.h +16 -0
index cb14f7e315f5..4889754415b5 100644
@@ -280,12 +280,28 @@ enum vmcs_field {
 	GUEST_BNDCFGS_HIGH              = 0x00002813,
 	GUEST_IA32_RTIT_CTL		= 0x00002814,
 	GUEST_IA32_RTIT_CTL_HIGH	= 0x00002815,
+	GUEST_IA32_FRED_CONFIG		= 0x0000281a,
+	GUEST_IA32_FRED_RSP1		= 0x0000281c,
+	GUEST_IA32_FRED_RSP2		= 0x0000281e,
+	GUEST_IA32_FRED_RSP3		= 0x00002820,
+	GUEST_IA32_FRED_STKLVLS		= 0x00002822,
+	GUEST_IA32_FRED_SSP1		= 0x00002824,
+	GUEST_IA32_FRED_SSP2		= 0x00002826,
+	GUEST_IA32_FRED_SSP3		= 0x00002828,
 	HOST_IA32_PAT			= 0x00002c00,
 	HOST_IA32_PAT_HIGH		= 0x00002c01,
 	HOST_IA32_EFER			= 0x00002c02,
 	HOST_IA32_EFER_HIGH		= 0x00002c03,
 	HOST_IA32_PERF_GLOBAL_CTRL	= 0x00002c04,
 	HOST_IA32_PERF_GLOBAL_CTRL_HIGH	= 0x00002c05,
+	HOST_IA32_FRED_CONFIG		= 0x00002c08,
+	HOST_IA32_FRED_RSP1		= 0x00002c0a,
+	HOST_IA32_FRED_RSP2		= 0x00002c0c,
+	HOST_IA32_FRED_RSP3		= 0x00002c0e,
+	HOST_IA32_FRED_STKLVLS		= 0x00002c10,
+	HOST_IA32_FRED_SSP1		= 0x00002c12,
+	HOST_IA32_FRED_SSP2		= 0x00002c14,
+	HOST_IA32_FRED_SSP3		= 0x00002c16,
 	PIN_BASED_VM_EXEC_CONTROL       = 0x00004000,
 	CPU_BASED_VM_EXEC_CONTROL       = 0x00004002,
 	EXCEPTION_BITMAP                = 0x00004004,
arch/x86/kvm/vmx/vmx.c +0 -0
index d58ed2d3d379..b7b772183ee4 100644

arch/x86/kvm/vmx/vmx.c void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu, · line 1473

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +1 -0
@@ -1470,6 +1470,18 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
 				    (unsigned long)(cpu_entry_stack(cpu) + 1));
 		}
 
+#ifdef CONFIG_X86_64

is this #ifdeffery neccesary?

I assume kvm_cpu_cap_has(X86_FEATURE_FRED) is always false for !CONFIG_X86_64. Looks most of FRED changes in core kernel don't have such #ifdeffery.

arch/x86/kvm/vmx/vmx.c void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu, · line 1474

Quoted 1 line
arch/x86/kvm/vmx/vmx.c +1 -0
+		/* Per-CPU FRED MSRs */

Please explain why these six MSRs are updated here and why only they are updated in this comment.

Quoted 30 lines
arch/x86/kvm/vmx/vmx.c +19 -0
+		if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+			vmcs_write64(HOST_IA32_FRED_RSP1, read_msr(MSR_IA32_FRED_RSP1));
+			vmcs_write64(HOST_IA32_FRED_RSP2, read_msr(MSR_IA32_FRED_RSP2));
+			vmcs_write64(HOST_IA32_FRED_RSP3, read_msr(MSR_IA32_FRED_RSP3));
+			vmcs_write64(HOST_IA32_FRED_SSP1, read_msr(MSR_IA32_FRED_SSP1));
+			vmcs_write64(HOST_IA32_FRED_SSP2, read_msr(MSR_IA32_FRED_SSP2));
+			vmcs_write64(HOST_IA32_FRED_SSP3, read_msr(MSR_IA32_FRED_SSP3));
+		}
+#endif
+
 		vmx->loaded_vmcs->cpu = cpu;
 	}
 }
@@ -4321,6 +4333,15 @@ void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
 	 */
 	vmcs_write16(HOST_DS_SELECTOR, 0);
 	vmcs_write16(HOST_ES_SELECTOR, 0);
+
+	/*
+	 * FRED MSRs are per-cpu, however FRED CONFIG and STKLVLS MSRs
+	 * are the same on all CPUs, thus they are initialized here.
+	 */
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmcs_write64(HOST_IA32_FRED_CONFIG, read_msr(MSR_IA32_FRED_CONFIG));
+		vmcs_write64(HOST_IA32_FRED_STKLVLS, read_msr(MSR_IA32_FRED_STKLVLS));
+	}
 #else
 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */

arch/x86/kvm/vmx/vmx.c static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu) · line 4890

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -4865,6 +4886,19 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
 	 */
 	vmx->pi_desc.nv = POSTED_INTR_VECTOR;
 	vmx->pi_desc.sn = 1;
+
+#ifdef CONFIG_X86_64

ditto

Quoted 18 lines
arch/x86/kvm/vmx/vmx.c +11 -0
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmcs_write64(GUEST_IA32_FRED_CONFIG, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP1, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP2, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP3, 0);
+		vmcs_write64(GUEST_IA32_FRED_STKLVLS, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP1, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP2, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP3, 0);
+	}
+#endif
 }
 
 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
Signature · 1 line
2.43.0
author
#29 lore raw

RE: [PATCH v2 08/25] KVM: VMX: Initialize VMCS FRED fields

Quoted 3 lines
Quoted 1 line

+#ifdef CONFIG_X86_64

is this #ifdeffery neccesary?

Yes, otherwise build fails on 32 bit.

Quoted 4 lines

I assume kvm_cpu_cap_has(X86_FEATURE_FRED) is always false for !CONFIG_X86_64.
Looks most of FRED changes in core kernel don't have such #ifdeffery.

Because it's not a compile time false, instead false from runtime.

Quoted 5 lines

arch/x86/kvm/vmx/vmx.c void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu, · line 1474

Quoted 2 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+		/* Per-CPU FRED MSRs */

Please explain why these six MSRs are updated here and why only they are updated in this comment.

The explanation is kind of implicit "per-CPU", I will make it more explicit.

Thanks!
Xin

#30 lore raw

Re: [PATCH v2 08/25] KVM: VMX: Initialize VMCS FRED fields

In reply to Xin Li

arch/x86/kvm/vmx/vmx.c void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu, · line 1473

Quoted 9 lines · Xin Li
arch/x86/kvm/vmx/vmx.c +1 -0
index d58ed2d3d379..b7b772183ee4 100644
@@ -1470,6 +1470,18 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
 				    (unsigned long)(cpu_entry_stack(cpu) + 1));
 		}
 
+#ifdef CONFIG_X86_64

Don't bother, practically no one cares about 32-bit KVM these days, and I highly don't anyone that runs 32-bit KVM cares about the code footprint to this degree.

arch/x86/kvm/vmx/vmx.c void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu, · line 1481

Quoted 8 lines
arch/x86/kvm/vmx/vmx.c +8 -0
+		/* Per-CPU FRED MSRs */
+		if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+			vmcs_write64(HOST_IA32_FRED_RSP1, read_msr(MSR_IA32_FRED_RSP1));
+			vmcs_write64(HOST_IA32_FRED_RSP2, read_msr(MSR_IA32_FRED_RSP2));
+			vmcs_write64(HOST_IA32_FRED_RSP3, read_msr(MSR_IA32_FRED_RSP3));
+			vmcs_write64(HOST_IA32_FRED_SSP1, read_msr(MSR_IA32_FRED_SSP1));
+			vmcs_write64(HOST_IA32_FRED_SSP2, read_msr(MSR_IA32_FRED_SSP2));
+			vmcs_write64(HOST_IA32_FRED_SSP3, read_msr(MSR_IA32_FRED_SSP3));

That's a lot of RDMSRs to eat on every task migration. How hard would it be to add a per-CPU cache for each of these? Or is there a pre-existing way to get at the info that's faster than RDMSR?

Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +3 -0
+		}
+#endif
+
 		vmx->loaded_vmcs->cpu = cpu;
 	}
 }

arch/x86/kvm/vmx/vmx.c void vmx_set_constant_host_state(struct vcpu_vmx *vmx) · line 4339

Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +4 -0
@@ -4321,6 +4333,15 @@ void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
 	 */
 	vmcs_write16(HOST_DS_SELECTOR, 0);
 	vmcs_write16(HOST_ES_SELECTOR, 0);
+
+	/*
+	 * FRED MSRs are per-cpu, however FRED CONFIG and STKLVLS MSRs
+	 * are the same on all CPUs, thus they are initialized here.

Eh, just trim this to:

	/* FRED CONFIG and STKLVLS are the same on all CPUs. */
Quoted 14 lines
arch/x86/kvm/vmx/vmx.c +7 -0
+	 */
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmcs_write64(HOST_IA32_FRED_CONFIG, read_msr(MSR_IA32_FRED_CONFIG));
+		vmcs_write64(HOST_IA32_FRED_STKLVLS, read_msr(MSR_IA32_FRED_STKLVLS));
+	}
 #else
 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
@@ -4865,6 +4886,19 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
 	 */
 	vmx->pi_desc.nv = POSTED_INTR_VECTOR;
 	vmx->pi_desc.sn = 1;
+
+#ifdef CONFIG_X86_64

arch/x86/kvm/vmx/vmx.c static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu) · line 4900

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmcs_write64(GUEST_IA32_FRED_CONFIG, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP1, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP2, 0);
+		vmcs_write64(GUEST_IA32_FRED_RSP3, 0);
+		vmcs_write64(GUEST_IA32_FRED_STKLVLS, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP1, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP2, 0);
+		vmcs_write64(GUEST_IA32_FRED_SSP3, 0);
+	}

Somewhat of a moot point, but this belongs in init_vmcs(), not __vmx_vcpu_reset().

author
#31 lore raw

PATCH v2 9/25 KVM: VMX: Switch FRED RSP0 between host and guest

In reply to Xin Li

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

---

Changes since v1:
* Don't use guest_cpuid_has() in vmx_prepare_switch_to_{host,guest}(), which are called from IRQ-disabled context (Chao Gao).
* Reset msr_guest_fred_rsp0 in __vmx_vcpu_reset() (Chao Gao).

---
 arch/x86/kvm/vmx/vmx.c | 17 +++++++++++++++++
 arch/x86/kvm/vmx/vmx.h |  2 ++
 2 files changed, 19 insertions(+)
arch/x86/kvm/vmx/vmx.c +17 -0
index b7b772183ee4..264378c3b784 100644
@@ -1337,6 +1337,16 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 	}
 
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
+
+	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+		/*
+		 * MSR_IA32_FRED_RSP0 is top of task stack, which never changes.
+		 * Thus it should be initialized only once.
+		 */
+		if (unlikely(vmx->msr_host_fred_rsp0 == 0))
+			vmx->msr_host_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
+	}
 #else
 	savesegment(fs, fs_sel);
 	savesegment(gs, gs_sel);
@@ -1381,6 +1391,11 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
 	invalidate_tss_limit();
 #ifdef CONFIG_X86_64
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
+
+	if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);
+	}
 #endif
 	load_fixmap_gdt(raw_smp_processor_id());
 	vmx->guest_state_loaded = false;
@@ -4889,6 +4904,8 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
 
 #ifdef CONFIG_X86_64
 	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = 0;
+
 		vmcs_write64(GUEST_IA32_FRED_CONFIG, 0);
 		vmcs_write64(GUEST_IA32_FRED_RSP1, 0);
 		vmcs_write64(GUEST_IA32_FRED_RSP2, 0);
arch/x86/kvm/vmx/vmx.h +2 -0
index 3ad52437f426..176ad39be406 100644
@@ -278,6 +278,8 @@ struct vcpu_vmx {
 #ifdef CONFIG_X86_64
 	u64		      msr_host_kernel_gs_base;
 	u64		      msr_guest_kernel_gs_base;
+	u64		      msr_host_fred_rsp0;
+	u64		      msr_guest_fred_rsp0;
 #endif
 
 	u64		      spec_ctrl;
Signature · 1 line
2.43.0
#32 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 30 lines · Xin Li

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

---

Changes since v1:
* Don't use guest_cpuid_has() in vmx_prepare_switch_to_{host,guest}(), which are called from IRQ-disabled context (Chao Gao).
* Reset msr_guest_fred_rsp0 in __vmx_vcpu_reset() (Chao Gao).
---
arch/x86/kvm/vmx/vmx.c | 17 +++++++++++++++++ arch/x86/kvm/vmx/vmx.h | 2 ++

2 files changed, 19 insertions(+)
arch/x86/kvm/vmx/vmx.c +0 -0
index b7b772183ee4..264378c3b784 100644
@@ -1337,6 +1337,16 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 	}

arch/x86/kvm/vmx/vmx.c void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) · line 1347

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +8 -0
 
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
+
+	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+		/*
+		 * MSR_IA32_FRED_RSP0 is top of task stack, which never changes.
+		 * Thus it should be initialized only once.
+		 */
+		if (unlikely(vmx->msr_host_fred_rsp0 == 0))
+			vmx->msr_host_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);

can we just drop this and use "(unsigned long)task_stack_page(current) + THREAD_SIZE" as host fred rsp0?

arch/x86/kvm/vmx/vmx.c void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) · line 1348

Quoted 1 line
arch/x86/kvm/vmx/vmx.c +1 -0
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);

any reason to not use wrmsrns?

arch/x86/kvm/vmx/vmx.c static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx) · line 1397

Quoted 12 lines
arch/x86/kvm/vmx/vmx.c +5 -0
+	}
 #else
 	savesegment(fs, fs_sel);
 	savesegment(gs, gs_sel);
@@ -1381,6 +1391,11 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
 	invalidate_tss_limit();
 #ifdef CONFIG_X86_64
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
+
+	if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);

same question.

Quoted 30 lines
arch/x86/kvm/vmx/vmx.c +3 -0
+	}
 #endif
 	load_fixmap_gdt(raw_smp_processor_id());
 	vmx->guest_state_loaded = false;
@@ -4889,6 +4904,8 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
 
 #ifdef CONFIG_X86_64
 	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = 0;
+
 		vmcs_write64(GUEST_IA32_FRED_CONFIG, 0);
 		vmcs_write64(GUEST_IA32_FRED_RSP1, 0);
 		vmcs_write64(GUEST_IA32_FRED_RSP2, 0);
arch/x86/kvm/vmx/vmx.h +2 -0
index 3ad52437f426..176ad39be406 100644
@@ -278,6 +278,8 @@ struct vcpu_vmx {
 #ifdef CONFIG_X86_64
 	u64		      msr_host_kernel_gs_base;
 	u64		      msr_guest_kernel_gs_base;
+	u64		      msr_host_fred_rsp0;
+	u64		      msr_guest_fred_rsp0;
 #endif
 
 	u64		      spec_ctrl;
Signature · 1 line
2.43.0
author
#33 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 7 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		if (unlikely(vmx->msr_host_fred_rsp0 == 0))
+			vmx->msr_host_fred_rsp0 =

read_msr(MSR_IA32_FRED_RSP0);

can we just drop this and use "(unsigned long)task_stack_page(current) + THREAD_SIZE"
as host fred rsp0?

I thought about it, however, don't see a strong reason that it's better,
i.e., is RDMSR slower than reading 'stack' from current task_struct?

Quoted 4 lines

arch/x86/kvm/vmx/vmx.c void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) · line 1348

Quoted 2 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);

any reason to not use wrmsrns?

Good call!

Quoted 6 lines

Review static void vmx_prepare_switch_to_host(struct

Quoted 5 lines
(quoted diff) +1 -0
+	}
#else
	savesegment(fs, fs_sel);
	savesegment(gs, gs_sel);
(quoted diff) +0 -0
@@ -1381,6 +1391,11 @@ static void vmx_prepare_switch_to_host(struct

vcpu_vmx *vmx)

Quoted 9 lines

arch/x86/kvm/vmx/vmx.c static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx) · line 1397

Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +4 -0
 	invalidate_tss_limit();
 #ifdef CONFIG_X86_64
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
+
+	if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);

same question.

Will do!

Thanks!
Xin

#34 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

In reply to Xin Li
Quoted 10 lines · Xin Li

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation: please use the user_return_msr() APIs.

Quoted 18 lines

---

Changes since v1:
* Don't use guest_cpuid_has() in vmx_prepare_switch_to_{host,guest}(), which are called from IRQ-disabled context (Chao Gao).
* Reset msr_guest_fred_rsp0 in __vmx_vcpu_reset() (Chao Gao).

---
 arch/x86/kvm/vmx/vmx.c | 17 +++++++++++++++++
 arch/x86/kvm/vmx/vmx.h |  2 ++
 2 files changed, 19 insertions(+)
arch/x86/kvm/vmx/vmx.c +0 -0
index b7b772183ee4..264378c3b784 100644

arch/x86/kvm/vmx/vmx.c void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) · line 1344

Quoted 8 lines
arch/x86/kvm/vmx/vmx.c +5 -0
@@ -1337,6 +1337,16 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 	}
 
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
+
+	if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
+		/*
+		 * MSR_IA32_FRED_RSP0 is top of task stack, which never changes.
+		 * Thus it should be initialized only once.

Then grab the host value during vmx_hardware_setup(). And when you rebase on top of the latest kvm-x86/next, there's a handy dandy "struct kvm_host_values kvm_host" to track host MSR values (and similar state).

You could also use that for MSR_IA32_FRED_CONFIG and MSR_IA32_FRED_STKLVLS.

Quoted 21 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+		 */
+		if (unlikely(vmx->msr_host_fred_rsp0 == 0))
+			vmx->msr_host_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
+	}
 #else
 	savesegment(fs, fs_sel);
 	savesegment(gs, gs_sel);
@@ -1381,6 +1391,11 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
 	invalidate_tss_limit();
 #ifdef CONFIG_X86_64
 	wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
+
+	if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);
+	}
 #endif
 	load_fixmap_gdt(raw_smp_processor_id());
 	vmx->guest_state_loaded = false;

arch/x86/kvm/vmx/vmx.c static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu) · line 4907

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +1 -0
@@ -4889,6 +4904,8 @@ static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
 
 #ifdef CONFIG_X86_64
 	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = 0;

Eh, I wouldn't bother. Arguably it's better to use __kvm_set_msr(), and "vmx" is zero-allocated so this is unnecessary.

The GUEST_IA32_FRED_* VMCS fields need to be explicitly initialized because the VMCS could (very theoretically) use a non-zero-based encoding scheme.

author
#35 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 8 lines · Xin Li
Quoted 7 lines

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

Quoted 6 lines
Quoted 2 lines

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation: please use the user_return_msr() APIs.

IIUC the user return MSR framework works for MSRs that are per CPU constants, but like MSR_KERNEL_GS_BASE, MSR_IA32_FRED_RSP0 is a per *task* constant, thus we can't use it.

#36 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 11 lines · On Wed, Jul 10, 2024, Xin3 Li wrote:
Quoted 11 lines · Xin Li
Quoted 9 lines

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Quoted 7 lines
Quoted 3 lines

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation: please use the user_return_msr() APIs.

IIUC the user return MSR framework works for MSRs that are per CPU constants, but like MSR_KERNEL_GS_BASE, MSR_IA32_FRED_RSP0 is a per *task* constant, thus we can't use it.

Ah, in that case, the changelog is very misleading and needs to be fixed. Alternatively, is the desired RSP0 value tracked anywhere other than the MSR? E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0. Even if we don't get fancy, avoiding the RDMSR to get the current task's value would be nice.

author
#37 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines
Quoted 9 lines

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation: please use the user_return_msr() APIs.

Quoted 5 lines
Quoted 3 lines

IIUC the user return MSR framework works for MSRs that are per CPU constants, but like MSR_KERNEL_GS_BASE, MSR_IA32_FRED_RSP0 is a per *task* constant, thus we can't use it.

Ah, in that case, the changelog is very misleading and needs to be fixed.

I probably should've given more details about how FRED RSPs are used:
RSP0 is a bit of special because it's a per task constant pointing to its kernel stack top, while other RSPs are per CPU constants.

Quoted 1 line

Alternatively, is the desired RSP0 value tracked anywhere other than the MSR?

Yes, It's simply "(unsigned long)task_stack_page(task) + THREAD_SIZE".

Quoted 2 lines

E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0.

So you're suggesting to extend the framework to allow per task constants?

Quoted 2 lines

Even if we don't get fancy, avoiding the RDMSR
to get the current task's value would be nice.

TBH, I didn't know RDMSR is NOT a preferred approach. But it does make sense because it costs hundreds cycles to read from CR2.

And of course this can be easily changed to "(unsigned long)task_stack_page(task) + THREAD_SIZE".

#38 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 9 lines · On Fri, Jul 12, 2024, Xin3 Li wrote:
Quoted 2 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line

Switch MSR_IA32_FRED_RSP0 between host and guest in

Alternatively, is the desired RSP0 value tracked anywhere other than the MSR?

Yes, It's simply "(unsigned long)task_stack_page(task) + THREAD_SIZE".

Quoted 2 lines

E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0.

So you're suggesting to extend the framework to allow per task constants?

Yeah, or more likely, special case MSR_IA32_FRED_RSP0. If KVM didn't already have the user return framework, I wouldn't suggest this as I doubt avoiding WRMSR when switching between vCPU tasks will be very meaningful, but it's easy to handle FRED_RSP0, so why not.

arch/x86/kvm/x86.c +10 -3
index 1783986d8626..ebecb205e5de 100644
@@ -352,6 +352,7 @@ static void kvm_on_user_return(struct user_return_notifier *urn)
                = container_of(urn, struct kvm_user_return_msrs, urn);
        struct kvm_user_return_msr_values *values;
        unsigned long flags;
+       u64 host_val;
 
        /*
         * Disabling irqs at this point since the following code could be
@@ -365,9 +366,15 @@ static void kvm_on_user_return(struct user_return_notifier *urn)
        local_irq_restore(flags);
        for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
                values = &msrs->values[slot];
-               if (values->host != values->curr) {
-                       wrmsrl(kvm_uret_msrs_list[slot], values->host);
-                       values->curr = values->host;
+
+               if (kvm_uret_msrs_list[slot] == MSR_IA32_FRED_RSP0)
+                       host_val = get_current_fred_rsp0();
+               else
+                       host_val = values->host;
+
+               if (host_val != values->curr) {
+                       wrmsrl(kvm_uret_msrs_list[slot], host_val);
+                       values->curr = host_val;
                }
        }
 }
author
#39 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 9 lines
Quoted 4 lines
Quoted 2 lines

E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0.

So you're suggesting to extend the framework to allow per task constants?

Yeah, or more likely, special case MSR_IA32_FRED_RSP0. If KVM didn't already have the user return framework, I wouldn't suggest this as I doubt avoiding WRMSR when switching between vCPU tasks will be very meaningful, but it's easy to handle FRED_RSP0, so why not.

Great, I will take the patch.

It looks to me that this also works for KERNEL GS BASE MSR, no?

Quoted 33 lines
arch/x86/kvm/x86.c index renamed from arch/x86/kvm/x86.c +0 -0

1783986d8626..ebecb205e5de 100644

arch/x86/kvm/x86.c +1 -0
@@ -352,6 +352,7 @@ static void kvm_on_user_return(struct
 user_return_notifier *urn)
                = container_of(urn, struct kvm_user_return_msrs, urn);
        struct kvm_user_return_msr_values *values;
        unsigned long flags;
+       u64 host_val;
 
        /*

* Disabling irqs at this point since the following code could be @@ -365,9
+366,15 @@ static void kvm_on_user_return(struct user_return_notifier *urn)

        local_irq_restore(flags);
        for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
                values = &msrs->values[slot];
arch/x86/kvm/x86.c +9 -3
-               if (values->host != values->curr) {
-                       wrmsrl(kvm_uret_msrs_list[slot], values->host);
-                       values->curr = values->host;
+
+               if (kvm_uret_msrs_list[slot] == MSR_IA32_FRED_RSP0)
+                       host_val = get_current_fred_rsp0();
+               else
+                       host_val = values->host;
+
+               if (host_val != values->curr) {
+                       wrmsrl(kvm_uret_msrs_list[slot], host_val);
+                       values->curr = host_val;
                }
        }
 }
#40 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 5 lines · On Fri, Jul 12, 2024, Xin3 Li wrote:
Quoted 5 lines
Quoted 4 lines
Quoted 2 lines

E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0.

So you're suggesting to extend the framework to allow per task constants?

Quoted 8 lines
Quoted 4 lines

Yeah, or more likely, special case MSR_IA32_FRED_RSP0. If KVM didn't already have the user return framework, I wouldn't suggest this as I doubt avoiding WRMSR when switching between vCPU tasks will be very meaningful, but it's easy to handle FRED_RSP0, so why not.

Great, I will take the patch.

It looks to me that this also works for KERNEL GS BASE MSR, no?

I don't think so, because the kernel expects MSR_KERNEL_GS_BASE to be accurate when querying GS.base for the current task:

unsigned long x86_gsbase_read_task(struct task_struct *task)

  {
	unsigned long gsbase;

	if (task == current)
		gsbase = x86_gsbase_read_cpu_inactive();
	else if (boot_cpu_has(X86_FEATURE_FSGSBASE) ||
		 (task->thread.gsindex == 0))
		gsbase = task->thread.gsbase;
	else
		gsbase = x86_fsgsbase_read_task(task, task->thread.gsindex);

	return gsbase;

}

author
#41 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

In reply to Li, Xin3
Quoted 11 lines
Quoted 9 lines
Quoted 4 lines
Quoted 2 lines

E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0.

So you're suggesting to extend the framework to allow per task constants?

Yeah, or more likely, special case MSR_IA32_FRED_RSP0. If KVM didn't already have the user return framework, I wouldn't suggest this as I doubt avoiding WRMSR when switching between vCPU tasks will be very meaningful, but it's easy to handle FRED_RSP0, so why not.

Great, I will take the patch.

I tried to make this work, however because FRED RSP0 is per task and keeps changing during context switch[1], we lose track of FRED RSP0 values from both host and guest, thus we need to:

1) *always* save guest FRED RSP0 in vmx_prepare_switch_to_host().

2) *always* restore guest FRED RSP0 in vmx_prepare_switch_to_guest(), because sometimes context switches happen but the CPU does NOT return to user mode thus the user return framework detects no change.

So it essentially becomes the same as what the original patch does.

I guess It's probably not worth the change, how do you think?

[1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=9356c4b8886c4f7d3436c3f7fe31715bdcf1c79e

Quoted 34 lines
Quoted 34 lines
arch/x86/kvm/x86.c index renamed from arch/x86/kvm/x86.c +0 -0

1783986d8626..ebecb205e5de 100644

arch/x86/kvm/x86.c +1 -0
@@ -352,6 +352,7 @@ static void kvm_on_user_return(struct
 user_return_notifier *urn)
                = container_of(urn, struct kvm_user_return_msrs, urn);
        struct kvm_user_return_msr_values *values;
        unsigned long flags;
+       u64 host_val;
 
        /*

* Disabling irqs at this point since the following code could
be @@ -365,9
+366,15 @@ static void kvm_on_user_return(struct user_return_notifier

arch/x86/kvm/x86.c +10 -3
+*urn)
        local_irq_restore(flags);
        for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
                values = &msrs->values[slot];
-               if (values->host != values->curr) {
-                       wrmsrl(kvm_uret_msrs_list[slot], values->host);
-                       values->curr = values->host;
+
+               if (kvm_uret_msrs_list[slot] == MSR_IA32_FRED_RSP0)
+                       host_val = get_current_fred_rsp0();
+               else
+                       host_val = values->host;
+
+               if (host_val != values->curr) {
+                       wrmsrl(kvm_uret_msrs_list[slot], host_val);
+                       values->curr = host_val;
                }
        }
 }
#42 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 10 lines · On Wed, Jul 17, 2024, Xin3 Li wrote:
Quoted 10 lines
Quoted 9 lines
Quoted 4 lines
Quoted 2 lines

E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0.

So you're suggesting to extend the framework to allow per task constants?

Yeah, or more likely, special case MSR_IA32_FRED_RSP0. If KVM didn't already have the user return framework, I wouldn't suggest this as I doubt avoiding WRMSR when switching between vCPU tasks will be very meaningful, but it's easy to handle FRED_RSP0, so why not.

Quoted 5 lines
Quoted 1 line

Great, I will take the patch.

I tried to make this work, however because FRED RSP0 is per task and keeps changing during context switch[1], we lose track of FRED RSP0 values from both host and guest,

Ah, right, the host value is volatile. And MSR_IA32_FRED_RSP0 is passed through to the guest, so the guest value is volatile/unknown too.

Quoted 11 lines

thus we need to:

1) *always* save guest FRED RSP0 in vmx_prepare_switch_to_host().

2) *always* restore guest FRED RSP0 in vmx_prepare_switch_to_guest(), because sometimes context switches happen but the CPU does NOT return to user mode thus the user return framework detects no change.

So it essentially becomes the same as what the original patch does.

I guess It's probably not worth the change, how do you think?

One idea would be to have the kernel write MSR_IA32_FRED_RSP0 on return to userspace instead of on context switch. As is, amusingly, there's no need to restore the host value if a context switch occurs as the kernel will have written the new task's value. RSP0 only needs to be manually restored if the kernel returns to userspace for the vCPU task. Using a TI flag to track if RSP0 needs to be loaded would avoid a fair number of WRMSRs in both KVM and the kernel.

E.g.

arch/x86/include/asm/entry-common.h +5 -0
index ce8f50192ae3..76724cc42869 100644
@@ -57,6 +57,11 @@ static inline void arch_exit_to_user_mode_prepare(struct pt_regs *regs,
        if (unlikely(ti_work & _TIF_NEED_FPU_LOAD))
                switch_fpu_return();
 
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           (ti_work & _TIF_NEED_RSP0_LOAD))
+               wrmsrns(MSR_IA32_FRED_RSP0,
+                       (unsigned long)task_stack_page(current) + THREAD_SIZE);
+
 #ifdef CONFIG_COMPAT
        /*
         * Compat syscalls set TS_COMPAT.  Make sure we clear it before
arch/x86/include/asm/switch_to.h +1 -2
index c3bd0c0758c9..1674d98a8850 100644
@@ -71,8 +71,7 @@ static inline void update_task_stack(struct task_struct *task)
        this_cpu_write(cpu_tss_rw.x86_tss.sp1, task->thread.sp0);
 #else
        if (cpu_feature_enabled(X86_FEATURE_FRED)) {
-               /* WRMSRNS is a baseline feature for FRED. */
-               wrmsrns(MSR_IA32_FRED_RSP0, (unsigned long)task_stack_page(task) + THREAD_SIZE);
+               set_thread_flag(TIF_NEED_RSP0_LOAD);
        } else if (cpu_feature_enabled(X86_FEATURE_XENPV)) {
                /* Xen PV enters the kernel on the thread stack. */
                load_sp0(task_top_of_stack(task));
arch/x86/kvm/vmx/vmx.c +6 -11
index 5c6bb26463e8..cb7e3bcb001f 100644
@@ -1338,15 +1338,9 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
 
-       if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
-               /*
-                * MSR_IA32_FRED_RSP0 is top of task stack, which never changes.
-                * Thus it should be initialized only once.
-                */
-               if (unlikely(vmx->msr_host_fred_rsp0 == 0))
-                       vmx->msr_host_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
-               wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
-       }
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           guest_can_use(vcpu, X86_FEATURE_FRED))
+               wrmsrns(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
 #else
        savesegment(fs, fs_sel);
        savesegment(gs, gs_sel);
@@ -1392,9 +1386,10 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
 #ifdef CONFIG_X86_64
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
 
-       if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
                vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
-               wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);
+               set_thread_flag(TIF_NEED_RSP0_LOAD);
        }
 #endif
        load_fixmap_gdt(raw_smp_processor_id());
author
#43 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 10 lines
Quoted 10 lines

thus we need to:

1) *always* save guest FRED RSP0 in vmx_prepare_switch_to_host().

2) *always* restore guest FRED RSP0 in vmx_prepare_switch_to_guest(), because sometimes context switches happen but the CPU does NOT return to user mode thus the user return framework detects no change.

So it essentially becomes the same as what the original patch does.

Quoted 8 lines
Quoted 1 line

I guess It's probably not worth the change, how do you think?

One idea would be to have the kernel write MSR_IA32_FRED_RSP0 on return to userspace instead of on context switch. As is, amusingly, there's no need to restore the host value if a context switch occurs as the kernel will have written the new task's value. RSP0 only needs to be manually restored if the kernel returns to userspace for the vCPU task. Using a TI flag to track if RSP0 needs to be loaded would avoid a fair number of WRMSRs in both KVM and the kernel.

I also thought about it (while in the FRED ERETU code path), however we will need performance data first, even an extra check (ti_work & _TIF_NEED_RSP0_LOAD) seems neglectable, but both return to user and context switch are hot paths, and I assume return to user is extremely hot.

So let's revisit it at a later time?

Quoted 42 lines
arch/x86/include/asm/entry-common.h +6 -0
index ce8f50192ae3..76724cc42869 100644
@@ -57,6 +57,11 @@ static inline void arch_exit_to_user_mode_prepare(struct
 pt_regs *regs,
        if (unlikely(ti_work & _TIF_NEED_FPU_LOAD))
                switch_fpu_return();
 
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           (ti_work & _TIF_NEED_RSP0_LOAD))
+               wrmsrns(MSR_IA32_FRED_RSP0,
+                       (unsigned long)task_stack_page(current) +
+ THREAD_SIZE);
+
 #ifdef CONFIG_COMPAT
        /*
         * Compat syscalls set TS_COMPAT.  Make sure we clear it before diff --git

a/arch/x86/include/asm/switch_to.h b/arch/x86/include/asm/switch_to.h index c3bd0c0758c9..1674d98a8850 100644

arch/x86/include/asm/switch_to.h +1 -2
@@ -71,8 +71,7 @@ static inline void update_task_stack(struct task_struct *task)
        this_cpu_write(cpu_tss_rw.x86_tss.sp1, task->thread.sp0);  #else
        if (cpu_feature_enabled(X86_FEATURE_FRED)) {
-               /* WRMSRNS is a baseline feature for FRED. */
-               wrmsrns(MSR_IA32_FRED_RSP0, (unsigned long)task_stack_page(task) +
 THREAD_SIZE);
+               set_thread_flag(TIF_NEED_RSP0_LOAD);
        } else if (cpu_feature_enabled(X86_FEATURE_XENPV)) {
                /* Xen PV enters the kernel on the thread stack. */
                load_sp0(task_top_of_stack(task));
arch/x86/kvm/vmx/vmx.c index renamed from arch/x86/kvm/vmx/vmx.c +0 -0

5c6bb26463e8..cb7e3bcb001f 100644

arch/x86/kvm/vmx/vmx.c +0 -0
@@ -1338,15 +1338,9 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu
 *vcpu)
 
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
 

arch/x86/kvm/vmx/vmx.c void vmx_prepare_switch_to_guest(struct kvm_vcpu · line 1342

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +1 -9
-       if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
-               /*
-                * MSR_IA32_FRED_RSP0 is top of task stack, which never changes.
-                * Thus it should be initialized only once.
-                */
-               if (unlikely(vmx->msr_host_fred_rsp0 == 0))
-                       vmx->msr_host_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
-               wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
-       }
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&

This check seems unnecessary, I guess you add it to skip the following code when FRED is not enabled on host?

Quoted 18 lines
arch/x86/kvm/vmx/vmx.c +2 -0
+           guest_can_use(vcpu, X86_FEATURE_FRED))
+               wrmsrns(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
 #else
        savesegment(fs, fs_sel);
        savesegment(gs, gs_sel);
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -1392,9 +1386,10 @@ static void vmx_prepare_switch_to_host(struct

vcpu_vmx *vmx) #ifdef CONFIG_X86_64

        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
arch/x86/kvm/vmx/vmx.c +3 -2
-       if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
                vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
-               wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);
+               set_thread_flag(TIF_NEED_RSP0_LOAD);
        }
 #endif
        load_fixmap_gdt(raw_smp_processor_id());
#44 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

In reply to Sean Christopherson
Quoted 20 lines · Sean Christopherson
Quoted 11 lines · On Wed, Jul 10, 2024, Xin3 Li wrote:
Quoted 11 lines · Xin Li
Quoted 9 lines

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Quoted 7 lines
Quoted 3 lines

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation: please use the user_return_msr() APIs.

IIUC the user return MSR framework works for MSRs that are per CPU constants, but like MSR_KERNEL_GS_BASE, MSR_IA32_FRED_RSP0 is a per *task* constant, thus we can't use it.

Quoted 5 lines

Ah, in that case, the changelog is very misleading and needs to be fixed. Alternatively, is the desired RSP0 value tracked anywhere other than the MSR? E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0. Even if we don't get fancy, avoiding the RDMSR to get the current task's value would be nice.

Hm, perhaps the right thing to do is to always invoke this function before a context switch happens if that happens before return to user space?

#45 lore raw

Re: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 21 lines · H. Peter Anvin
Quoted 20 lines · Sean Christopherson
Quoted 18 lines · On Wed, Jul 10, 2024, Xin3 Li wrote:
Quoted 8 lines · Xin Li
Quoted 7 lines

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM entry and exit.

Quoted 6 lines
Quoted 2 lines

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation: please use the user_return_msr() APIs.

IIUC the user return MSR framework works for MSRs that are per CPU constants, but like MSR_KERNEL_GS_BASE, MSR_IA32_FRED_RSP0 is a per *task* constant, thus we can't use it.

Quoted 8 lines
Quoted 5 lines

Ah, in that case, the changelog is very misleading and needs to be fixed. Alternatively, is the desired RSP0 value tracked anywhere other than the MSR? E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0. Even if we don't get fancy, avoiding the RDMSR to get the current task's value would be nice.

Hm, perhaps the right thing to do is to always invoke this function before a context switch happens if that happens before return to user space?

Actually, if the _TIF_NEED_RSP0_LOAD doesn't provide a meaningful benefit (or y'all just don't want it :-) ), what KVM could do is restore MSR_IA32_FRED_RSP0 when putting the vCPU and the vCPU is not being scheduled out, i.e. if and only if KVM can't guarantee a context switch.

If the vCPU/task is being scheduled out, update_task_stack() is guaranteed to write MSR_IA32_FRED_RSP0 with the new task's value.

On top of kvm/next, which adds the necessary vcpu->scheduled_out:

arch/x86/kvm/vmx/vmx.c +9 -11
index 5c6bb26463e8..4532ae943f2a 100644
@@ -1338,15 +1338,9 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
 
-       if (guest_can_use(vcpu, X86_FEATURE_FRED)) {
-               /*
-                * MSR_IA32_FRED_RSP0 is top of task stack, which never changes.
-                * Thus it should be initialized only once.
-                */
-               if (unlikely(vmx->msr_host_fred_rsp0 == 0))
-                       vmx->msr_host_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
-               wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
-       }
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           guest_can_use(vcpu, X86_FEATURE_FRED))
+               wrmsrns(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
 #else
        savesegment(fs, fs_sel);
        savesegment(gs, gs_sel);
@@ -1392,9 +1386,13 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
 #ifdef CONFIG_X86_64
        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
 
-       if (guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
+       if (cpu_feature_enabled(X86_FEATURE_FRED) &&
+           guest_can_use(&vmx->vcpu, X86_FEATURE_FRED)) {
                vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
-               wrmsrl(MSR_IA32_FRED_RSP0, vmx->msr_host_fred_rsp0);
+
+               if (!vcpu->scheduled_out)
+                       wrmsrns(MSR_IA32_FRED_RSP0,
+                                (unsigned long)task_stack_page(task) + THREAD_SIZE);
        }
 #endif
        load_fixmap_gdt(raw_smp_processor_id());
author
#46 lore raw

RE: [PATCH v2 09/25] KVM: VMX: Switch FRED RSP0 between host and guest

Quoted 32 lines · H. Peter Anvin
Quoted 1 line

On July 12, 2024 8:12:51 AM PDT, Sean Christopherson <[email protected]>

Quoted 8 lines · wrote:
Quoted 8 lines · On Wed, Jul 10, 2024, Xin3 Li wrote:
Quoted 7 lines
Quoted 7 lines · Xin Li
Quoted 6 lines

Switch MSR_IA32_FRED_RSP0 between host and guest in vmx_prepare_switch_to_{host,guest}().

MSR_IA32_FRED_RSP0 is used during ring 3 event delivery only, thus KVM, running on ring 0, can run safely with guest FRED RSP0, i.e., no need to switch between host/guest FRED RSP0 during VM

entry and exit.

Quoted 19 lines
Quoted 18 lines
Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

KVM should switch to host FRED RSP0 before returning to user level, and switch to guest FRED RSP0 before entering guest mode.

Quoted 8 lines
Quoted 4 lines

Heh, if only KVM had a framework that was specifically designed for context switching MSRs on return to userspace. Translation:
please use the
user_return_msr() APIs.

IIUC the user return MSR framework works for MSRs that are per CPU constants, but like MSR_KERNEL_GS_BASE, MSR_IA32_FRED_RSP0 is a per *task* constant, thus we can't use it.

Ah, in that case, the changelog is very misleading and needs to be fixed. Alternatively, is the desired RSP0 value tracked anywhere other than the MSR? E.g. if it's somewhere in task_struct, then kvm_on_user_return() would restore the current task's desired RSP0. Even if we don't get fancy, avoiding the RDMSR to get the current task's value would be nice.

Quoted 5 lines
Quoted 2 lines

Hm, perhaps the right thing to do is to always invoke this function before a context switch happens if that happens before return to user space?

Actually, if the _TIF_NEED_RSP0_LOAD doesn't provide a meaningful benefit (or y'all just don't want it :-) ),

We want it 😊.

My concern was adding an extra check of (ti_work & _TIF_NEED_RSP0_LOAD) into a hot function arch_exit_to_user_mode_prepare(). HPA checked the function and suggested to test ti_work for zero and then process individual bits in it:

arch/x86/include/asm/entry-common.h +9 -7
index fb2809b20b0a..4c78b99060b5 100644
@@ -47,15 +47,17 @@ static __always_inline void arch_enter_from_user_mode(struct pt_regs *regs)
 static inline void arch_exit_to_user_mode_prepare(struct pt_regs *regs,
                                                  unsigned long ti_work)
 {
-       if (ti_work & _TIF_USER_RETURN_NOTIFY)
-               fire_user_return_notifiers();
+       if (ti_work) {
+               if (ti_work & _TIF_USER_RETURN_NOTIFY)
+                       fire_user_return_notifiers();
 
-       if (unlikely(ti_work & _TIF_IO_BITMAP))
-               tss_update_io_bitmap();
+               if (unlikely(ti_work & _TIF_IO_BITMAP))
+                       tss_update_io_bitmap();
 
-       fpregs_assert_state_consistent();
-       if (unlikely(ti_work & _TIF_NEED_FPU_LOAD))
-               switch_fpu_return();
+               fpregs_assert_state_consistent();
+               if (unlikely(ti_work & _TIF_NEED_FPU_LOAD))
+                       switch_fpu_return();
+       }
 
 #ifdef CONFIG_COMPAT
        /*

Based on it, I measured how many 0s are out of every one million ti_work values in kernel build tests, it's over 99%, i.e., unlikely(ti_work).

When booting a KVM guest, it becomes 75%, which is expected. After the guest is up running kernel build in it, it's 99% again.

So at least this patch seems a low-hanging fruit, and I have sent it to Intel 0day for broader perf tests.

As context switches are way less frequent than exit to user mode, I do NOT expect it makes a difference to write MSR_IA32_FRED_RSP0 on exit to user mode instead of on context switch especially when we do it on top of the above patch.

author
#47 lore raw

PATCH v2 10/25 KVM: VMX: Add support for FRED context save/restore

In reply to Xin Li

Handle host initiated FRED MSR access requests to allow FRED context to be set/get from user level.

During VM save/restore and live migration, FRED context needs to be saved/restored, which requires FRED MSRs to be accessed from a user level application, e.g., Qemu.

Note, handling of MSR_IA32_FRED_SSP0, i.e., MSR_IA32_PL0_SSP, is not added yet, which is done in the KVM CET patch set.

---

Changes since v1:
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() (Chao Gao).
* Fail host requested FRED MSRs access if KVM cannot virtualize FRED (Chao Gao).
* Handle the case FRED MSRs are valid but KVM cannot virtualize FRED (Chao Gao).
* Add sanity checks when writing to FRED MSRs.

---
 arch/x86/kvm/vmx/vmx.c | 72 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/x86.c     | 47 +++++++++++++++++++++++++++
 2 files changed, 119 insertions(+)
arch/x86/kvm/vmx/vmx.c +72 -0
index 264378c3b784..ee61d2c25cb0 100644
@@ -1420,6 +1420,24 @@ static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
 	preempt_enable();
 	vmx->msr_guest_kernel_gs_base = data;
 }
+
+static u64 vmx_read_guest_fred_rsp0(struct vcpu_vmx *vmx)
+{
+	preempt_disable();
+	if (vmx->guest_state_loaded)
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+	preempt_enable();
+	return vmx->msr_guest_fred_rsp0;
+}
+
+static void vmx_write_guest_fred_rsp0(struct vcpu_vmx *vmx, u64 data)
+{
+	preempt_disable();
+	if (vmx->guest_state_loaded)
+		wrmsrl(MSR_IA32_FRED_RSP0, data);
+	preempt_enable();
+	vmx->msr_guest_fred_rsp0 = data;
+}
 #endif
 
 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
@@ -2019,6 +2037,33 @@ static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 	case MSR_KERNEL_GS_BASE:
 		msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
 		break;
+	case MSR_IA32_FRED_RSP0:
+		msr_info->data = vmx_read_guest_fred_rsp0(vmx);
+		break;
+	case MSR_IA32_FRED_RSP1:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_RSP1);
+		break;
+	case MSR_IA32_FRED_RSP2:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_RSP2);
+		break;
+	case MSR_IA32_FRED_RSP3:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_RSP3);
+		break;
+	case MSR_IA32_FRED_STKLVLS:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_STKLVLS);
+		break;
+	case MSR_IA32_FRED_SSP1:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_SSP1);
+		break;
+	case MSR_IA32_FRED_SSP2:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_SSP2);
+		break;
+	case MSR_IA32_FRED_SSP3:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_SSP3);
+		break;
+	case MSR_IA32_FRED_CONFIG:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_CONFIG);
+		break;
 #endif
 	case MSR_EFER:
 		return kvm_get_msr_common(vcpu, msr_info);
@@ -2226,6 +2271,33 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 			vmx_update_exception_bitmap(vcpu);
 		}
 		break;
+	case MSR_IA32_FRED_RSP0:
+		vmx_write_guest_fred_rsp0(vmx, data);
+		break;
+	case MSR_IA32_FRED_RSP1:
+		vmcs_write64(GUEST_IA32_FRED_RSP1, data);
+		break;
+	case MSR_IA32_FRED_RSP2:
+		vmcs_write64(GUEST_IA32_FRED_RSP2, data);
+		break;
+	case MSR_IA32_FRED_RSP3:
+		vmcs_write64(GUEST_IA32_FRED_RSP3, data);
+		break;
+	case MSR_IA32_FRED_STKLVLS:
+		vmcs_write64(GUEST_IA32_FRED_STKLVLS, data);
+		break;
+	case MSR_IA32_FRED_SSP1:
+		vmcs_write64(GUEST_IA32_FRED_SSP1, data);
+		break;
+	case MSR_IA32_FRED_SSP2:
+		vmcs_write64(GUEST_IA32_FRED_SSP2, data);
+		break;
+	case MSR_IA32_FRED_SSP3:
+		vmcs_write64(GUEST_IA32_FRED_SSP3, data);
+		break;
+	case MSR_IA32_FRED_CONFIG:
+		vmcs_write64(GUEST_IA32_FRED_CONFIG, data);
+		break;
 #endif
 	case MSR_IA32_SYSENTER_CS:
 		if (is_guest_mode(vcpu))
arch/x86/kvm/x86.c +47 -0

71 lines not on this page · raw message

Signature · 1 line
2.43.0
#48 lore raw

Re: [PATCH v2 10/25] KVM: VMX: Add support for FRED context save/restore

Quoted 3 lines · Xin Li

Handle host initiated FRED MSR access requests to allow FRED context to be set/get from user level.

The changelog isn't accurate because guest accesses are also handled by this patch, specifically in the "else" branch.

	>+		if (host_initiated) {
	>+			if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
	>+				return 1;
	>+		} else {
Quoted 22 lines

void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,

arch/x86/kvm/vmx/vmx.c +17 -0
@@ -2019,6 +2037,33 @@ static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 	case MSR_KERNEL_GS_BASE:
 		msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
 		break;
+	case MSR_IA32_FRED_RSP0:
+		msr_info->data = vmx_read_guest_fred_rsp0(vmx);
+		break;
+	case MSR_IA32_FRED_RSP1:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_RSP1);
+		break;
+	case MSR_IA32_FRED_RSP2:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_RSP2);
+		break;
+	case MSR_IA32_FRED_RSP3:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_RSP3);
+		break;
+	case MSR_IA32_FRED_STKLVLS:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_STKLVLS);
+		break;
+	case MSR_IA32_FRED_SSP1:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_SSP1);

arch/x86/kvm/vmx/vmx.c static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) · line 2066

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+		break;
+	case MSR_IA32_FRED_SSP2:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_SSP2);
+		break;
+	case MSR_IA32_FRED_SSP3:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_SSP3);
+		break;
+	case MSR_IA32_FRED_CONFIG:
+		msr_info->data = vmcs_read64(GUEST_IA32_FRED_CONFIG);
+		break;

how about adding a helper function to convert MSR index to the VMCS field id? Then do:

	case MSR_IA32_FRED_RSP1 ... MSR_IA32_FRED_STKLVLS:
	case MSR_IA32_FRED_SSP1 ... MSR_IA32_FRED_CONFIG:
		msr_info->data = vmcs_read64(msr_to_vmcs(index));
		break;

and ...

Quoted 24 lines
arch/x86/kvm/vmx/vmx.c +17 -0
 #endif
 	case MSR_EFER:
 		return kvm_get_msr_common(vcpu, msr_info);
@@ -2226,6 +2271,33 @@ static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 			vmx_update_exception_bitmap(vcpu);
 		}
 		break;
+	case MSR_IA32_FRED_RSP0:
+		vmx_write_guest_fred_rsp0(vmx, data);
+		break;
+	case MSR_IA32_FRED_RSP1:
+		vmcs_write64(GUEST_IA32_FRED_RSP1, data);
+		break;
+	case MSR_IA32_FRED_RSP2:
+		vmcs_write64(GUEST_IA32_FRED_RSP2, data);
+		break;
+	case MSR_IA32_FRED_RSP3:
+		vmcs_write64(GUEST_IA32_FRED_RSP3, data);
+		break;
+	case MSR_IA32_FRED_STKLVLS:
+		vmcs_write64(GUEST_IA32_FRED_STKLVLS, data);
+		break;
+	case MSR_IA32_FRED_SSP1:
+		vmcs_write64(GUEST_IA32_FRED_SSP1, data);

arch/x86/kvm/vmx/vmx.c static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) · line 2300

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+		break;
+	case MSR_IA32_FRED_SSP2:
+		vmcs_write64(GUEST_IA32_FRED_SSP2, data);
+		break;
+	case MSR_IA32_FRED_SSP3:
+		vmcs_write64(GUEST_IA32_FRED_SSP3, data);
+		break;
+	case MSR_IA32_FRED_CONFIG:
+		vmcs_write64(GUEST_IA32_FRED_CONFIG, data);
+		break;
	case MSR_IA32_FRED_RSP1 ... MSR_IA32_FRED_STKLVLS:
	case MSR_IA32_FRED_SSP1 ... MSR_IA32_FRED_CONFIG:
		vmcs_write64(msr_to_vmcs(index), data);
		break;

The code will be more compact and generate less instructions. I believe CET series can do the same change [*]. Performance here isn't critical. I just think it looks cumbersome to repeat the same pattern for 8 (and more with CET considered) MSRs.

[*]: https://lore.kernel.org/kvm/[email protected]/

Quoted 25 lines
arch/x86/kvm/vmx/vmx.c +0 -0
 #endif
 	case MSR_IA32_SYSENTER_CS:
 		if (is_guest_mode(vcpu))
arch/x86/kvm/x86.c +7 -0
index 363b1c080205..4e8d60f248e3 100644
@@ -1451,6 +1451,9 @@ static const u32 msrs_to_save_base[] = {
 	MSR_STAR,
 #ifdef CONFIG_X86_64
 	MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
+	MSR_IA32_FRED_RSP0, MSR_IA32_FRED_RSP1, MSR_IA32_FRED_RSP2,
+	MSR_IA32_FRED_RSP3, MSR_IA32_FRED_STKLVLS, MSR_IA32_FRED_SSP1,
+	MSR_IA32_FRED_SSP2, MSR_IA32_FRED_SSP3, MSR_IA32_FRED_CONFIG,
 #endif
 	MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
 	MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
@@ -1892,6 +1895,30 @@ static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
 			return 1;
 
 		data = (u32)data;
+		break;
+	case MSR_IA32_FRED_RSP0 ... MSR_IA32_FRED_CONFIG:
+		if (index != MSR_IA32_FRED_STKLVLS && is_noncanonical_address(data, vcpu))
+			return 1;

arch/x86/kvm/x86.c static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data, · line 1911

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+		if ((index >= MSR_IA32_FRED_RSP0 && index <= MSR_IA32_FRED_RSP3) &&
+		    (data & GENMASK_ULL(5, 0)))
+			return 1;
+		if ((index >= MSR_IA32_FRED_SSP1 && index <= MSR_IA32_FRED_SSP3) &&
+		    (data & GENMASK_ULL(2, 0)))
+			return 1;
+
+		if (host_initiated) {
+			if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+				return 1;

Should be:

			if (!kvm_cpu_cap_has(X86_FEATURE_FRED) && data)

KVM ABI allows userspace to write only 0 if guests cannot enumerate the feature. And even better, your next version can be on top of Sean's series

https://lore.kernel.org/kvm/[email protected]/T/#md00be687770e1e658fc9fe0eac20b5f0bd230e4c

this way, you can get rid of the "host_initiated" check.

#49 lore raw

Re: [PATCH v2 10/25] KVM: VMX: Add support for FRED context save/restore

In reply to Xin Li
Quoted 16 lines · Xin Li
arch/x86/kvm/vmx/vmx.c +8 -0
index 264378c3b784..ee61d2c25cb0 100644
@@ -1420,6 +1420,24 @@ static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
 	preempt_enable();
 	vmx->msr_guest_kernel_gs_base = data;
 }
+
+static u64 vmx_read_guest_fred_rsp0(struct vcpu_vmx *vmx)
+{
+	preempt_disable();
+	if (vmx->guest_state_loaded)
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+	preempt_enable();
+	return vmx->msr_guest_fred_rsp0;

arch/x86/kvm/vmx/vmx.c static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data) · line 1440

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+}
+
+static void vmx_write_guest_fred_rsp0(struct vcpu_vmx *vmx, u64 data)
+{
+	preempt_disable();
+	if (vmx->guest_state_loaded)
+		wrmsrl(MSR_IA32_FRED_RSP0, data);
+	preempt_enable();
+	vmx->msr_guest_fred_rsp0 = data;
+}

This should be unnecessary when you switch to the user return framework.

KERNEL_GS_BASE is a bit special because it needs to be reloaded if the kernel switches to a different task, i.e. before an exit to userspace.

Quoted 14 lines
arch/x86/kvm/vmx/vmx.c +10 -0
@@ -1892,6 +1895,30 @@ static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data,
 			return 1;
 
 		data = (u32)data;
+		break;
+	case MSR_IA32_FRED_RSP0 ... MSR_IA32_FRED_CONFIG:
+		if (index != MSR_IA32_FRED_STKLVLS && is_noncanonical_address(data, vcpu))
+			return 1;
+		if ((index >= MSR_IA32_FRED_RSP0 && index <= MSR_IA32_FRED_RSP3) &&
+		    (data & GENMASK_ULL(5, 0)))
+			return 1;
+		if ((index >= MSR_IA32_FRED_SSP1 && index <= MSR_IA32_FRED_SSP3) &&
+		    (data & GENMASK_ULL(2, 0)))
+			return 1;

arch/x86/kvm/vmx/vmx.c static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data, · line 1917

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+
+		if (host_initiated) {
+			if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+				return 1;
+		} else {
+			/*
+			 * Inject #GP upon FRED MSRs accesses from a non-FRED guest,
+			 * which also ensures no malicious guest can write to FRED
+			 * MSRs to corrupt host FRED MSRs.
+			 */

Drop the comment, if someone reading KVM code doesn't grok that attempting to access MSRs that shouldn't exist results in #GP, then a comment probably isn't going to save them.

This should also be bumped to the top, i.e. do the "does this exist check" first.

Lastly, the direction we are taking is to NOT exempt host-initiated writes, i.e. userspace has to set CPUID before MSRs. If you base the next version on top of this series, it should just work (and if it doesn't, I definitely want to know):

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

arch/x86/kvm/vmx/vmx.c static int __kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data, · line 1921

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+			if (!guest_can_use(vcpu, X86_FEATURE_FRED))
+				return 1;
+		}
+

Uh, where does the value go? Oh, this is common code. Ah, and it's in common code so that VMX can avoid having to make an extra function call for every MSR. Neat.

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +3 -0
 		break;
 	}
 
@@ -1936,6 +1963,22 @@ int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data,
 		    !guest_cpuid_has(vcpu, X86_FEATURE_RDPID))
 			return 1;
 		break;
+	case MSR_IA32_FRED_RSP0 ... MSR_IA32_FRED_CONFIG:
+		if (host_initiated) {
+			if (!kvm_cpu_cap_has(X86_FEATURE_FRED))

arch/x86/kvm/vmx/vmx.c int __kvm_get_msr(struct kvm_vcpu *vcpu, u32 index, u64 *data, · line 1978

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+				return 1;
+		} else {
+			/*
+			 * Inject #GP upon FRED MSRs accesses from a non-FRED guest,
+			 * which also ensures no malicious guest can write to FRED
+			 * MSRs to corrupt host FRED MSRs.
+			 */
+			if (!guest_can_use(vcpu, X86_FEATURE_FRED))
+				return 1;
+		}

Same comments here.

author
#50 lore raw

PATCH v2 11/25 KVM: x86: Add kvm_is_fred_enabled()

In reply to Xin Li

Add kvm_is_fred_enabled() to get if FRED is enabled on a vCPU.

---

Change since v1:
* Explain why it is ok to only check CR4.FRED (Chao Gao).

---
 arch/x86/kvm/kvm_cache_regs.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
arch/x86/kvm/kvm_cache_regs.h +17 -0
index 75eae9c4998a..1d431c703fdf 100644
@@ -187,6 +187,23 @@ static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu,
 	return !!kvm_read_cr4_bits(vcpu, cr4_bit);
 }
 
+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ *
+ * More details at FRED Spec 6.0 Section 4.2 Enabling in CR4.
+ */
+static __always_inline bool kvm_is_fred_enabled(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_X86_64
+	return kvm_is_cr4_bit_set(vcpu, X86_CR4_FRED);
+#else
+	return false;
+#endif
+}
+
 static inline ulong kvm_read_cr3(struct kvm_vcpu *vcpu)
 {
 	if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
Signature · 1 line
2.43.0
#51 lore raw

Re: [PATCH v2 11/25] KVM: x86: Add kvm_is_fred_enabled()

Quoted 18 lines · Xin Li

Add kvm_is_fred_enabled() to get if FRED is enabled on a vCPU.

---

Change since v1:
* Explain why it is ok to only check CR4.FRED (Chao Gao).
---
arch/x86/kvm/kvm_cache_regs.h | 17 +++++++++++++++++

1 file changed, 17 insertions(+)
arch/x86/kvm/kvm_cache_regs.h +0 -0
index 75eae9c4998a..1d431c703fdf 100644
@@ -187,6 +187,23 @@ static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu,
 	return !!kvm_read_cr4_bits(vcpu, cr4_bit);

arch/x86/kvm/kvm_cache_regs.h static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu, · line 197

Quoted 10 lines
arch/x86/kvm/kvm_cache_regs.h +8 -0
 }
 
+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ *
+ * More details at FRED Spec 6.0 Section 4.2 Enabling in CR4.
+ */

I think we can give more context here, e.g.,

Although FRED architecture applies to 64-bit mode only, there is no need to check if the CPU is in 64-bit mode (i.e., IA32_EFER.LMA and CS.L) to tell if FRED is enabled because CR4.FRED=1 implies the CPU is in 64-bit mode. Specifically,

1) ..
2) ..

author
#52 lore raw

RE: [PATCH v2 11/25] KVM: x86: Add kvm_is_fred_enabled()

Quoted 9 lines
Quoted 8 lines

+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ *
+ * More details at FRED Spec 6.0 Section 4.2 Enabling in CR4.
+ */

Quoted 5 lines

I think we can give more context here, e.g.,

Although FRED architecture applies to 64-bit mode only, there is no need to check if the CPU is in 64-bit mode (i.e., IA32_EFER.LMA and CS.L) to tell if FRED is enabled because CR4.FRED=1 implies the CPU is in 64-bit mode.

What is "more context" here?

Quoted 1 line

Specifically,

#53 lore raw

Re: [PATCH v2 11/25] KVM: x86: Add kvm_is_fred_enabled()

Quoted 9 lines · On Sat, May 11, 2024 at 09:24:12AM +0800, Li, Xin3 wrote:
Quoted 9 lines
Quoted 8 lines

+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ *
+ * More details at FRED Spec 6.0 Section 4.2 Enabling in CR4.
+ */

Quoted 7 lines
Quoted 5 lines

I think we can give more context here, e.g.,

Although FRED architecture applies to 64-bit mode only, there is no need to check if the CPU is in 64-bit mode (i.e., IA32_EFER.LMA and CS.L) to tell if FRED is enabled because CR4.FRED=1 implies the CPU is in 64-bit mode.

What is "more context" here?

e.g.,
why IA32_EFER.LMA and CPU mode are related to FRED here?

"it's enough to " implies something else is not necessary. what is it?

I don't think the original comment make them super clear.

Quoted 4 lines
Quoted 2 lines

Specifically,

#54 lore raw

Re: [PATCH v2 11/25] KVM: x86: Add kvm_is_fred_enabled()

In reply to Xin Li
Quoted 19 lines · Xin Li

Add kvm_is_fred_enabled() to get if FRED is enabled on a vCPU.

---

Change since v1:
* Explain why it is ok to only check CR4.FRED (Chao Gao).

---
 arch/x86/kvm/kvm_cache_regs.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
arch/x86/kvm/kvm_cache_regs.h +0 -0
index 75eae9c4998a..1d431c703fdf 100644
@@ -187,6 +187,23 @@ static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu,
 	return !!kvm_read_cr4_bits(vcpu, cr4_bit);
 }

arch/x86/kvm/kvm_cache_regs.h static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu, · line 198

Quoted 10 lines
arch/x86/kvm/kvm_cache_regs.h +9 -0
 
+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ *
+ * More details at FRED Spec 6.0 Section 4.2 Enabling in CR4.
+ */
+static __always_inline bool kvm_is_fred_enabled(struct kvm_vcpu *vcpu)

Maybe just is_fred_enabled(), or even just is_fred()? Most helpers in x86.h that wrap CR4/CR0 in similar ways omit the "kvm_", partly for brevity, but also because the check is architectural, not KVM-defined (though the state obviously comes from KVM).

Quoted 14 lines
arch/x86/kvm/kvm_cache_regs.h +8 -0
+{
+#ifdef CONFIG_X86_64
+	return kvm_is_cr4_bit_set(vcpu, X86_CR4_FRED);
+#else
+	return false;
+#endif
+}
+
 static inline ulong kvm_read_cr3(struct kvm_vcpu *vcpu)
 {
 	if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
Signature · 1 line
2.43.0
#55 lore raw

Re: [PATCH v2 11/25] KVM: x86: Add kvm_is_fred_enabled()

In reply to Xin Li
Quoted 17 lines · Xin Li

Add kvm_is_fred_enabled() to get if FRED is enabled on a vCPU.

---

Change since v1:
* Explain why it is ok to only check CR4.FRED (Chao Gao).

---
 arch/x86/kvm/kvm_cache_regs.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
arch/x86/kvm/kvm_cache_regs.h +0 -0
index 75eae9c4998a..1d431c703fdf 100644

arch/x86/kvm/kvm_cache_regs.h static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu, · line 196

Quoted 10 lines
arch/x86/kvm/kvm_cache_regs.h +7 -0
@@ -187,6 +187,23 @@ static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu,
 	return !!kvm_read_cr4_bits(vcpu, cr4_bit);
 }
 
+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ *
+ * More details at FRED Spec 6.0 Section 4.2 Enabling in CR4.

Please don't reference specific sections/tables/fields in comments. They always become stale. And the code+comments always reflect the current state, i.e. don't need to worry about spec revisions and whatnot. If there is a spec change, then there darn well needs to be a way for software to differentiate old vs. new, at which point there will be accompanying code to capture the difference.

Even in changelogs, references specific specs by section number is usually discouraged. Again, it shouldn't matter if its FRED spec 6.0 vs. spec 5.0, because if there is a difference between those two, then the code better be different too.

Instead, for the changelog, if it's really necessary/helpful, reference the section by name and/or keyword, as those are much less likely to become stale.

arch/x86/kvm/kvm_cache_regs.h static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu, · line 198

Quoted 2 lines
arch/x86/kvm/kvm_cache_regs.h +2 -0
+ */
+static __always_inline bool kvm_is_fred_enabled(struct kvm_vcpu *vcpu)

This doesn't need to be __always_inline, it's not used from a noinstr section. kvm_is_cr4_bit_set() is __always_inline so that @cr4_bit is guaranteed to be a compile-time constant, otherwise the BUILD_BUG_ON() would fail.

author
#56 lore raw

PATCH v2 12/25 KVM: VMX: Handle FRED event data

In reply to Xin Li

Set injected-event data when injecting a #PF, #DB, or #NM caused by extended feature disable using FRED event delivery, and save original-event data for being used as injected-event data.

Unlike IDT using some extra CPU register as part of an event context, e.g., %cr2 for #PF, FRED saves a complete event context in its stack frame, e.g., FRED saves the faulting linear address of a #PF into the event data field defined in its stack frame.

Thus a new VMX control field called injected-event data is added to provide the event data that will be pushed into a FRED stack frame for VM entries that inject an event using FRED event delivery. In addition, a new VM exit information field called original-event data is added to store the event data that would have saved into a FRED stack frame for VM exits that occur during FRED event delivery. After such a VM exit is handled to allow the original-event to be delivered, the data in the original-event data VMCS field needs to be set into the injected-event data VMCS field for the injection of the original event.

---

Change since v1:
* Document event data should be equal to CR2/DR6/IA32_XFD_ERR instead of using WARN_ON() (Chao Gao).
* Zero event data if a #NM was not caused by extended feature disable (Chao Gao).

---
 arch/x86/include/asm/vmx.h |   4 ++
 arch/x86/kvm/vmx/vmx.c     | 109 ++++++++++++++++++++++++++++---------
 arch/x86/kvm/vmx/vmx.h     |   1 +
 arch/x86/kvm/x86.c         |  10 +++-
 4 files changed, 95 insertions(+), 29 deletions(-)
arch/x86/include/asm/vmx.h +4 -0
index 4889754415b5..6b796c5c9c2b 100644
@@ -256,8 +256,12 @@ enum vmcs_field {
 	PID_POINTER_TABLE_HIGH		= 0x00002043,
 	SECONDARY_VM_EXIT_CONTROLS	= 0x00002044,
 	SECONDARY_VM_EXIT_CONTROLS_HIGH	= 0x00002045,
+	INJECTED_EVENT_DATA		= 0x00002052,
+	INJECTED_EVENT_DATA_HIGH	= 0x00002053,
 	GUEST_PHYSICAL_ADDRESS          = 0x00002400,
 	GUEST_PHYSICAL_ADDRESS_HIGH     = 0x00002401,
+	ORIGINAL_EVENT_DATA		= 0x00002404,
+	ORIGINAL_EVENT_DATA_HIGH	= 0x00002405,
 	VMCS_LINK_POINTER               = 0x00002800,
 	VMCS_LINK_POINTER_HIGH          = 0x00002801,
 	GUEST_IA32_DEBUGCTL             = 0x00002802,
arch/x86/kvm/vmx/vmx.c +82 -27

162 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.h +1 -0
index 176ad39be406..d5738c5a4814 100644
@@ -266,6 +266,7 @@ struct vcpu_vmx {
 	u32                   exit_intr_info;
 	u32                   idt_vectoring_info;
 	ulong                 rflags;
+	u64                   fred_xfd_event_data;
 
 	/*
 	 * User return MSRs are always emulated when enabled in the guest, but
arch/x86/kvm/x86.c +8 -2
index 4e8d60f248e3..00c0062726ae 100644
@@ -680,8 +680,14 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
 			vcpu->arch.exception.injected = true;
 			if (WARN_ON_ONCE(has_payload)) {
 				/*
-				 * A reinjected event has already
-				 * delivered its payload.
+				 * For a reinjected event, KVM delivers its
+				 * payload through:
+				 *   #PF: save %cr2 into arch.cr2 immediately
+				 *        after VM exits.
+				 *   #DB: save %dr6 into arch.dr6 later in
+				 *        sync_dirty_debug_regs().
+				 *
+				 * For FRED guest, see __vmx_complete_interrupts().
 				 */
 				has_payload = false;
 				payload = 0;
Signature · 1 line
2.43.0
#57 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 17 lines

index ee61d2c25cb0..f622fb90a098 100644

arch/x86/kvm/vmx/vmx.c +7 -1
@@ -1871,9 +1871,29 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
               vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
                            vmx->vcpu.arch.event_exit_inst_len);
               intr_info |= INTR_TYPE_SOFT_EXCEPTION;
-       } else
+       } else {
               intr_info |= INTR_TYPE_HARD_EXCEPTION;
 
+               if (kvm_is_fred_enabled(vcpu)) {
+                       u64 event_data = 0;
+
+                       if (is_debug(intr_info))
+                               /*
+                                * Compared to DR6, FRED #DB event data saved on

arch/x86/kvm/vmx/vmx.c static void vmx_inject_exception(struct kvm_vcpu *vcpu) · line 1892

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+                                * the stack frame have bits 4 ~ 11 and 16 ~ 31
+                                * inverted, i.e.,
+                                *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+                                */
+                               event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+                       else if (is_page_fault(intr_info))
+                               event_data = vcpu->arch.cr2;
+                       else if (is_nm_fault(intr_info))
+                               event_data = to_vmx(vcpu)->fred_xfd_event_data;
+

IMO, deriving an event_data from CR2/DR6 is a little short-sighted because the event_data and CR2/DR6 __can__ be different, e.g., L1 VMM __can__ set CR2 to A and event_data field to B (!=A) when injecting #PF.

And this approach cannot be extended to handle a (future) exception whose event_data isn't tied to a dedicated register like CR2/DR6.

Adding a new field fred_xfd_event_data in struct vcpu has problems too:
fred_xfd_event_data gets lost during migration; strickly speaking, event_data is tied to an exception rather than a CPU. e.g., the CPU may detect a nested exception when delivering one and both have their own event_data.

I think we can make event_data a property of exceptions. i.e., add a payload2 to struct kvm_queued_exception. and add new APIs to kvm_queue_exception* family to accept a payload2 and in VMX code, just program payload2 to the VMCS event_data field if FRED is enabled. KVM ABI should be extended as well to pass payload2 to userspace like how the payload is handled in kvm_vcpu_ioctl_x86_get/put_vcpu_events.

author
#58 lore raw

RE: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 13 lines
Quoted 13 lines
arch/x86/kvm/vmx/vmx.c +13 -0
+               if (kvm_is_fred_enabled(vcpu)) {
+                       u64 event_data = 0;
+
+                       if (is_debug(intr_info))
+                               /*
+                                * Compared to DR6, FRED #DB event data saved on
+                                * the stack frame have bits 4 ~ 11 and 16 ~ 31
+                                * inverted, i.e.,
+                                *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+                                */
+                               event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+                       else if (is_page_fault(intr_info))
+                               event_data = vcpu->arch.cr2;
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static void vmx_inject_exception(struct kvm_vcpu *vcpu) · line 1892

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+                       else if (is_nm_fault(intr_info))
+                               event_data =
+ to_vmx(vcpu)->fred_xfd_event_data;
+

IMO, deriving an event_data from CR2/DR6 is a little short-sighted because the event_data and CR2/DR6 __can__ be different, e.g., L1 VMM __can__ set CR2 to A and event_data field to B (!=A) when injecting #PF.

VMM should guarantee a FRED guest _sees_ consistent values in CR6/DR6 and event data. If not it's just a VMM bug that we need to fix.

Quoted 3 lines

And this approach cannot be extended to handle a (future) exception whose event_data isn't tied to a dedicated register like CR2/DR6.

See below.

Quoted 2 lines

Adding a new field fred_xfd_event_data in struct vcpu has problems too:
fred_xfd_event_data gets lost during migration;

I'm not bothered, because this is not hard to fix, right?

Quoted 3 lines

strickly speaking, event_data is tied
to an exception rather than a CPU. e.g., the CPU may detect a nested exception when delivering one and both have their own event_data.

No, don't get me wrong. An event data has to be _regenerated_ after a nested exception is handled and the original instruction flow is restarted.
sometimes the original event could be gone.

We don't say an event data is tied to an exception or a CPU, which is just confusing, or misleading.

Quoted 6 lines

I think we can make event_data a property of exceptions. i.e., add a payload2 to struct kvm_queued_exception. and add new APIs to kvm_queue_exception* family to accept a payload2 and in VMX code, just program payload2 to the VMCS event_data field if FRED is enabled. KVM ABI should be extended as well to pass payload2 to userspace like how the payload is handled in kvm_vcpu_ioctl_x86_get/put_vcpu_events.

Yes, it's very likely that we will need to add a payload2 in future, but NOT now. 2 reasons:

1) The first-generation FRED is designed to NOT go too far from what IDT can do. And FRED event data is conceptually an alias of CR2/DR6 in the latest FRED spec (not considering xfd event data for now). And the existing payload is a nice match for now;

2) FRED is an extendable CPU architecture, which allows the structure of event data to become way bigger and complicated. Let's not assume anything and add a payload2 too early.

#59 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 22 lines · On Fri, May 10, 2024 at 05:36:03PM +0800, Li, Xin3 wrote:
Quoted 13 lines
Quoted 13 lines
arch/x86/kvm/vmx/vmx.c +13 -0
+               if (kvm_is_fred_enabled(vcpu)) {
+                       u64 event_data = 0;
+
+                       if (is_debug(intr_info))
+                               /*
+                                * Compared to DR6, FRED #DB event data saved on
+                                * the stack frame have bits 4 ~ 11 and 16 ~ 31
+                                * inverted, i.e.,
+                                *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+                                */
+                               event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+                       else if (is_page_fault(intr_info))
+                               event_data = vcpu->arch.cr2;
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static void vmx_inject_exception(struct kvm_vcpu *vcpu) · line 1892

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+                       else if (is_nm_fault(intr_info))
+                               event_data =
+ to_vmx(vcpu)->fred_xfd_event_data;
+

IMO, deriving an event_data from CR2/DR6 is a little short-sighted because the event_data and CR2/DR6 __can__ be different, e.g., L1 VMM __can__ set CR2 to A and event_data field to B (!=A) when injecting #PF.

Quoted 2 lines

VMM should guarantee a FRED guest _sees_ consistent values in CR6/DR6 and event data. If not it's just a VMM bug that we need to fix.

I don't get why VMM should.

I know the hardware will guarantee this. And likely KVM will also do this. but I don't think it is necessary for KVM to assume L1 VMM will guarantee this. because as long as L2 guest is enlightened to read event_data from stack only, the ABI between L1 VMM and L2 guest can be: CR2/DR6 may be out of sync with the event_data. I am not saying it is good that L1 VMM deviates from the real hardware behavior. But how L1 VMM defines this ABI with L2 has nothing to do with KVM as L0. KVM shouldn't make assumptions on that.

#60 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 28 lines · Chao Gao
Quoted 22 lines · On Fri, May 10, 2024 at 05:36:03PM +0800, Li, Xin3 wrote:
Quoted 13 lines
Quoted 13 lines
arch/x86/kvm/vmx/vmx.c +13 -0
+               if (kvm_is_fred_enabled(vcpu)) {
+                       u64 event_data = 0;
+
+                       if (is_debug(intr_info))
+                               /*
+                                * Compared to DR6, FRED #DB event data saved on
+                                * the stack frame have bits 4 ~ 11 and 16 ~ 31
+                                * inverted, i.e.,
+                                *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+                                */
+                               event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+                       else if (is_page_fault(intr_info))
+                               event_data = vcpu->arch.cr2;
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static void vmx_inject_exception(struct kvm_vcpu *vcpu) · line 1892

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+                       else if (is_nm_fault(intr_info))
+                               event_data =
+ to_vmx(vcpu)->fred_xfd_event_data;
+

IMO, deriving an event_data from CR2/DR6 is a little short-sighted because the event_data and CR2/DR6 __can__ be different, e.g., L1 VMM __can__ set CR2 to A and event_data field to B (!=A) when injecting #PF.

Quoted 2 lines

VMM should guarantee a FRED guest _sees_ consistent values in CR6/DR6 and event data. If not it's just a VMM bug that we need to fix.

I don't get why VMM should.

Quoted 7 lines

I know the hardware will guarantee this. And likely KVM will also do this. but I don't think it is necessary for KVM to assume L1 VMM will guarantee this. because as long as L2 guest is enlightened to read event_data from stack only, the ABI between L1 VMM and L2 guest can be: CR2/DR6 may be out of sync with the event_data. I am not saying it is good that L1 VMM deviates from the real hardware behavior. But how L1 VMM defines this ABI with L2 has nothing to do with KVM as L0. KVM shouldn't make assumptions on that.

Right, but in that case the propagation of event_data would be from vmcs12 => vmcs02, which is handled by prepare_vmcs02_early().

For this flow, it specifically handles exception injection from _L0 KVM_, in which case KVM should always follow the architectural behavior.

Ahh, but the code in with __vmx_complete_interrupts() is wrong. Overwriting vcpu->arch.{dr6,cr2} is wrong, because theres no telling what was in vmcs02. And even if vmcs02 holds DR6/CR2 values, those might be L2 values, i.e. shouldn't clobber the vCPU state.

It's not clear to me that we need to do anything new for FRED in __vmx_complete_interrupts(). The relevant VMCS fields should already hold the correct values, there's no reason to clobber vCPU state. The reason KVM grabs things like instruction length and error code is because that information is visible to other aspects of injection, e.g. to adjust RIP and pushed the error code on the stack.

#61 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 37 lines · Sean Christopherson
Quoted 28 lines · Chao Gao
Quoted 22 lines · On Fri, May 10, 2024 at 05:36:03PM +0800, Li, Xin3 wrote:
Quoted 13 lines
Quoted 13 lines
arch/x86/kvm/vmx/vmx.c +13 -0
+               if (kvm_is_fred_enabled(vcpu)) {
+                       u64 event_data = 0;
+
+                       if (is_debug(intr_info))
+                               /*
+                                * Compared to DR6, FRED #DB event data saved on
+                                * the stack frame have bits 4 ~ 11 and 16 ~ 31
+                                * inverted, i.e.,
+                                *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+                                */
+                               event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+                       else if (is_page_fault(intr_info))
+                               event_data = vcpu->arch.cr2;
Quoted 8 lines

arch/x86/kvm/vmx/vmx.c static void vmx_inject_exception(struct kvm_vcpu *vcpu) · line 1892

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+                       else if (is_nm_fault(intr_info))
+                               event_data =
+ to_vmx(vcpu)->fred_xfd_event_data;
+

IMO, deriving an event_data from CR2/DR6 is a little short-sighted because the event_data and CR2/DR6 __can__ be different, e.g., L1 VMM __can__ set CR2 to A and event_data field to B (!=A) when injecting #PF.

Quoted 2 lines

VMM should guarantee a FRED guest _sees_ consistent values in CR6/DR6 and event data. If not it's just a VMM bug that we need to fix.

I don't get why VMM should.

Quoted 7 lines

I know the hardware will guarantee this. And likely KVM will also do this. but I don't think it is necessary for KVM to assume L1 VMM will guarantee this. because as long as L2 guest is enlightened to read event_data from stack only, the ABI between L1 VMM and L2 guest can be: CR2/DR6 may be out of sync with the event_data. I am not saying it is good that L1 VMM deviates from the real hardware behavior. But how L1 VMM defines this ABI with L2 has nothing to do with KVM as L0. KVM shouldn't make assumptions on that.

Quoted 2 lines

Right, but in that case the propagation of event_data would be from vmcs12 => vmcs02, which is handled by prepare_vmcs02_early().

Yes. But delivering this event to L2 may cause VM-exit. So, L0 KVM may need to re-inject this event ...

Quoted 3 lines

For this flow, it specifically handles exception injection from _L0 KVM_, in which case KVM should always follow the architectural behavior.

... and go through this exception injection flow. For such an event, there is no guarantee that the associated event data is consistent with the vCPU's DR6/CR2/XFD_ERR.

Quoted 5 lines

Ahh, but the code in with __vmx_complete_interrupts() is wrong. Overwriting vcpu->arch.{dr6,cr2} is wrong, because theres no telling what was in vmcs02. And even if vmcs02 holds DR6/CR2 values, those might be L2 values, i.e. shouldn't clobber the vCPU state.

Exactly.

Quoted 4 lines

It's not clear to me that we need to do anything new for FRED in __vmx_complete_interrupts(). The relevant VMCS fields should already hold the correct values, there's no reason to clobber vCPU state. The reason KVM grabs

The whole point is to cache the ORIGINAL_EVENT_DATA VMCS field so that KVM can set it back to the INJECTED_EVENT_DATA VMCS field when reinjecting the pending event in IDT-vectoring information.

Quoted 3 lines

things like instruction length and error code is because that information is visible to other aspects of injection, e.g. to adjust RIP and pushed the error code on the stack.

maintainer Tested-by Shan Kang
#62 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 61 lines · Chao Gao
Quoted 37 lines · Sean Christopherson
Quoted 28 lines · Chao Gao
Quoted 22 lines · On Fri, May 10, 2024 at 05:36:03PM +0800, Li, Xin3 wrote:
Quoted 13 lines
Quoted 13 lines
(quoted diff) +13 -0
+               if (kvm_is_fred_enabled(vcpu)) {
+                       u64 event_data = 0;
+
+                       if (is_debug(intr_info))
+                               /*
+                                * Compared to DR6, FRED #DB event data saved on
+                                * the stack frame have bits 4 ~ 11 and 16 ~ 31
+                                * inverted, i.e.,
+                                *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+                                */
+                               event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+                       else if (is_page_fault(intr_info))
+                               event_data = vcpu->arch.cr2;
Quoted 8 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+                       else if (is_nm_fault(intr_info))
+                               event_data =
+ to_vmx(vcpu)->fred_xfd_event_data;
+

IMO, deriving an event_data from CR2/DR6 is a little short-sighted because the event_data and CR2/DR6 __can__ be different, e.g., L1 VMM __can__ set CR2 to A and event_data field to B (!=A) when injecting #PF.

Quoted 2 lines

VMM should guarantee a FRED guest _sees_ consistent values in CR6/DR6 and event data. If not it's just a VMM bug that we need to fix.

I don't get why VMM should.

Quoted 7 lines

I know the hardware will guarantee this. And likely KVM will also do this. but I don't think it is necessary for KVM to assume L1 VMM will guarantee this. because as long as L2 guest is enlightened to read event_data from stack only, the ABI between L1 VMM and L2 guest can be: CR2/DR6 may be out of sync with the event_data. I am not saying it is good that L1 VMM deviates from the real hardware behavior. But how L1 VMM defines this ABI with L2 has nothing to do with KVM as L0. KVM shouldn't make assumptions on that.

Quoted 2 lines

Right, but in that case the propagation of event_data would be from vmcs12 => vmcs02, which is handled by prepare_vmcs02_early().

Yes. But delivering this event to L2 may cause VM-exit. So, L0 KVM may need to re-inject this event ...

Quoted 3 lines

For this flow, it specifically handles exception injection from _L0 KVM_, in which case KVM should always follow the architectural behavior.

... and go through this exception injection flow. For such an event, there is no guarantee that the associated event data is consistent with the vCPU's DR6/CR2/XFD_ERR.

Quoted 5 lines

Ahh, but the code in with __vmx_complete_interrupts() is wrong. Overwriting vcpu->arch.{dr6,cr2} is wrong, because theres no telling what was in vmcs02. And even if vmcs02 holds DR6/CR2 values, those might be L2 values, i.e. shouldn't clobber the vCPU state.

Exactly.

Quoted 1 line
Quoted 7 lines
Quoted 3 lines

It's not clear to me that we need to do anything new for FRED in __vmx_complete_interrupts(). The relevant VMCS fields should already hold the correct values, there's no reason to clobber vCPU state. The reason KVM grabs

The whole point is to cache the ORIGINAL_EVENT_DATA VMCS field so that KVM can set it back to the INJECTED_EVENT_DATA VMCS field when reinjecting the pending event in IDT-vectoring information.

Hrm, right. I was thinking INJECTED_EVENT_DATA would already hold the correct data, but that's only true when the VM-Exit occurred on an injected event, i.e. when KVM already set the relevant fields. Ah, and not capturing the state would lead to loss of data on migration.

I think the right way to handle this is to add kvm_queued_exception.event_data, and then fill event_data during kvm_deliver_exception_payload() when injecting an event for the first time, and set it directly when re-injecting an event. The event data is effectively the same thing as the payload, it just happens to be deliver on the event stack frame, not via architectural register state.

And I think we should also rework kvm_requeue_exception() to open code stuffing vcpu->arch.exception instead of using kvm_multiple_exception(). The two flows (injection vs. re-injection) don't actually have that much in common, and the common parts are the super duper simple things, e.g. actually setting values and requested KVM_REQ_EVENT.

Aha! And there is a pre-existing bug in handle_nm_fault_irqoff(), as it clobbers guest XFD_ERR if CR0.TS=1.

Speaking of XFD_ERR, I think the best way to deal with that is to pass it along as a payload, but then simply do nothing when delivering the payload... until FRED comes along, and then kvm_deliver_exception_payload() can be responsible for setting FRED's ex->event_data.

With that combination of tweaks, "normal" injection always sets event_data via the payload, and because re-injected events never deliver payloads (already delivered), KVM will naturally avoid clobbering ex->event_data with stale state (and obviously doesn't need to overwrite CR2 or DR6).

Attached patches are compile-tested only. They're a subset of the overall series, hopefully it's fairly easy to understand where they slot in.

From 0cdb034adbcfcc11a584d0e16dddfa151afb36db Mon Sep 17 00:00:00 2001
From: Sean Christopherson <[email protected]>
Date: Thu, 13 Jun 2024 08:09:51 -0700
Subject: [PATCH 03/28] KVM: x86: Use a dedicated flow for queueing re-injected
exceptions

Open code the filling of vcpu->arch.exception in kvm_requeue_exception() instead of bouncing through kvm_multiple_exception(), as re-injection doesn't actually share that much code with "normal" injection, e.g. the VM-Exit interception check, payload delivery, and nested exception code is all bypassed as those flows only apply during initial injection.

When FRED comes along, the special casing will only get worse, as FRED explicitly tracks nested exceptions and essentially delivers the payload on the stack frame, i.e. re-injection will need more inputs, and normal injection will have yet more code that needs to be bypassed when KVM is re-injecting an exception.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h |  4 +-
 arch/x86/kvm/svm/svm.c          | 15 +++---
 arch/x86/kvm/vmx/vmx.c          | 16 +++---
 arch/x86/kvm/x86.c              | 89 ++++++++++++++++-----------------
 4 files changed, 63 insertions(+), 61 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -2
index b5b2d0fde579..2cd08b8da3b3 100644
@@ -2060,8 +2060,8 @@ 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 nr);
-void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
+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);
 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 				    struct x86_exception *fault);
arch/x86/kvm/svm/svm.c +9 -6
index e90b429c84f1..cd2ed3329c01 100644
@@ -4048,20 +4048,23 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 		vcpu->arch.nmi_injected = true;
 		svm->nmi_l1_to_l2 = nmi_l1_to_l2;
 		break;
-	case SVM_EXITINTINFO_TYPE_EXEPT:
+	case SVM_EXITINTINFO_TYPE_EXEPT: {
+		u32 error_code = 0;
+
 		/*
 		 * Never re-inject a #VC exception.
 		 */
 		if (vector == X86_TRAP_VC)
 			break;
 
-		if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
-			u32 err = svm->vmcb->control.exit_int_info_err;
-			kvm_requeue_exception_e(vcpu, vector, err);
+		if (exitintinfo & SVM_EXITINTINFO_VALID_ERR)
+			error_code = svm->vmcb->control.exit_int_info_err;
 
-		} else
-			kvm_requeue_exception(vcpu, vector);
+		kvm_requeue_exception(vcpu, vector,
+				      exitintinfo & SVM_EXITINTINFO_VALID_ERR,
+				      error_code);
 		break;
+	}
 	case SVM_EXITINTINFO_TYPE_INTR:
 		kvm_queue_interrupt(vcpu, vector, false);
 		break;
arch/x86/kvm/vmx/vmx.c +10 -6
index 581967d20659..8485fd1e28eb 100644
@@ -7085,13 +7085,17 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
 	case INTR_TYPE_SOFT_EXCEPTION:
 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
 		fallthrough;
-	case INTR_TYPE_HARD_EXCEPTION:
-		if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
-			u32 err = vmcs_read32(error_code_field);
-			kvm_requeue_exception_e(vcpu, vector, err);
-		} else
-			kvm_requeue_exception(vcpu, vector);
+	case INTR_TYPE_HARD_EXCEPTION: {
+		u32 error_code = 0;
+
+		if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK)
+			error_code = vmcs_read32(error_code_field);
+
+		kvm_requeue_exception(vcpu, vector,
+				      idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK,
+				      error_code);
 		break;
+	}
 	case INTR_TYPE_SOFT_INTR:
 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
 		fallthrough;
arch/x86/kvm/x86.c +42 -47

138 lines not on this page · raw message

Signature · 1 line
2.45.2.627.g7a2c4fd464-goog

From 64ff7eb90d0e3b044fb423c6d073b3966f866eb3 Mon Sep 17 00:00:00 2001
From: Sean Christopherson <[email protected]>
Date: Thu, 13 Jun 2024 10:10:11 -0700
Subject: [PATCH 04/28] KVM: VMX: Don't modify guest XFD_ERR if CR0.TS=1

Don't update the guest's XFD_ERR MSR if CR0.TS is set; per the SDM, XFD_ERR is not modified if CR0.TS=1. Although it's not explicitly stated in the SDM, conceptually it makes sense the CR0.TS check would be done prior to the XFD_ERR check, e.g. CR0.TS=1 blocks all SIMD state, whereas XFD blocks only XTILE state.

Device-not-available exceptions that are not due to XFD - those resulting from setting CR0.TS to 1 - do not modify the IA32_XFD_ERR MSR.

Opportunistically update the comment to call out that XFD_ERR is updated before the VM-Exit check occurs. Nothing in the SDM explicitly calls out this behavior, but logically it must be the behavior, otherwise reading XFD_ERR in handle_nm_fault_irqoff() would return stale data, i.e. the to-be-delivered XFD_ERR value would need to be saved in EXIT_QUALIFICATION, a la DR6 for #DB and CR2 for #PF, so that software could capture the guest value.

Fixes ec5be88ab29f ("kvm: x86: Intercept #NM for saving IA32_XFD_ERR")
---
 arch/x86/kvm/vmx/vmx.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
arch/x86/kvm/vmx/vmx.c +8 -8
index 8485fd1e28eb..16c91a78fc2b 100644
@@ -6923,16 +6923,16 @@ static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
 	 * MSR value is not clobbered by the host activity before the guest
 	 * has chance to consume it.
 	 *
-	 * Do not blindly read xfd_err here, since this exception might
-	 * be caused by L1 interception on a platform which doesn't
-	 * support xfd at all.
+	 * Update the guest's XFD_ERR if and only if XFD is enabled, as the #NM
+	 * interception may have been caused by L1 interception.  Per the SDM,
+	 * XFD_ERR is not modified if CR0.TS=1.
 	 *
-	 * Do it conditionally upon guest_fpu::xfd. xfd_err matters
-	 * only when xfd contains a non-zero value.
-	 *
-	 * Queuing exception is done in vmx_handle_exit. See comment there.
+	 * Note, XFD_ERR is updated _before_ the #NM interception check, i.e.
+	 * unlike CR2 and DR6, the value is not a payload that is attached to
+	 * the #NM exception.
 	 */
-	if (vcpu->arch.guest_fpu.fpstate->xfd)
+	if (vcpu->arch.guest_fpu.fpstate->xfd &&
+	    !kvm_is_cr0_bit_set(vcpu, X86_CR0_TS))
 		rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
 }
 
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog

From f38dcc04e334cda572289f05f4be7702bebfc96a Mon Sep 17 00:00:00 2001
From: Xin Li <[email protected]>
Date: Wed, 7 Feb 2024 09:26:31 -0800
Subject: [PATCH 13/28] KVM: x86: Add a helper to detect if FRED is enabled for
a vCPU

Add is_fred_enabled() to detect if FRED is enabled on a vCPU.

---
 arch/x86/kvm/kvm_cache_regs.h | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
arch/x86/kvm/kvm_cache_regs.h +15 -0
index 75eae9c4998a..fe5546efd388 100644
@@ -187,6 +187,21 @@ static __always_inline bool kvm_is_cr4_bit_set(struct kvm_vcpu *vcpu,
 	return !!kvm_read_cr4_bits(vcpu, cr4_bit);
 }
 
+/*
+ * It's enough to check just CR4.FRED (X86_CR4_FRED) to tell if
+ * a vCPU is running with FRED enabled, because:
+ * 1) CR4.FRED can be set to 1 only _after_ IA32_EFER.LMA = 1.
+ * 2) To leave IA-32e mode, CR4.FRED must be cleared first.
+ */
+static inline bool is_fred_enabled(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_X86_64
+	return kvm_is_cr4_bit_set(vcpu, X86_CR4_FRED);
+#else
+	return false;
+#endif
+}
+
 static inline ulong kvm_read_cr3(struct kvm_vcpu *vcpu)
 {
 	if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog

From d5ad36ae7d7aef4c6b97cf624bc38b3b0ec37515 Mon Sep 17 00:00:00 2001
From: Sean Christopherson <[email protected]>
Date: Thu, 13 Jun 2024 10:28:29 -0700
Subject: [PATCH 14/28] KVM: VMX: Pass XFD_ERR as pseudo-payload when injecting
#NM

Pass XFD_ERR via KVM's exception payload mechanism when injecting an #NM after interception so that XFD_ERR can be propagated to FRED's event_data field without needing a dedicated field (which would need to be migrated).

For non-FRED vCPUs, this is a glorified NOP as kvm_deliver_exception_payload() will simply do nothing (which is desirable and correct).

---
 arch/x86/kvm/vmx/vmx.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/vmx.c +10 -4
index d916199f1e60..f0643aa1f4ef 100644
@@ -5316,6 +5316,12 @@ bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu)
 	       (kvm_get_rflags(vcpu) & X86_EFLAGS_AC);
 }
 
+static bool is_xfd_nm_fault(struct kvm_vcpu *vcpu)
+{
+	return vcpu->arch.guest_fpu.fpstate->xfd &&
+	       !kvm_is_cr0_bit_set(vcpu, X86_CR0_TS);
+}
+
 static int handle_exception_nmi(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
@@ -5342,7 +5348,8 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
 	 * point.
 	 */
 	if (is_nm_fault(intr_info)) {
-		kvm_queue_exception(vcpu, NM_VECTOR);
+		kvm_queue_exception_p(vcpu, NM_VECTOR,
+				      is_xfd_nm_fault(vcpu) ? vcpu->arch.guest_fpu.xfd_err : 0);
 		return 1;
 	}
 
@@ -7075,14 +7082,13 @@ static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
 	 *
 	 * Update the guest's XFD_ERR if and only if XFD is enabled, as the #NM
 	 * interception may have been caused by L1 interception.  Per the SDM,
-	 * XFD_ERR is not modified if CR0.TS=1.
+	 * XFD_ERR is not modified for non-XFD #NM, i.e. if CR0.TS=1.
 	 *
 	 * Note, XFD_ERR is updated _before_ the #NM interception check, i.e.
 	 * unlike CR2 and DR6, the value is not a payload that is attached to
 	 * the #NM exception.
 	 */
-	if (vcpu->arch.guest_fpu.fpstate->xfd &&
-	    !kvm_is_cr0_bit_set(vcpu, X86_CR0_TS))
+	if (is_xfd_nm_fault(vcpu))
 		rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
 }
 
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog

From 6095c8428dc2b854cb19482832af59c348312527 Mon Sep 17 00:00:00 2001
From: Sean Christopherson <[email protected]>
Date: Thu, 13 Jun 2024 09:07:46 -0700
Subject: [PATCH 15/28] KVM: VMX: Virtualize FRED event_data

---
 arch/x86/include/asm/kvm_host.h |  3 ++-
 arch/x86/include/asm/vmx.h      |  4 ++++
 arch/x86/kvm/svm/svm.c          |  2 +-
 arch/x86/kvm/vmx/vmx.c          | 22 ++++++++++++++++++----
 arch/x86/kvm/x86.c              | 16 +++++++++++++++-
 5 files changed, 40 insertions(+), 7 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -1
index 7268f90c3615..62eddd1369da 100644
@@ -736,6 +736,7 @@ struct kvm_queued_exception {
 	u32 error_code;
 	unsigned long payload;
 	bool has_payload;
+	u64 event_data;
 };
 
 struct kvm_vcpu_arch {
@@ -2061,7 +2062,7 @@ 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);
+			   bool has_error_code, u32 error_code, u64 event_data);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault);
 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 				    struct x86_exception *fault);
arch/x86/include/asm/vmx.h +4 -0
index 4889754415b5..6b796c5c9c2b 100644
@@ -256,8 +256,12 @@ enum vmcs_field {
 	PID_POINTER_TABLE_HIGH		= 0x00002043,
 	SECONDARY_VM_EXIT_CONTROLS	= 0x00002044,
 	SECONDARY_VM_EXIT_CONTROLS_HIGH	= 0x00002045,
+	INJECTED_EVENT_DATA		= 0x00002052,
+	INJECTED_EVENT_DATA_HIGH	= 0x00002053,
 	GUEST_PHYSICAL_ADDRESS          = 0x00002400,
 	GUEST_PHYSICAL_ADDRESS_HIGH     = 0x00002401,
+	ORIGINAL_EVENT_DATA		= 0x00002404,
+	ORIGINAL_EVENT_DATA_HIGH	= 0x00002405,
 	VMCS_LINK_POINTER               = 0x00002800,
 	VMCS_LINK_POINTER_HIGH          = 0x00002801,
 	GUEST_IA32_DEBUGCTL             = 0x00002802,
arch/x86/kvm/svm/svm.c +1 -1
index cd2ed3329c01..ce25e43b4ec3 100644
@@ -4062,7 +4062,7 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 
 		kvm_requeue_exception(vcpu, vector,
 				      exitintinfo & SVM_EXITINTINFO_VALID_ERR,
-				      error_code);
+				      error_code, 0);
 		break;
 	}
 	case SVM_EXITINTINFO_TYPE_INTR:
arch/x86/kvm/vmx/vmx.c +18 -4
index f0643aa1f4ef..246230cf3e97 100644
@@ -1876,6 +1876,9 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 
 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
 
+	if (is_fred_enabled(vcpu))
+		vmcs_write64(INJECTED_EVENT_DATA, ex->event_data);
+
 	vmx_clear_hlt(vcpu);
 }
 
@@ -7208,7 +7211,8 @@ static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
 				      u32 idt_vectoring_info,
 				      int instr_len_field,
-				      int error_code_field)
+				      int error_code_field,
+				      int event_data_field)
 {
 	u8 vector;
 	int type;
@@ -7243,13 +7247,17 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
 		fallthrough;
 	case INTR_TYPE_HARD_EXCEPTION: {
 		u32 error_code = 0;
+		u64 event_data = 0;
 
 		if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK)
 			error_code = vmcs_read32(error_code_field);
+		if (is_fred_enabled(vcpu))
+			event_data = vmcs_read64(event_data_field);
 
 		kvm_requeue_exception(vcpu, vector,
 				      idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK,
-				      error_code);
+				      error_code,
+				      event_data);
 		break;
 	}
 	case INTR_TYPE_SOFT_INTR:
@@ -7267,7 +7275,8 @@ static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
 {
 	__vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
 				  VM_EXIT_INSTRUCTION_LEN,
-				  IDT_VECTORING_ERROR_CODE);
+				  IDT_VECTORING_ERROR_CODE,
+				  ORIGINAL_EVENT_DATA);
 }
 
 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
@@ -7275,7 +7284,8 @@ static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
 	__vmx_complete_interrupts(vcpu,
 				  vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
 				  VM_ENTRY_INSTRUCTION_LEN,
-				  VM_ENTRY_EXCEPTION_ERROR_CODE);
+				  VM_ENTRY_EXCEPTION_ERROR_CODE,
+				  INJECTED_EVENT_DATA);
 
 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
 }
@@ -7392,6 +7402,10 @@ static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
 
 	vmx_disable_fb_clear(vmx);
 
+	/*
+	 * Note, even though FRED delivers the faulting linear address via the
+	 * event data field on the stack, CR2 is still updated.
+	 */
 	if (vcpu->arch.cr2 != native_read_cr2())
 		native_write_cr2(vcpu->arch.cr2);
 
arch/x86/kvm/x86.c +15 -1
index 4e1517698e61..4a76d1ae0575 100644
@@ -611,9 +611,22 @@ void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,
 		 * breakpoint), it is reserved and must be zero in DR6.
 		 */
 		vcpu->arch.dr6 &= ~BIT(12);
+
+		/*
+		 * FRED #DB event data matches DR6, but follows the polarity of
+		 * VMX's pending debug exceptions, not DR6.
+		 */
+		ex->event_data = ex->payload & ~BIT(12);
+		break;
+	case NM_VECTOR:
+		ex->event_data = ex->payload;
 		break;
 	case PF_VECTOR:
 		vcpu->arch.cr2 = ex->payload;
+		ex->event_data = ex->payload;
+		break;
+	default:
+		ex->event_data = 0;
 		break;
 	}
 
@@ -727,7 +740,7 @@ static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
 }
 
 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
-			   bool has_error_code, u32 error_code)
+			   bool has_error_code, u32 error_code, u64 event_data)
 {
 
 	/*
@@ -752,6 +765,7 @@ void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 	vcpu->arch.exception.error_code = error_code;
 	vcpu->arch.exception.has_payload = false;
 	vcpu->arch.exception.payload = 0;
+	vcpu->arch.exception.event_data = event_data;
 }
 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
 
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog

From d604b666e72ac747470dfef54f7b75cb5f8e93fe Mon Sep 17 00:00:00 2001
From: Sean Christopherson <[email protected]>
Date: Thu, 13 Jun 2024 09:48:43 -0700
Subject: [PATCH 16/28] KVM: VMX: Virtualize FRED nested exception tracking

---
 arch/x86/include/asm/kvm_host.h |  4 +++-
 arch/x86/include/asm/vmx.h      |  6 ++++--
 arch/x86/kvm/svm/svm.c          |  2 +-
 arch/x86/kvm/vmx/vmx.c          |  6 +++++-
 arch/x86/kvm/x86.c              | 14 +++++++++++++-
 arch/x86/kvm/x86.h              |  1 +
 6 files changed, 27 insertions(+), 6 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -1
index 62eddd1369da..ceb01114a509 100644
@@ -736,6 +736,7 @@ struct kvm_queued_exception {
 	u32 error_code;
 	unsigned long payload;
 	bool has_payload;
+	bool nested;
 	u64 event_data;
 };
 
@@ -2062,7 +2063,8 @@ 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, u64 event_data);
+			   bool has_error_code, u32 error_code, bool nested,
+			   u64 event_data);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault);
 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 				    struct x86_exception *fault);
arch/x86/include/asm/vmx.h +4 -2
index 6b796c5c9c2b..26879ea197a4 100644
@@ -134,7 +134,7 @@
 #define VMX_BASIC_DUAL_MONITOR_TREATMENT	BIT_ULL(49)
 #define VMX_BASIC_INOUT				BIT_ULL(54)
 #define VMX_BASIC_TRUE_CTLS			BIT_ULL(55)
-
+#define VMX_BASIC_NESTED_EXCEPTION		BIT_ULL(58)
 
 /* VMX_MISC bits and bitmasks */
 #define VMX_MISC_INTEL_PT			BIT_ULL(14)
@@ -407,13 +407,15 @@ enum vmcs_field {
 #define INTR_INFO_INTR_TYPE_MASK        0x700           /* 10:8 */
 #define INTR_INFO_DELIVER_CODE_MASK     0x800           /* 11 */
 #define INTR_INFO_UNBLOCK_NMI		0x1000		/* 12 */
+#define INTR_INFO_NESTED_EXCEPTION_MASK	0x2000		/* 13 */
 #define INTR_INFO_VALID_MASK            0x80000000      /* 31 */
-#define INTR_INFO_RESVD_BITS_MASK       0x7ffff000
+#define INTR_INFO_RESVD_BITS_MASK       0x7fffd000
 
 #define VECTORING_INFO_VECTOR_MASK           	INTR_INFO_VECTOR_MASK
 #define VECTORING_INFO_TYPE_MASK        	INTR_INFO_INTR_TYPE_MASK
 #define VECTORING_INFO_DELIVER_CODE_MASK    	INTR_INFO_DELIVER_CODE_MASK
 #define VECTORING_INFO_VALID_MASK       	INTR_INFO_VALID_MASK
+#define VECTORING_INFO_NESTED_EXCEPTION_MASK	INTR_INFO_NESTED_EXCEPTION_MASK
 
 #define INTR_TYPE_EXT_INTR		(EVENT_TYPE_EXTINT << 8)	/* external interrupt */
 #define INTR_TYPE_RESERVED		(EVENT_TYPE_RESERVED << 8)	/* reserved */
arch/x86/kvm/svm/svm.c +1 -1
index ce25e43b4ec3..2597b22648dd 100644
@@ -4062,7 +4062,7 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 
 		kvm_requeue_exception(vcpu, vector,
 				      exitintinfo & SVM_EXITINTINFO_VALID_ERR,
-				      error_code, 0);
+				      error_code, false, 0);
 		break;
 	}
 	case SVM_EXITINTINFO_TYPE_INTR:
arch/x86/kvm/vmx/vmx.c +5 -1
index 246230cf3e97..1f017abf1403 100644
@@ -1871,8 +1871,11 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
 			     vmx->vcpu.arch.event_exit_inst_len);
 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
-	} else
+	} else {
 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
+		if (ex->nested)
+			intr_info |= INTR_INFO_NESTED_EXCEPTION_MASK;
+	}
 
 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
 
@@ -7257,6 +7260,7 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
 		kvm_requeue_exception(vcpu, vector,
 				      idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK,
 				      error_code,
+				      idt_vectoring_info & VECTORING_INFO_NESTED_EXCEPTION_MASK,
 				      event_data);
 		break;
 	}
arch/x86/kvm/x86.c +13 -1
index 4a76d1ae0575..905225a927ff 100644
@@ -681,6 +681,11 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 		vcpu->arch.exception.pending = true;
 		vcpu->arch.exception.injected = false;
 
+		vcpu->arch.exception.nested = vcpu->arch.exception.nested ||
+					      (is_fred_enabled(vcpu) &&
+					       (vcpu->arch.nmi_injected ||
+					        vcpu->arch.interrupt.injected));
+
 		vcpu->arch.exception.has_error_code = has_error;
 		vcpu->arch.exception.vector = nr;
 		vcpu->arch.exception.error_code = error_code;
@@ -710,8 +715,13 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 		vcpu->arch.exception.injected = false;
 		vcpu->arch.exception.pending = false;
 
+		/* #DF is NOT a nested event, per its definition. */
+		vcpu->arch.exception.nested = false;
+
 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
 	} else {
+		vcpu->arch.exception.nested = is_fred_enabled(vcpu);
+
 		/* replace previous exception with a new one in a hope
 		   that instruction re-execution will regenerate lost
 		   exception */
@@ -740,7 +750,8 @@ static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
 }
 
 void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
-			   bool has_error_code, u32 error_code, u64 event_data)
+			   bool has_error_code, u32 error_code, bool nested,
+			   u64 event_data)
 {
 
 	/*
@@ -765,6 +776,7 @@ void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 	vcpu->arch.exception.error_code = error_code;
 	vcpu->arch.exception.has_payload = false;
 	vcpu->arch.exception.payload = 0;
+	vcpu->arch.exception.nested = nested;
 	vcpu->arch.exception.event_data = event_data;
 }
 EXPORT_SYMBOL_GPL(kvm_requeue_exception);
arch/x86/kvm/x86.h +1 -0
index 9a52016ebf5a..c1f1d5696080 100644
@@ -108,6 +108,7 @@ static inline void kvm_clear_exception_queue(struct kvm_vcpu *vcpu)
 {
 	vcpu->arch.exception.pending = false;
 	vcpu->arch.exception.injected = false;
+	vcpu->arch.exception.nested = false;
 	vcpu->arch.exception_vmexit.pending = false;
 }
 
Signature · 1 line
2.45.2.627.g7a2c4fd464-goog
#63 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

In reply to Xin Li
Quoted 5 lines · Xin Li
arch/x86/include/asm/vmx.h +0 -0
index 4889754415b5..6b796c5c9c2b 100644

arch/x86/include/asm/vmx.h enum vmcs_field { · line 264

Quoted 9 lines
arch/x86/include/asm/vmx.h +4 -0
@@ -256,8 +256,12 @@ enum vmcs_field {
 	PID_POINTER_TABLE_HIGH		= 0x00002043,
 	SECONDARY_VM_EXIT_CONTROLS	= 0x00002044,
 	SECONDARY_VM_EXIT_CONTROLS_HIGH	= 0x00002045,
+	INJECTED_EVENT_DATA		= 0x00002052,
+	INJECTED_EVENT_DATA_HIGH	= 0x00002053,
 	GUEST_PHYSICAL_ADDRESS          = 0x00002400,
 	GUEST_PHYSICAL_ADDRESS_HIGH     = 0x00002401,
+	ORIGINAL_EVENT_DATA		= 0x00002404,
+	ORIGINAL_EVENT_DATA_HIGH	= 0x00002405,

Are these the actual names from the SDM? E.g. is there no FRED_ prefix to clue in readers that they are FRED specific? (unless they aren't FRED specific?)

Quoted 39 lines
arch/x86/include/asm/vmx.h +0 -0
 	VMCS_LINK_POINTER               = 0x00002800,
 	VMCS_LINK_POINTER_HIGH          = 0x00002801,
 	GUEST_IA32_DEBUGCTL             = 0x00002802,
arch/x86/kvm/vmx/vmx.c +21 -1
index ee61d2c25cb0..f622fb90a098 100644
@@ -1871,9 +1871,29 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 		vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
 			     vmx->vcpu.arch.event_exit_inst_len);
 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
-	} else
+	} else {
 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
 
+		if (kvm_is_fred_enabled(vcpu)) {
+			u64 event_data = 0;
+
+			if (is_debug(intr_info))
+				/*
+				 * Compared to DR6, FRED #DB event data saved on
+				 * the stack frame have bits 4 ~ 11 and 16 ~ 31
+				 * inverted, i.e.,
+				 *   fred_db_event_data = dr6 ^ 0xFFFF0FF0UL
+				 */
+				event_data = vcpu->arch.dr6 ^ DR6_RESERVED;
+			else if (is_page_fault(intr_info))
+				event_data = vcpu->arch.cr2;
+			else if (is_nm_fault(intr_info))
+				event_data = to_vmx(vcpu)->fred_xfd_event_data;
+
+			vmcs_write64(INJECTED_EVENT_DATA, event_data);
+		}
+	}
+
 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
 
 	vmx_clear_hlt(vcpu);

arch/x86/kvm/vmx/vmx.c static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu) · line 7107

Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +2 -1
@@ -7082,8 +7102,11 @@ static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu)
 	 *
 	 * Queuing exception is done in vmx_handle_exit. See comment there.
 	 */
-	if (vcpu->arch.guest_fpu.fpstate->xfd)
+	if (vcpu->arch.guest_fpu.fpstate->xfd) {
 		rdmsrl(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err);
+		to_vmx(vcpu)->fred_xfd_event_data = vcpu->arch.cr0 & X86_CR0_TS

kvm_is_cr0_bit_set(), don't read vcpu->arch.cr0 directly.

arch/x86/kvm/vmx/vmx.c static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu) · line 7108

Quoted 1 line
arch/x86/kvm/vmx/vmx.c +1 -0
+			? 0 : vcpu->arch.guest_fpu.xfd_err;

Maybe this?

		if (kvm_is_cr0_bit_set(vcpu, X86_CR0_TS))
			to_vmx(vcpu)->fred_xfd_event_data = 0;
		else
			to_vmx(vcpu)->fred_xfd_event_data = vcpu->arch.guest_fpu.xfd_err;

Hmm, but why does this need to be cached _now_? I.e. why does fred_xfd_event_data need to exist? Wouldn't it be simpler and more robust to use vcpu->arch.guest_fpu.xfd_err directly in vmx_inject_exception()?

Quoted 11 lines
arch/x86/kvm/vmx/vmx.c +1 -3
+	}
 }
 
 static void handle_exception_irqoff(struct vcpu_vmx *vmx)
@@ -7199,29 +7222,28 @@ static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
 					      vmx->loaded_vmcs->entry_time));
 }
 
-static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
-				      u32 idt_vectoring_info,
-				      int instr_len_field,

arch/x86/kvm/vmx/vmx.c static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx) · line 7228

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +3 -6
-				      int error_code_field)
+static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu, bool vectoring)
 {
-	u8 vector;
-	int type;
-	bool idtv_info_valid;
-
-	idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
+	u32 event_id = vectoring ? to_vmx(vcpu)->idt_vectoring_info
+				 : vmcs_read32(VM_ENTRY_INTR_INFO_FIELD);

Preferred style for ternary operators is:

	u32 event_id = vectoring ? to_vmx(vcpu)->idt_vectoring_info :
				   vmcs_read32(VM_ENTRY_INTR_INFO_FIELD);

That said, I don't think this is a net positive versus passing in all params. The bare true/false is somewhat inscrutable, and in this code, it's hard to understand why KVM looks at X instead of Y without the conext of the caller.

Quoted 30 lines
arch/x86/kvm/vmx/vmx.c +9 -5
+	int instr_len_field = vectoring ? VM_EXIT_INSTRUCTION_LEN
+					: VM_ENTRY_INSTRUCTION_LEN;
+	int error_code_field = vectoring ? IDT_VECTORING_ERROR_CODE
+					 : VM_ENTRY_EXCEPTION_ERROR_CODE;
+	int event_data_field = vectoring ? ORIGINAL_EVENT_DATA
+					 : INJECTED_EVENT_DATA;
+	u8 vector = event_id & INTR_INFO_VECTOR_MASK;
+	int type = event_id & INTR_INFO_INTR_TYPE_MASK;
 
 	vcpu->arch.nmi_injected = false;
 	kvm_clear_exception_queue(vcpu);
 	kvm_clear_interrupt_queue(vcpu);
 
-	if (!idtv_info_valid)
+	if (!(event_id & INTR_INFO_VALID_MASK))
 		return;
 
 	kvm_make_request(KVM_REQ_EVENT, vcpu);
 
-	vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
-	type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
-
 	switch (type) {
 	case INTR_TYPE_NMI_INTR:
 		vcpu->arch.nmi_injected = true;
@@ -7236,10 +7258,31 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
 		fallthrough;
 	case INTR_TYPE_HARD_EXCEPTION:
-		if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {

arch/x86/kvm/vmx/vmx.c static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu, · line 7267

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +7 -3
-			u32 err = vmcs_read32(error_code_field);
-			kvm_requeue_exception_e(vcpu, vector, err);
-		} else
+		if (kvm_is_fred_enabled(vcpu)) {
+			/* Save event data for being used as injected-event data */
+			u64 event_data = vmcs_read64(event_data_field);
+
+			switch (vector) {
+			case DB_VECTOR:
+				/* %dr6 should be equal to (event_data ^ DR6_RESERVED) */

DR6, no need to use assembly syntax, but I'd just drop this comment, as well as the CR2 comment. They add no insight beyond what the code literally does.

Quoted 14 lines
arch/x86/kvm/vmx/vmx.c +14 -0
+				vcpu->arch.dr6 = event_data ^ DR6_RESERVED;
+				break;
+			case NM_VECTOR:
+				to_vmx(vcpu)->fred_xfd_event_data = event_data;
+				break;
+			case PF_VECTOR:
+				/* %cr2 should be equal to event_data */
+				vcpu->arch.cr2 = event_data;
+				break;
+			default:
+				WARN_ON(event_data != 0);
+				break;
+			}
+		}
#64 lore raw

Re: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

In reply to Xin Li
Quoted 12 lines · Xin Li
arch/x86/kvm/vmx/vmx.c +8 -0
@@ -7382,6 +7419,24 @@ static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu,
 
 	vmx_disable_fb_clear(vmx);
 
+	/*
+	 * %cr2 needs to be saved after a VM exit and restored before a VM
+	 * entry in case a VM exit happens immediately after delivery of a
+	 * guest #PF but before guest reads %cr2.
+	 *
+	 * A FRED guest should read its #PF faulting linear address from
+	 * the event data field in its FRED stack frame instead of %cr2.
+	 * But the FRED 5.0 spec still requires a FRED CPU to update %cr2

arch/x86/kvm/vmx/vmx.c static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu, · line 7439

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	 * in the normal way, thus %cr2 is still updated even for a FRED
+	 * guest.
+	 *
+	 * Note, an NMI could interrupt KVM:
+	 *   1) after VM exit but before CR2 is saved.
+	 *   2) after CR2 is restored but before VM entry.
+	 * And a #PF could happen durng NMI handlng, which overwrites %cr2.
+	 * Thus exc_nmi() should save and restore %cr2 upon entering and
+	 * before leaving to make sure %cr2 not corrupted.
+	 */

This is 99.9% noise. What software does or does not do with respect to CR2 is completely irrelevant. The *only* thing that matters is the architectural behavior, and architecturally guest CR2 _must_ be up-to-date at all times because CR2 accesses cannot be intercepted. So, just say:

	/*
	 * Note, even though FRED delivers the faulting linear address via the
	 * event data field on the stack, CR2 is still updated.
	 */
Quoted 3 lines
arch/x86/kvm/vmx/vmx.c +0 -0
 	if (vcpu->arch.cr2 != native_read_cr2())
 		native_write_cr2(vcpu->arch.cr2);
 
author
#65 lore raw

RE: [PATCH v2 12/25] KVM: VMX: Handle FRED event data

Quoted 30 lines · Xin Li

Review static noinstr void vmx_vcpu_enter_exit(struct

Quoted 1 line
(quoted diff) +0 -0
@@ -7382,6 +7419,24 @@ static noinstr void vmx_vcpu_enter_exit(struct

kvm_vcpu *vcpu,

Quoted 11 lines
arch/x86/kvm/vmx/vmx.c +8 -0
 	vmx_disable_fb_clear(vmx);
 
+	/*
+	 * %cr2 needs to be saved after a VM exit and restored before a VM
+	 * entry in case a VM exit happens immediately after delivery of a
+	 * guest #PF but before guest reads %cr2.
+	 *
+	 * A FRED guest should read its #PF faulting linear address from
+	 * the event data field in its FRED stack frame instead of %cr2.
+	 * But the FRED 5.0 spec still requires a FRED CPU to update %cr2

arch/x86/kvm/vmx/vmx.c static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu, · line 7439

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	 * in the normal way, thus %cr2 is still updated even for a FRED
+	 * guest.
+	 *
+	 * Note, an NMI could interrupt KVM:
+	 *   1) after VM exit but before CR2 is saved.
+	 *   2) after CR2 is restored but before VM entry.
+	 * And a #PF could happen durng NMI handlng, which overwrites %cr2.
+	 * Thus exc_nmi() should save and restore %cr2 upon entering and
+	 * before leaving to make sure %cr2 not corrupted.
+	 */

This is 99.9% noise. What software does or does not do with respect to CR2 is completely irrelevant. The *only* thing that matters is the architectural behavior, and architecturally guest CR2 _must_ be up-to-date at all times because CR2 accesses cannot be intercepted. So, just say:

Quoted 4 lines
	/*
	 * Note, even though FRED delivers the faulting linear address via the
	 * event data field on the stack, CR2 is still updated.
	 */

Will do!

There is a reason for this comment because it won't be architectural:
https://lore.kernel.org/lkml/[email protected]/

FRED is designed to atomically save and restore _full_ supervisor/user context upon event delivery and return. But unfortunately, KVM still has to save/restore guest CR2 explicitly due to the issue mentioned above.

Thanks!
Xin

author
#66 lore raw

PATCH v2 13/25 KVM: VMX: Handle VMX nested exception for FRED

In reply to Xin Li

Set VMX nested exception bit in the VM-entry interruption information VMCS field when injecting a nested exception using FRED event delivery to ensure:
1) The nested exception is injected on a correct stack level.
2) The nested bit defined in FRED stack frame is set.

The event stack level used by FRED event delivery depends on whether the event was a nested exception encountered during delivery of another event, because a nested exception is "regarded" as happening on ring 0. E.g., when #PF is configured to use stack level 1 in IA32_FRED_STKLVLS MSR:
- nested #PF will be delivered on stack level 1 when encountered in

    ring 3.
  - normal #PF will be delivered on stack level 0 when encountered in
    ring 3.

The VMX nested-exception support ensures the correct event stack level is chosen when a VM entry injects a nested exception.

---

Changes since v1:
* Set the nested flag when there is an original interrupt (Chao Gao).

---
 arch/x86/include/asm/kvm_host.h |  6 +++--
 arch/x86/include/asm/vmx.h      |  5 ++--
 arch/x86/kvm/svm/svm.c          |  4 +--
 arch/x86/kvm/vmx/vmx.c          |  8 ++++--
 arch/x86/kvm/x86.c              | 46 ++++++++++++++++++++++++++-------
 arch/x86/kvm/x86.h              |  1 +
 6 files changed, 53 insertions(+), 17 deletions(-)
arch/x86/include/asm/kvm_host.h +4 -2
index 0d88873eba63..ef278ee0b6ca 100644
@@ -736,6 +736,7 @@ struct kvm_queued_exception {
 	u32 error_code;
 	unsigned long payload;
 	bool has_payload;
+	bool nested;
 };
 
 struct kvm_vcpu_arch {
@@ -2060,8 +2061,9 @@ 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 nr);
-void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
+void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr, bool nested);
+void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr,
+			     u32 error_code, bool nested);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault);
 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 				    struct x86_exception *fault);
arch/x86/include/asm/vmx.h +3 -2
index 6b796c5c9c2b..68af74e48788 100644
@@ -134,7 +134,7 @@
 #define VMX_BASIC_DUAL_MONITOR_TREATMENT	BIT_ULL(49)
 #define VMX_BASIC_INOUT				BIT_ULL(54)
 #define VMX_BASIC_TRUE_CTLS			BIT_ULL(55)
-
+#define VMX_BASIC_NESTED_EXCEPTION		BIT_ULL(58)
 
 /* VMX_MISC bits and bitmasks */
 #define VMX_MISC_INTEL_PT			BIT_ULL(14)
@@ -407,8 +407,9 @@ enum vmcs_field {
 #define INTR_INFO_INTR_TYPE_MASK        0x700           /* 10:8 */
 #define INTR_INFO_DELIVER_CODE_MASK     0x800           /* 11 */
 #define INTR_INFO_UNBLOCK_NMI		0x1000		/* 12 */
+#define INTR_INFO_NESTED_EXCEPTION_MASK	0x2000		/* 13 */
 #define INTR_INFO_VALID_MASK            0x80000000      /* 31 */
-#define INTR_INFO_RESVD_BITS_MASK       0x7ffff000
+#define INTR_INFO_RESVD_BITS_MASK       0x7fffd000
 
 #define VECTORING_INFO_VECTOR_MASK           	INTR_INFO_VECTOR_MASK
 #define VECTORING_INFO_TYPE_MASK        	INTR_INFO_INTR_TYPE_MASK
arch/x86/kvm/svm/svm.c +2 -2
index e90b429c84f1..c220b690a37c 100644
@@ -4057,10 +4057,10 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 
 		if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
 			u32 err = svm->vmcb->control.exit_int_info_err;
-			kvm_requeue_exception_e(vcpu, vector, err);
+			kvm_requeue_exception_e(vcpu, vector, err, false);
 
 		} else
-			kvm_requeue_exception(vcpu, vector);
+			kvm_requeue_exception(vcpu, vector, false);
 		break;
 	case SVM_EXITINTINFO_TYPE_INTR:
 		kvm_queue_interrupt(vcpu, vector, false);
arch/x86/kvm/vmx/vmx.c +6 -2
index f622fb90a098..1f265d526daf 100644
@@ -1891,6 +1891,8 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 				event_data = to_vmx(vcpu)->fred_xfd_event_data;
 
 			vmcs_write64(INJECTED_EVENT_DATA, event_data);
+
+			intr_info |= ex->nested ? INTR_INFO_NESTED_EXCEPTION_MASK : 0;
 		}
 	}
 
@@ -7281,9 +7283,11 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu, bool vectoring)
 		}
 
 		if (event_id & INTR_INFO_DELIVER_CODE_MASK)
-			kvm_requeue_exception_e(vcpu, vector, vmcs_read32(error_code_field));
+			kvm_requeue_exception_e(vcpu, vector, vmcs_read32(error_code_field),
+						event_id & INTR_INFO_NESTED_EXCEPTION_MASK);
 		else
-			kvm_requeue_exception(vcpu, vector);
+			kvm_requeue_exception(vcpu, vector,
+					      event_id & INTR_INFO_NESTED_EXCEPTION_MASK);
 		break;
 	case INTR_TYPE_SOFT_INTR:
 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
arch/x86/kvm/x86.c +37 -9

98 lines not on this page · raw message

arch/x86/kvm/x86.h +1 -0
index 9a52016ebf5a..c1f1d5696080 100644
@@ -108,6 +108,7 @@ static inline void kvm_clear_exception_queue(struct kvm_vcpu *vcpu)
 {
 	vcpu->arch.exception.pending = false;
 	vcpu->arch.exception.injected = false;
+	vcpu->arch.exception.nested = false;
 	vcpu->arch.exception_vmexit.pending = false;
 }
 
Signature · 1 line
2.43.0
#67 lore raw

Re: [PATCH v2 13/25] KVM: VMX: Handle VMX nested exception for FRED

Quoted 38 lines · Xin Li

Set VMX nested exception bit in the VM-entry interruption information VMCS field when injecting a nested exception using FRED event delivery to ensure:
1) The nested exception is injected on a correct stack level.
2) The nested bit defined in FRED stack frame is set.

The event stack level used by FRED event delivery depends on whether the event was a nested exception encountered during delivery of another event, because a nested exception is "regarded" as happening on ring 0. E.g., when #PF is configured to use stack level 1 in IA32_FRED_STKLVLS MSR:
- nested #PF will be delivered on stack level 1 when encountered in ring 3.
- normal #PF will be delivered on stack level 0 when encountered in ring 3.

The VMX nested-exception support ensures the correct event stack level is chosen when a VM entry injects a nested exception.

---

Changes since v1:
* Set the nested flag when there is an original interrupt (Chao Gao).
---

arch/x86/include/asm/kvm_host.h |  6 +++--
arch/x86/include/asm/vmx.h      |  5 ++--
arch/x86/kvm/svm/svm.c          |  4 +--
arch/x86/kvm/vmx/vmx.c          |  8 ++++--
arch/x86/kvm/x86.c              | 46 ++++++++++++++++++++++++++-------
arch/x86/kvm/x86.h              |  1 +
6 files changed, 53 insertions(+), 17 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 0d88873eba63..ef278ee0b6ca 100644

arch/x86/include/asm/kvm_host.h struct kvm_queued_exception { · line 739

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +1 -0
@@ -736,6 +736,7 @@ struct kvm_queued_exception {
 	u32 error_code;
 	unsigned long payload;
 	bool has_payload;
+	bool nested;

"nested" may be lost after migration.

Quoted 20 lines
arch/x86/include/asm/kvm_host.h +3 -2
 };
 
 struct kvm_vcpu_arch {
@@ -2060,8 +2061,9 @@ 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 nr);
-void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code);
+void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr, bool nested);
+void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr,
+			     u32 error_code, bool nested);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault);
 void kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
 				    struct x86_exception *fault);
arch/x86/include/asm/vmx.h +0 -0
index 6b796c5c9c2b..68af74e48788 100644

arch/x86/include/asm/vmx.h line 137

Quoted 5 lines
arch/x86/include/asm/vmx.h +1 -1
@@ -134,7 +134,7 @@
 #define VMX_BASIC_DUAL_MONITOR_TREATMENT	BIT_ULL(49)
 #define VMX_BASIC_INOUT				BIT_ULL(54)
 #define VMX_BASIC_TRUE_CTLS			BIT_ULL(55)
-
+#define VMX_BASIC_NESTED_EXCEPTION		BIT_ULL(58)

this definition is not used in this patch.

Quoted 73 lines
arch/x86/include/asm/vmx.h +2 -1
 /* VMX_MISC bits and bitmasks */
 #define VMX_MISC_INTEL_PT			BIT_ULL(14)
@@ -407,8 +407,9 @@ enum vmcs_field {
 #define INTR_INFO_INTR_TYPE_MASK        0x700           /* 10:8 */
 #define INTR_INFO_DELIVER_CODE_MASK     0x800           /* 11 */
 #define INTR_INFO_UNBLOCK_NMI		0x1000		/* 12 */
+#define INTR_INFO_NESTED_EXCEPTION_MASK	0x2000		/* 13 */
 #define INTR_INFO_VALID_MASK            0x80000000      /* 31 */
-#define INTR_INFO_RESVD_BITS_MASK       0x7ffff000
+#define INTR_INFO_RESVD_BITS_MASK       0x7fffd000
 
 #define VECTORING_INFO_VECTOR_MASK           	INTR_INFO_VECTOR_MASK
 #define VECTORING_INFO_TYPE_MASK        	INTR_INFO_INTR_TYPE_MASK
arch/x86/kvm/svm/svm.c +2 -2
index e90b429c84f1..c220b690a37c 100644
@@ -4057,10 +4057,10 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 
 		if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
 			u32 err = svm->vmcb->control.exit_int_info_err;
-			kvm_requeue_exception_e(vcpu, vector, err);
+			kvm_requeue_exception_e(vcpu, vector, err, false);
 
 		} else
-			kvm_requeue_exception(vcpu, vector);
+			kvm_requeue_exception(vcpu, vector, false);
 		break;
 	case SVM_EXITINTINFO_TYPE_INTR:
 		kvm_queue_interrupt(vcpu, vector, false);
arch/x86/kvm/vmx/vmx.c +6 -2
index f622fb90a098..1f265d526daf 100644
@@ -1891,6 +1891,8 @@ static void vmx_inject_exception(struct kvm_vcpu *vcpu)
 				event_data = to_vmx(vcpu)->fred_xfd_event_data;
 
 			vmcs_write64(INJECTED_EVENT_DATA, event_data);
+
+			intr_info |= ex->nested ? INTR_INFO_NESTED_EXCEPTION_MASK : 0;
 		}
 	}
 
@@ -7281,9 +7283,11 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu, bool vectoring)
 		}
 
 		if (event_id & INTR_INFO_DELIVER_CODE_MASK)
-			kvm_requeue_exception_e(vcpu, vector, vmcs_read32(error_code_field));
+			kvm_requeue_exception_e(vcpu, vector, vmcs_read32(error_code_field),
+						event_id & INTR_INFO_NESTED_EXCEPTION_MASK);
 		else
-			kvm_requeue_exception(vcpu, vector);
+			kvm_requeue_exception(vcpu, vector,
+					      event_id & INTR_INFO_NESTED_EXCEPTION_MASK);
 		break;
 	case INTR_TYPE_SOFT_INTR:
 		vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
arch/x86/kvm/x86.c +2 -1
index 00c0062726ae..725819262085 100644
@@ -645,7 +645,8 @@ static void kvm_leave_nested(struct kvm_vcpu *vcpu)
 
 static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
 		unsigned nr, bool has_error, u32 error_code,
-	        bool has_payload, unsigned long payload, bool reinject)
+	        bool has_payload, unsigned long payload,
+		bool reinject, bool nested)
 {
 	u32 prev_nr;
 	int class1, class2;

arch/x86/kvm/x86.c static void kvm_multiple_exception(struct kvm_vcpu *vcpu, · line 705

Quoted 9 lines
arch/x86/kvm/x86.c +6 -0
@@ -696,6 +697,13 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
 			vcpu->arch.exception.pending = true;
 			vcpu->arch.exception.injected = false;
 		}
+
+		vcpu->arch.exception.nested = vcpu->arch.exception.nested ||
+					      (kvm_is_fred_enabled(vcpu) &&
+					       ((reinject && nested) ||
+					        vcpu->arch.nmi_injected ||
+					        vcpu->arch.interrupt.injected));

You can set the nested flag regardless of FRED because the sole place using such information (vmx_inject_exception()) is guarded by kvm_is_fred_enabled() already.

I would also drop the check about @reinject to make @reinject and @nested orthogonal (i.e., avoid the artifical rule that nested interrupts should be queued by "reinject" only)

so, how about:

		if (vcpu->arch.nmi_injected || vcpu->arch.interrupt.injected ||
		    nested)
			vcpu->arch.exception.nested = true;
Quoted 19 lines
arch/x86/kvm/x86.c +10 -0
+
 		vcpu->arch.exception.has_error_code = has_error;
 		vcpu->arch.exception.vector = nr;
 		vcpu->arch.exception.error_code = error_code;
@@ -725,8 +733,28 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
 		vcpu->arch.exception.injected = false;
 		vcpu->arch.exception.pending = false;
 
+		/*
+		 * A #DF is NOT a nested event per its definition, however per
+		 * FRED spec 5.0 Appendix B, its delivery determines the new
+		 * stack level as is done for events occurring when CPL = 0.
+		 */
+		vcpu->arch.exception.nested = false;
+
 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
 	} else {
+		/*
+		 * FRED spec 5.0 Appendix B: delivery of a nested exception

arch/x86/kvm/x86.c static void kvm_multiple_exception(struct kvm_vcpu *vcpu, · line 756

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+		 * determines the new stack level as is done for events
+		 * occurring when CPL = 0.
+		 *
+		 * IOW, FRED event delivery of an event encountered in ring 3
+		 * normally uses stack level 0 unconditionally.  However, if
+		 * the event is an exception nested on any earlier event,
+		 * delivery of the nested exception will consult the FRED MSR
+		 * IA32_FRED_STKLVLS to determine which stack level to use.
+		 */
+		vcpu->arch.exception.nested = kvm_is_fred_enabled(vcpu);

as said above, nested flag can be set regardless of FRED.

#68 lore raw

Re: [PATCH v2 13/25] KVM: VMX: Handle VMX nested exception for FRED

In reply to Xin Li

arch/x86/kvm/x86.c static void kvm_multiple_exception(struct kvm_vcpu *vcpu, · line 740

Quoted 9 lines · Xin Li
arch/x86/kvm/x86.c +5 -0
@@ -725,8 +733,28 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
 		vcpu->arch.exception.injected = false;
 		vcpu->arch.exception.pending = false;
 
+		/*
+		 * A #DF is NOT a nested event per its definition, however per
+		 * FRED spec 5.0 Appendix B, its delivery determines the new
+		 * stack level as is done for events occurring when CPL = 0.
+		 */

Similar to my comments about CR2, this is mostly noise. Unless I'm missing a patch, KVM is not responsible for emulating the stack level stuff, and so there is zero reason to mention it, because it's not relevant to the KVM code. Simply say that #DF is defined to not be a nested exception.

		/* #DF is NOT a nested event, per its definition. */
Quoted 5 lines
arch/x86/kvm/x86.c +3 -0
+		vcpu->arch.exception.nested = false;
+
 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
 	} else {
+		/*

arch/x86/kvm/x86.c static void kvm_multiple_exception(struct kvm_vcpu *vcpu, · line 755

Quoted 10 lines
arch/x86/kvm/x86.c +10 -0
+		 * FRED spec 5.0 Appendix B: delivery of a nested exception
+		 * determines the new stack level as is done for events
+		 * occurring when CPL = 0.
+		 *
+		 * IOW, FRED event delivery of an event encountered in ring 3
+		 * normally uses stack level 0 unconditionally.  However, if
+		 * the event is an exception nested on any earlier event,
+		 * delivery of the nested exception will consult the FRED MSR
+		 * IA32_FRED_STKLVLS to determine which stack level to use.
+		 */

And drop this entirely. The above does not help the reader understand _why_ KVM sets nested=true for FRED. E.g. there's no CPL check here.

IMO, this code is entirely self-explanatory; KVM is quite obviously handling a back-to-back exceptions, and it doesn't take a big mental leap to grok that FRED tracks that information by describing the second exception as "nested".

Quoted 5 lines
arch/x86/kvm/x86.c +2 -0
+		vcpu->arch.exception.nested = kvm_is_fred_enabled(vcpu);
+
 		/* replace previous exception with a new one in a hope
 		   that instruction re-execution will regenerate lost
 		   exception */
author
#69 lore raw

PATCH v2 14/25 KVM: VMX: Disable FRED if FRED consistency checks fail

In reply to Xin Li

Refuse to virtualize FRED if FRED consistency checks fail.

---
 arch/x86/kvm/vmx/capabilities.h | 10 ++++++++++
 arch/x86/kvm/vmx/vmx.c          |  2 ++
 2 files changed, 12 insertions(+)
arch/x86/kvm/vmx/capabilities.h +10 -0
index e8f3ad0f79ee..73bf6618c425 100644
@@ -400,6 +400,16 @@ static inline bool vmx_pebs_supported(void)
 	return boot_cpu_has(X86_FEATURE_PEBS) && kvm_pmu_cap.pebs_ept;
 }
 
+static inline bool cpu_has_vmx_fred(void)
+{
+	return boot_cpu_has(X86_FEATURE_FRED) &&
+		(vmcs_config.basic & VMX_BASIC_NESTED_EXCEPTION) &&
+		(vmcs_config.vmexit_ctrl & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) &&
+		(vmcs_config.secondary_vmexit_ctrl & SECONDARY_VM_EXIT_SAVE_IA32_FRED) &&
+		(vmcs_config.secondary_vmexit_ctrl & SECONDARY_VM_EXIT_LOAD_IA32_FRED) &&
+		(vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_FRED);
+}
+
 static inline bool cpu_has_notify_vmexit(void)
 {
 	return vmcs_config.cpu_based_2nd_exec_ctrl &
arch/x86/kvm/vmx/vmx.c +2 -0
index 1f265d526daf..a484b9ac2400 100644
@@ -8113,6 +8113,8 @@ static __init void vmx_set_cpu_caps(void)
 		kvm_cpu_cap_check_and_set(X86_FEATURE_DS);
 		kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
 	}
+	if (!cpu_has_vmx_fred())
+		kvm_cpu_cap_clear(X86_FEATURE_FRED);
 
 	if (!enable_pmu)
 		kvm_cpu_cap_clear(X86_FEATURE_PDCM);
Signature · 1 line
2.43.0
#70 lore raw

Re: [PATCH v2 14/25] KVM: VMX: Disable FRED if FRED consistency checks fail

Quoted 1 line · Xin Li

Refuse to virtualize FRED if FRED consistency checks fail.

After reading this, I realize some consistency checks are missing in setup_vmcs_config(). Actually Sean requested some infrastructure for vmcs_entry_exit_pairs to deal with secondary_vmexit_ctrl.

https://lore.kernel.org/kvm/[email protected]/

#71 lore raw

Re: [PATCH v2 14/25] KVM: VMX: Disable FRED if FRED consistency checks fail

Quoted 6 lines · Chao Gao
Quoted 1 line · Xin Li

Refuse to virtualize FRED if FRED consistency checks fail.

After reading this, I realize some consistency checks are missing in setup_vmcs_config(). Actually Sean requested some infrastructure for vmcs_entry_exit_pairs to deal with secondary_vmexit_ctrl.

Yeah, this belongs in setup_vmcs_config(), e.g. to guarantee that discrepancies between CPUs are detected. I would also strongly prefer this be squashed with the patch(es) that introduce recognition of the FRED fields, if only so that we can avoid "consistency checks" in the shortlog (I thought this patch was going to disable FRED if a VM-Enter consistency check failed, which would be... interesting).

author
#72 lore raw

PATCH v2 15/25 KVM: VMX: Dump FRED context in dump_vmcs()

In reply to Xin Li

Add FRED related VMCS fields to dump_vmcs() to have it dump FRED context.

---

Change since v1:
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() (Chao Gao).
* Dump guest FRED states only if guest has FRED enabled (Nikolay Borisov).

---
 arch/x86/kvm/vmx/vmx.c | 46 +++++++++++++++++++++++++++++++++++-------
 1 file changed, 39 insertions(+), 7 deletions(-)
arch/x86/kvm/vmx/vmx.c +39 -7
index a484b9ac2400..e3409607122d 100644
@@ -6392,7 +6392,7 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 	u32 vmentry_ctl, vmexit_ctl;
 	u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
-	u64 tertiary_exec_control;
+	u64 tertiary_exec_control, secondary_vmexit_ctl;
 	unsigned long cr4;
 	int efer_slot;
 
@@ -6403,6 +6403,8 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
 
 	vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
 	vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
+	secondary_vmexit_ctl = cpu_has_secondary_vmexit_ctrls() ?
+			       vmcs_read64(SECONDARY_VM_EXIT_CONTROLS) : 0;
 	cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
 	pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
 	cr4 = vmcs_readl(GUEST_CR4);
@@ -6449,6 +6451,19 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
 	vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
 	vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
 	vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
+#ifdef CONFIG_X86_64
+	if (kvm_is_fred_enabled(vcpu)) {
+		pr_err("FRED guest: config=0x%016llx, stack levels=0x%016llx\n"
+		       "RSP0=0x%016lx, RSP1=0x%016llx\n"
+		       "RSP2=0x%016llx, RSP3=0x%016llx\n",
+		       vmcs_read64(GUEST_IA32_FRED_CONFIG),
+		       vmcs_read64(GUEST_IA32_FRED_STKLVLS),
+		       read_msr(MSR_IA32_FRED_RSP0),
+		       vmcs_read64(GUEST_IA32_FRED_RSP1),
+		       vmcs_read64(GUEST_IA32_FRED_RSP2),
+		       vmcs_read64(GUEST_IA32_FRED_RSP3));
+	}
+#endif
 	efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
 	if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
 		pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));
@@ -6496,6 +6511,19 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
 	       vmcs_readl(HOST_TR_BASE));
 	pr_err("GDTBase=%016lx IDTBase=%016lx\n",
 	       vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
+#ifdef CONFIG_X86_64
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		pr_err("FRED host: config=0x%016llx, stack levels=0x%016llx\n"
+		       "RSP0=0x%016llx, RSP1=0x%016llx\n"
+		       "RSP2=0x%016llx, RSP3=0x%016llx\n",
+		       vmcs_read64(HOST_IA32_FRED_CONFIG),
+		       vmcs_read64(HOST_IA32_FRED_STKLVLS),
+		       vmx->msr_host_fred_rsp0,
+		       vmcs_read64(HOST_IA32_FRED_RSP1),
+		       vmcs_read64(HOST_IA32_FRED_RSP2),
+		       vmcs_read64(HOST_IA32_FRED_RSP3));
+	}
+#endif
 	pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
 	       vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
 	       vmcs_readl(HOST_CR4));
@@ -6517,25 +6545,29 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
 	pr_err("*** Control State ***\n");
 	pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
 	       cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
-	pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
-	       pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);
+	pr_err("PinBased=0x%08x EntryControls=0x%08x\n",
+	       pin_based_exec_ctrl, vmentry_ctl);
+	pr_err("ExitControls=0x%08x SecondaryExitControls=0x%016llx\n",
+	       vmexit_ctl, secondary_vmexit_ctl);
 	pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
 	       vmcs_read32(EXCEPTION_BITMAP),
 	       vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
 	       vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
-	pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
+	pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x event data=%016llx\n",
 	       vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
 	       vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
-	       vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
+	       vmcs_read32(VM_ENTRY_INSTRUCTION_LEN),
+	       kvm_cpu_cap_has(X86_FEATURE_FRED) ? vmcs_read64(INJECTED_EVENT_DATA) : 0);
 	pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
 	       vmcs_read32(VM_EXIT_INTR_INFO),
 	       vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
 	       vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
 	pr_err("        reason=%08x qualification=%016lx\n",
 	       vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
-	pr_err("IDTVectoring: info=%08x errcode=%08x\n",
+	pr_err("IDTVectoring: info=%08x errcode=%08x event data=%016llx\n",
 	       vmcs_read32(IDT_VECTORING_INFO_FIELD),
-	       vmcs_read32(IDT_VECTORING_ERROR_CODE));
+	       vmcs_read32(IDT_VECTORING_ERROR_CODE),
+	       kvm_cpu_cap_has(X86_FEATURE_FRED) ? vmcs_read64(ORIGINAL_EVENT_DATA) : 0);
 	pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
 	if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
 		pr_err("TSC Multiplier = 0x%016llx\n",
Signature · 1 line
2.43.0
#73 lore raw

Re: [PATCH v2 15/25] KVM: VMX: Dump FRED context in dump_vmcs()

Quoted 36 lines · Xin Li

Add FRED related VMCS fields to dump_vmcs() to have it dump FRED context.

---

Change since v1:
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() (Chao Gao).
* Dump guest FRED states only if guest has FRED enabled (Nikolay Borisov).
---
arch/x86/kvm/vmx/vmx.c | 46 +++++++++++++++++++++++++++++++++++-------

1 file changed, 39 insertions(+), 7 deletions(-)
arch/x86/kvm/vmx/vmx.c +3 -1
index a484b9ac2400..e3409607122d 100644
@@ -6392,7 +6392,7 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
       struct vcpu_vmx *vmx = to_vmx(vcpu);
       u32 vmentry_ctl, vmexit_ctl;
       u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control;
-       u64 tertiary_exec_control;
+       u64 tertiary_exec_control, secondary_vmexit_ctl;
       unsigned long cr4;
       int efer_slot;
 
@@ -6403,6 +6403,8 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
 
       vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
       vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
+       secondary_vmexit_ctl = cpu_has_secondary_vmexit_ctrls() ?
+                              vmcs_read64(SECONDARY_VM_EXIT_CONTROLS) : 0;
       cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
       pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
       cr4 = vmcs_readl(GUEST_CR4);

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6455

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -6449,6 +6451,19 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
       vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
       vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
       vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
+#ifdef CONFIG_X86_64
+       if (kvm_is_fred_enabled(vcpu)) {

FRED MSRs are accessible even if CR4.FRED isn't set and #ifdef is ugly, I think you can simply do:

if (vmentry_ctrl & VM_ENTRY_LOAD_IA32_FRED)

just like below handling for EFER/PAT etc.

Quoted 15 lines
arch/x86/kvm/vmx/vmx.c +11 -0
+               pr_err("FRED guest: config=0x%016llx, stack levels=0x%016llx\n"
+                      "RSP0=0x%016lx, RSP1=0x%016llx\n"
+                      "RSP2=0x%016llx, RSP3=0x%016llx\n",
+                      vmcs_read64(GUEST_IA32_FRED_CONFIG),
+                      vmcs_read64(GUEST_IA32_FRED_STKLVLS),
+                      read_msr(MSR_IA32_FRED_RSP0),
+                      vmcs_read64(GUEST_IA32_FRED_RSP1),
+                      vmcs_read64(GUEST_IA32_FRED_RSP2),
+                      vmcs_read64(GUEST_IA32_FRED_RSP3));
+       }
+#endif
       efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER);
       if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER)
               pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER));

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6515

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -6496,6 +6511,19 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
              vmcs_readl(HOST_TR_BASE));
       pr_err("GDTBase=%016lx IDTBase=%016lx\n",
              vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
+#ifdef CONFIG_X86_64
+       if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {

ditto

Quoted 20 lines
arch/x86/kvm/vmx/vmx.c +11 -2
+               pr_err("FRED host: config=0x%016llx, stack levels=0x%016llx\n"
+                      "RSP0=0x%016llx, RSP1=0x%016llx\n"
+                      "RSP2=0x%016llx, RSP3=0x%016llx\n",
+                      vmcs_read64(HOST_IA32_FRED_CONFIG),
+                      vmcs_read64(HOST_IA32_FRED_STKLVLS),
+                      vmx->msr_host_fred_rsp0,
+                      vmcs_read64(HOST_IA32_FRED_RSP1),
+                      vmcs_read64(HOST_IA32_FRED_RSP2),
+                      vmcs_read64(HOST_IA32_FRED_RSP3));
+       }
+#endif
       pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
              vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
              vmcs_readl(HOST_CR4));
@@ -6517,25 +6545,29 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
       pr_err("*** Control State ***\n");
       pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n",
              cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control);
-       pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n",
-              pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl);

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6556

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +5 -1
+       pr_err("PinBased=0x%08x EntryControls=0x%08x\n",
+              pin_based_exec_ctrl, vmentry_ctl);
+       pr_err("ExitControls=0x%08x SecondaryExitControls=0x%016llx\n",
+              vmexit_ctl, secondary_vmexit_ctl);
       pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
              vmcs_read32(EXCEPTION_BITMAP),
              vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
              vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
-       pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
+       pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x event data=%016llx\n",

s/event data/event_data/

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6560

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +2 -1
              vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
              vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
-              vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
+              vmcs_read32(VM_ENTRY_INSTRUCTION_LEN),
+              kvm_cpu_cap_has(X86_FEATURE_FRED) ? vmcs_read64(INJECTED_EVENT_DATA) : 0);

again, it is better to check some vmexit/vmentry ctrl bit.

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6567

Quoted 8 lines
arch/x86/kvm/vmx/vmx.c +1 -1
       pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
              vmcs_read32(VM_EXIT_INTR_INFO),
              vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
              vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
       pr_err("        reason=%08x qualification=%016lx\n",
              vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
-       pr_err("IDTVectoring: info=%08x errcode=%08x\n",
+       pr_err("IDTVectoring: info=%08x errcode=%08x event data=%016llx\n",

s/event data/event_data/

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6570

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +2 -1
              vmcs_read32(IDT_VECTORING_INFO_FIELD),
-              vmcs_read32(IDT_VECTORING_ERROR_CODE));
+              vmcs_read32(IDT_VECTORING_ERROR_CODE),
+              kvm_cpu_cap_has(X86_FEATURE_FRED) ? vmcs_read64(ORIGINAL_EVENT_DATA) : 0);

ditto

#74 lore raw

Re: [PATCH v2 15/25] KVM: VMX: Dump FRED context in dump_vmcs()

Quoted 11 lines · Chao Gao

arch/x86/kvm/vmx/vmx.c void dump_vmcs(struct kvm_vcpu *vcpu) · line 6455

Quoted 6 lines · Xin Li
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -6449,6 +6451,19 @@ void dump_vmcs(struct kvm_vcpu *vcpu)
       vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
       vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
       vmx_dump_sel("TR:  ", GUEST_TR_SELECTOR);
+#ifdef CONFIG_X86_64
+       if (kvm_is_fred_enabled(vcpu)) {

FRED MSRs are accessible even if CR4.FRED isn't set and #ifdef is ugly, I think you can simply do:

Quoted 3 lines

if (vmentry_ctrl & VM_ENTRY_LOAD_IA32_FRED)

just like below handling for EFER/PAT etc.

+1

author
#75 lore raw

PATCH v2 16/25 KVM: VMX: Invoke vmx_set_cpu_caps() before nested setup

In reply to Xin Li

Set VMX CPU capabilities before initializing nested instead of after, as it needs to check VMX CPU capabilities to setup the VMX basic MSR for nested.

---
 arch/x86/kvm/vmx/vmx.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/vmx.c +2 -2
index e3409607122d..fc808d599493 100644
@@ -8912,6 +8912,8 @@ static __init int hardware_setup(void)
 
 	setup_default_sgx_lepubkeyhash();
 
+	vmx_set_cpu_caps();
+
 	if (nested) {
 		nested_vmx_setup_ctls_msrs(&vmcs_config, vmx_capability.ept);
 
@@ -8920,8 +8922,6 @@ static __init int hardware_setup(void)
 			return r;
 	}
 
-	vmx_set_cpu_caps();
-
 	r = alloc_kvm_area();
 	if (r && nested)
 		nested_vmx_hardware_unsetup();
Signature · 1 line
2.43.0
author
#76 lore raw

PATCH v2 17/25 KVM: nVMX: Add support for the secondary VM exit controls

In reply to Xin Li

Enable the secondary VM exit controls to prepare for nested FRED.

---
 Documentation/virt/kvm/x86/nested-vmx.rst |  1 +
 arch/x86/kvm/vmx/capabilities.h           |  1 +
 arch/x86/kvm/vmx/nested.c                 | 15 ++++++++++++++-
 arch/x86/kvm/vmx/vmcs12.c                 |  1 +
 arch/x86/kvm/vmx/vmcs12.h                 |  2 ++
 arch/x86/kvm/x86.h                        |  2 +-
 6 files changed, 20 insertions(+), 2 deletions(-)
Documentation/virt/kvm/x86/nested-vmx.rst +1 -0
index ac2095d41f02..e64ef231f310 100644
@@ -217,6 +217,7 @@ struct shadow_vmcs is ever changed.
 		u16 host_fs_selector;
 		u16 host_gs_selector;
 		u16 host_tr_selector;
+		u64 secondary_vm_exit_controls;
 	};
 
 
arch/x86/kvm/vmx/capabilities.h +1 -0
index 73bf6618c425..b41c2cde811d 100644
@@ -38,6 +38,7 @@ struct nested_vmx_msrs {
 	u32 pinbased_ctls_high;
 	u32 exit_ctls_low;
 	u32 exit_ctls_high;
+	u64 secondary_exit_ctls;
 	u32 entry_ctls_low;
 	u32 entry_ctls_high;
 	u32 misc_low;
arch/x86/kvm/vmx/nested.c +14 -1
index 8a5fda04e2de..1132e360ff13 100644
@@ -1431,6 +1431,7 @@ int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
 	case MSR_IA32_VMX_PINBASED_CTLS:
 	case MSR_IA32_VMX_PROCBASED_CTLS:
 	case MSR_IA32_VMX_EXIT_CTLS:
+	case MSR_IA32_VMX_EXIT_CTLS2:
 	case MSR_IA32_VMX_ENTRY_CTLS:
 		/*
 		 * The "non-true" VMX capability MSRs are generated from the
@@ -1509,6 +1510,9 @@ int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
 		if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
 			*pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
 		break;
+	case MSR_IA32_VMX_EXIT_CTLS2:
+		*pdata = msrs->secondary_exit_ctls;
+		break;
 	case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
 	case MSR_IA32_VMX_ENTRY_CTLS:
 		*pdata = vmx_control_msr(
@@ -2443,6 +2447,11 @@ static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct loaded_vmcs *vmcs0
 		exec_control &= ~VM_EXIT_LOAD_IA32_EFER;
 	vm_exit_controls_set(vmx, exec_control);
 
+	if (exec_control & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) {
+		exec_control = __secondary_vm_exit_controls_get(vmcs01);
+		secondary_vm_exit_controls_set(vmx, exec_control);
+	}
+
 	/*
 	 * Interrupt/Exception Fields
 	 */
@@ -6856,13 +6865,17 @@ static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
 		VM_EXIT_HOST_ADDR_SPACE_SIZE |
 #endif
 		VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT |
-		VM_EXIT_CLEAR_BNDCFGS;
+		VM_EXIT_CLEAR_BNDCFGS | VM_EXIT_ACTIVATE_SECONDARY_CONTROLS;
 	msrs->exit_ctls_high |=
 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
 		VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
 		VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT |
 		VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
 
+	/* secondary exit controls */
+	if (msrs->exit_ctls_high & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS)
+		rdmsrl(MSR_IA32_VMX_EXIT_CTLS2, msrs->secondary_exit_ctls);
+
 	/* We support free control of debug control saving. */
 	msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
 }
arch/x86/kvm/vmx/vmcs12.c +1 -0
index 106a72c923ca..98457d7b2b23 100644
@@ -73,6 +73,7 @@ const unsigned short vmcs12_field_offsets[] = {
 	FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
 	FIELD(CR3_TARGET_COUNT, cr3_target_count),
 	FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
+	FIELD(SECONDARY_VM_EXIT_CONTROLS, secondary_vm_exit_controls),
 	FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
 	FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
 	FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
arch/x86/kvm/vmx/vmcs12.h +2 -0
index 01936013428b..f50f897b9b5f 100644
@@ -185,6 +185,7 @@ struct __packed vmcs12 {
 	u16 host_gs_selector;
 	u16 host_tr_selector;
 	u16 guest_pml_index;
+	u64 secondary_vm_exit_controls;
 };
 
 /*
@@ -358,6 +359,7 @@ static inline void vmx_check_vmcs12_offsets(void)
 	CHECK_OFFSET(host_gs_selector, 992);
 	CHECK_OFFSET(host_tr_selector, 994);
 	CHECK_OFFSET(guest_pml_index, 996);
+	CHECK_OFFSET(secondary_vm_exit_controls, 998);
 }
 
 extern const unsigned short vmcs12_field_offsets[];
arch/x86/kvm/x86.h +1 -1
index c1f1d5696080..498bb6090b1e 100644
@@ -47,7 +47,7 @@ void kvm_spurious_fault(void);
  * associated feature that KVM supports for nested virtualization.
  */
 #define KVM_FIRST_EMULATED_VMX_MSR	MSR_IA32_VMX_BASIC
-#define KVM_LAST_EMULATED_VMX_MSR	MSR_IA32_VMX_VMFUNC
+#define KVM_LAST_EMULATED_VMX_MSR	MSR_IA32_VMX_EXIT_CTLS2
 
 #define KVM_DEFAULT_PLE_GAP		128
 #define KVM_VMX_DEFAULT_PLE_WINDOW	4096
Signature · 1 line
2.43.0
#77 lore raw

Re: [PATCH v2 17/25] KVM: nVMX: Add support for the secondary VM exit controls

arch/x86/kvm/vmx/nested.c static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf, · line 6875

Quoted 13 lines · Xin Li
arch/x86/kvm/vmx/nested.c +2 -1
@@ -6856,13 +6865,17 @@ static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
 		VM_EXIT_HOST_ADDR_SPACE_SIZE |
 #endif
 		VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT |
-		VM_EXIT_CLEAR_BNDCFGS;
+		VM_EXIT_CLEAR_BNDCFGS | VM_EXIT_ACTIVATE_SECONDARY_CONTROLS;
 	msrs->exit_ctls_high |=
 		VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
 		VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
 		VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT |
 		VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
 
+	/* secondary exit controls */

Drop the comment, it's pretty obvious what field is being setup.

arch/x86/kvm/vmx/nested.c static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf, · line 6877

Quoted 2 lines
arch/x86/kvm/vmx/nested.c +2 -0
+	if (msrs->exit_ctls_high & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS)
+		rdmsrl(MSR_IA32_VMX_EXIT_CTLS2, msrs->secondary_exit_ctls);

This is wrong, the resulting msrs->secondary_exit_ctls needs to be sanitized based on what KVM supports for nVMX.

On a very related topic, this should not do a raw RDMSR. One of the reasons why KVM uses vmcs_config as the base is to avoid advertising features to L1 that KVM itself doesn't support, e.g. because the expected entry+exit pairs aren't supported.

And by pulling state from vmcs_conf->secondary_exit_ctls there's no need to check the activation bit.

I.e. literaly just this:

	msrs->secondary_exit_ctls = vmcs_conf->secondary_exit_ctls;
	msrs->secondary_exit_ctls &= 0;

and then when nVMX FRED support is ready, it becomes:

	msrs->secondary_exit_ctls = vmcs_conf->secondary_exit_ctls;
	msrs->secondary_exit_ctls &= SECONDARY_VM_EXIT_SAVE_IA32_FRED |
				     SECONDARY_VM_EXIT_LOAD_IA32_FRED;
author
#78 lore raw

PATCH v2 18/25 KVM: nVMX: Add a prerequisite to SHADOW_FIELD_R[OW] macros

In reply to Xin Li

Add a prerequisite for accessing VMCS fields referenced in macros SHADOW_FIELD_R[OW], because a VMCS field may not exist on some CPUs.

---
 arch/x86/kvm/vmx/nested.c             | 70 ++++++++++++++++++------
 arch/x86/kvm/vmx/vmcs_shadow_fields.h | 76 +++++++++++++--------------
 2 files changed, 91 insertions(+), 55 deletions(-)
arch/x86/kvm/vmx/nested.c +53 -17
index 1132e360ff13..94da6a0a2f81 100644
@@ -53,14 +53,14 @@ struct shadow_vmcs_field {
 	u16	offset;
 };
 static struct shadow_vmcs_field shadow_read_only_fields[] = {
-#define SHADOW_FIELD_RO(x, y) { x, offsetof(struct vmcs12, y) },
+#define SHADOW_FIELD_RO(x, y, c) { x, offsetof(struct vmcs12, y) },
 #include "vmcs_shadow_fields.h"
 };
 static int max_shadow_read_only_fields =
 	ARRAY_SIZE(shadow_read_only_fields);
 
 static struct shadow_vmcs_field shadow_read_write_fields[] = {
-#define SHADOW_FIELD_RW(x, y) { x, offsetof(struct vmcs12, y) },
+#define SHADOW_FIELD_RW(x, y, c) { x, offsetof(struct vmcs12, y) },
 #include "vmcs_shadow_fields.h"
 };
 static int max_shadow_read_write_fields =
@@ -83,6 +83,17 @@ static void init_vmcs_shadow_fields(void)
 			pr_err("Missing field from shadow_read_only_field %x\n",
 			       field + 1);
 
+		switch (field) {
+#define SHADOW_FIELD_RO(x, y, c)		\
+		case x:				\
+			if (!(c))		\
+				continue;	\
+			break;
+#include "vmcs_shadow_fields.h"
+		default:
+			break;
+		}
+
 		clear_bit(field, vmx_vmread_bitmap);
 		if (field & 1)
 #ifdef CONFIG_X86_64
@@ -114,18 +125,12 @@ static void init_vmcs_shadow_fields(void)
 		 * on bare metal.
 		 */
 		switch (field) {
-		case GUEST_PML_INDEX:
-			if (!cpu_has_vmx_pml())
-				continue;
-			break;
-		case VMX_PREEMPTION_TIMER_VALUE:
-			if (!cpu_has_vmx_preemption_timer())
-				continue;
-			break;
-		case GUEST_INTR_STATUS:
-			if (!cpu_has_vmx_apicv())
-				continue;
+#define SHADOW_FIELD_RW(x, y, c)		\
+		case x:				\
+			if (!(c))		\
+				continue;	\
 			break;
+#include "vmcs_shadow_fields.h"
 		default:
 			break;
 		}
@@ -1585,6 +1590,18 @@ static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
 
 	for (i = 0; i < max_shadow_read_write_fields; i++) {
 		field = shadow_read_write_fields[i];
+
+		switch (field.encoding) {
+#define SHADOW_FIELD_RW(x, y, c)		\
+		case x:				\
+			if (!(c))		\
+				continue;	\
+			break;
+#include "vmcs_shadow_fields.h"
+		default:
+			break;
+		}
+
 		val = __vmcs_readl(field.encoding);
 		vmcs12_write_any(vmcs12, field.encoding, field.offset, val);
 	}
@@ -1619,6 +1636,23 @@ static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
 	for (q = 0; q < ARRAY_SIZE(fields); q++) {
 		for (i = 0; i < max_fields[q]; i++) {
 			field = fields[q][i];
+
+			switch (field.encoding) {
+#define SHADOW_FIELD_RO(x, y, c)			\
+			case x:				\
+				if (!(c))		\
+					continue;	\
+				break;
+#define SHADOW_FIELD_RW(x, y, c)			\
+			case x:				\
+				if (!(c))		\
+					continue;	\
+				break;
+#include "vmcs_shadow_fields.h"
+			default:
+				break;
+			}
+
 			val = vmcs12_read_any(vmcs12, field.encoding,
 					      field.offset);
 			__vmcs_writel(field.encoding, val);
@@ -5492,9 +5526,10 @@ static int handle_vmread(struct kvm_vcpu *vcpu)
 static bool is_shadow_field_rw(unsigned long field)
 {
 	switch (field) {
-#define SHADOW_FIELD_RW(x, y) case x:
+#define SHADOW_FIELD_RW(x, y, c)	\
+	case x:				\
+		return c;
 #include "vmcs_shadow_fields.h"
-		return true;
 	default:
 		break;
 	}
@@ -5504,9 +5539,10 @@ static bool is_shadow_field_rw(unsigned long field)
 static bool is_shadow_field_ro(unsigned long field)
 {
 	switch (field) {
-#define SHADOW_FIELD_RO(x, y) case x:
+#define SHADOW_FIELD_RO(x, y, c)	\
+	case x:				\
+		return c;
 #include "vmcs_shadow_fields.h"
-		return true;
 	default:
 		break;
 	}
arch/x86/kvm/vmx/vmcs_shadow_fields.h +38 -38

96 lines not on this page · raw message

Signature · 1 line
2.43.0
#79 lore raw

Re: [PATCH v2 18/25] KVM: nVMX: Add a prerequisite to SHADOW_FIELD_R[OW] macros

Quoted 72 lines · Xin Li
arch/x86/kvm/vmx/vmcs_shadow_fields.h +30 -34
@@ -32,48 +32,48 @@ BUILD_BUG_ON(1)
  */
 
 /* 16-bits */
-SHADOW_FIELD_RW(GUEST_INTR_STATUS, guest_intr_status)
-SHADOW_FIELD_RW(GUEST_PML_INDEX, guest_pml_index)
-SHADOW_FIELD_RW(HOST_FS_SELECTOR, host_fs_selector)
-SHADOW_FIELD_RW(HOST_GS_SELECTOR, host_gs_selector)
+SHADOW_FIELD_RW(GUEST_INTR_STATUS, guest_intr_status, cpu_has_vmx_apicv())
+SHADOW_FIELD_RW(GUEST_PML_INDEX, guest_pml_index, cpu_has_vmx_pml())
+SHADOW_FIELD_RW(HOST_FS_SELECTOR, host_fs_selector, true)
+SHADOW_FIELD_RW(HOST_GS_SELECTOR, host_gs_selector, true)
 
 /* 32-bits */
-SHADOW_FIELD_RO(VM_EXIT_REASON, vm_exit_reason)
-SHADOW_FIELD_RO(VM_EXIT_INTR_INFO, vm_exit_intr_info)
-SHADOW_FIELD_RO(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len)
-SHADOW_FIELD_RO(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field)
-SHADOW_FIELD_RO(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code)
-SHADOW_FIELD_RO(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code)
-SHADOW_FIELD_RO(GUEST_CS_AR_BYTES, guest_cs_ar_bytes)
-SHADOW_FIELD_RO(GUEST_SS_AR_BYTES, guest_ss_ar_bytes)
-SHADOW_FIELD_RW(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control)
-SHADOW_FIELD_RW(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control)
-SHADOW_FIELD_RW(EXCEPTION_BITMAP, exception_bitmap)
-SHADOW_FIELD_RW(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code)
-SHADOW_FIELD_RW(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field)
-SHADOW_FIELD_RW(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len)
-SHADOW_FIELD_RW(TPR_THRESHOLD, tpr_threshold)
-SHADOW_FIELD_RW(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info)
-SHADOW_FIELD_RW(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value)
+SHADOW_FIELD_RO(VM_EXIT_REASON, vm_exit_reason, true)
+SHADOW_FIELD_RO(VM_EXIT_INTR_INFO, vm_exit_intr_info, true)
+SHADOW_FIELD_RO(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len, true)
+SHADOW_FIELD_RO(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code, true)
+SHADOW_FIELD_RO(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field, true)
+SHADOW_FIELD_RO(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code, true)
+SHADOW_FIELD_RO(GUEST_CS_AR_BYTES, guest_cs_ar_bytes, true)
+SHADOW_FIELD_RO(GUEST_SS_AR_BYTES, guest_ss_ar_bytes, true)
+SHADOW_FIELD_RW(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control, true)
+SHADOW_FIELD_RW(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control, true)
+SHADOW_FIELD_RW(EXCEPTION_BITMAP, exception_bitmap, true)
+SHADOW_FIELD_RW(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code, true)
+SHADOW_FIELD_RW(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field, true)
+SHADOW_FIELD_RW(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len, true)
+SHADOW_FIELD_RW(TPR_THRESHOLD, tpr_threshold, true)
+SHADOW_FIELD_RW(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info, true)
+SHADOW_FIELD_RW(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value, cpu_has_vmx_preemption_timer())
 
 /* Natural width */
-SHADOW_FIELD_RO(EXIT_QUALIFICATION, exit_qualification)
-SHADOW_FIELD_RO(GUEST_LINEAR_ADDRESS, guest_linear_address)
-SHADOW_FIELD_RW(GUEST_RIP, guest_rip)
-SHADOW_FIELD_RW(GUEST_RSP, guest_rsp)
-SHADOW_FIELD_RW(GUEST_CR0, guest_cr0)
-SHADOW_FIELD_RW(GUEST_CR3, guest_cr3)
-SHADOW_FIELD_RW(GUEST_CR4, guest_cr4)
-SHADOW_FIELD_RW(GUEST_RFLAGS, guest_rflags)
-SHADOW_FIELD_RW(CR0_GUEST_HOST_MASK, cr0_guest_host_mask)
-SHADOW_FIELD_RW(CR0_READ_SHADOW, cr0_read_shadow)
-SHADOW_FIELD_RW(CR4_READ_SHADOW, cr4_read_shadow)
-SHADOW_FIELD_RW(HOST_FS_BASE, host_fs_base)
-SHADOW_FIELD_RW(HOST_GS_BASE, host_gs_base)
+SHADOW_FIELD_RO(EXIT_QUALIFICATION, exit_qualification, true)
+SHADOW_FIELD_RO(GUEST_LINEAR_ADDRESS, guest_linear_address, true)
+SHADOW_FIELD_RW(GUEST_RIP, guest_rip, true)
+SHADOW_FIELD_RW(GUEST_RSP, guest_rsp, true)
+SHADOW_FIELD_RW(GUEST_CR0, guest_cr0, true)
+SHADOW_FIELD_RW(GUEST_CR3, guest_cr3, true)
+SHADOW_FIELD_RW(GUEST_CR4, guest_cr4, true)
+SHADOW_FIELD_RW(GUEST_RFLAGS, guest_rflags, true)
+SHADOW_FIELD_RW(CR0_GUEST_HOST_MASK, cr0_guest_host_mask, true)

arch/x86/kvm/vmx/vmcs_shadow_fields.h BUILD_BUG_ON(1) · line 76

Quoted 10 lines
arch/x86/kvm/vmx/vmcs_shadow_fields.h +6 -2
+SHADOW_FIELD_RW(CR0_READ_SHADOW, cr0_read_shadow, true)
+SHADOW_FIELD_RW(CR4_READ_SHADOW, cr4_read_shadow, true)
+SHADOW_FIELD_RW(HOST_FS_BASE, host_fs_base, true)
+SHADOW_FIELD_RW(HOST_GS_BASE, host_gs_base, true)
 
 /* 64-bit */
-SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS, guest_physical_address)
-SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS_HIGH, guest_physical_address)
+SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS, guest_physical_address, true)
+SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS_HIGH, guest_physical_address, true)

This is not a net postive for readability or maintability. I don't hate the idea, it just needs MOAR MACROs :-) E.g. add a layer for the common case where the field unconditionally exists.

#ifndef __SHADOW_FIELD_RO
#define __SHADOW_FIELD_RO(x, y, c)
#endif
#ifndef __SHADOW_FIELD_RW
#define __SHADOW_FIELD_RW(x, y, c)
#endif

#define SHADOW_FIELD_RO(x, y) __SHADOW_FIELD_RO(x, y, true) #define SHADOW_FIELD_RW(x, y) __SHADOW_FIELD_RW(x, y, true)

author
#80 lore raw

PATCH v2 19/25 KVM: nVMX: Add FRED VMCS fields

In reply to Xin Li

Add FRED VMCS fields to nested VMX context management.

Todo: change VMCS12_REVISION, as struct vmcs12 is changed.

---

Change since v1:
* Remove hyperv TLFS related changes (Jeremi Piotrowski).
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() (Chao Gao).

---
 Documentation/virt/kvm/x86/nested-vmx.rst | 18 +++++
 arch/x86/kvm/vmx/nested.c                 | 91 +++++++++++++++++++----
 arch/x86/kvm/vmx/vmcs12.c                 | 18 +++++
 arch/x86/kvm/vmx/vmcs12.h                 | 36 +++++++++
 arch/x86/kvm/vmx/vmcs_shadow_fields.h     |  4 +
 5 files changed, 152 insertions(+), 15 deletions(-)
Documentation/virt/kvm/x86/nested-vmx.rst +18 -0
index e64ef231f310..87fa9f3877ab 100644
@@ -218,6 +218,24 @@ struct shadow_vmcs is ever changed.
 		u16 host_gs_selector;
 		u16 host_tr_selector;
 		u64 secondary_vm_exit_controls;
+		u64 guest_ia32_fred_config;
+		u64 guest_ia32_fred_rsp1;
+		u64 guest_ia32_fred_rsp2;
+		u64 guest_ia32_fred_rsp3;
+		u64 guest_ia32_fred_stklvls;
+		u64 guest_ia32_fred_ssp1;
+		u64 guest_ia32_fred_ssp2;
+		u64 guest_ia32_fred_ssp3;
+		u64 host_ia32_fred_config;
+		u64 host_ia32_fred_rsp1;
+		u64 host_ia32_fred_rsp2;
+		u64 host_ia32_fred_rsp3;
+		u64 host_ia32_fred_stklvls;
+		u64 host_ia32_fred_ssp1;
+		u64 host_ia32_fred_ssp2;
+		u64 host_ia32_fred_ssp3;
+		u64 injected_event_data;
+		u64 original_event_data;
 	};
 
 
arch/x86/kvm/vmx/nested.c +76 -15

159 lines not on this page · raw message

arch/x86/kvm/vmx/vmcs12.c +18 -0
index 98457d7b2b23..59f17fdfad11 100644
@@ -80,6 +80,7 @@ const unsigned short vmcs12_field_offsets[] = {
 	FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
 	FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
 	FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
+	FIELD(INJECTED_EVENT_DATA, injected_event_data),
 	FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
 	FIELD(TPR_THRESHOLD, tpr_threshold),
 	FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
@@ -89,6 +90,7 @@ const unsigned short vmcs12_field_offsets[] = {
 	FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
 	FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
 	FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
+	FIELD(ORIGINAL_EVENT_DATA, original_event_data),
 	FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
 	FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
 	FIELD(GUEST_ES_LIMIT, guest_es_limit),
@@ -152,5 +154,21 @@ const unsigned short vmcs12_field_offsets[] = {
 	FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
 	FIELD(HOST_RSP, host_rsp),
 	FIELD(HOST_RIP, host_rip),
+	FIELD(GUEST_IA32_FRED_CONFIG, guest_ia32_fred_config),
+	FIELD(GUEST_IA32_FRED_RSP1, guest_ia32_fred_rsp1),
+	FIELD(GUEST_IA32_FRED_RSP2, guest_ia32_fred_rsp2),
+	FIELD(GUEST_IA32_FRED_RSP3, guest_ia32_fred_rsp3),
+	FIELD(GUEST_IA32_FRED_STKLVLS, guest_ia32_fred_stklvls),
+	FIELD(GUEST_IA32_FRED_SSP1, guest_ia32_fred_ssp1),
+	FIELD(GUEST_IA32_FRED_SSP2, guest_ia32_fred_ssp2),
+	FIELD(GUEST_IA32_FRED_SSP3, guest_ia32_fred_ssp3),
+	FIELD(HOST_IA32_FRED_CONFIG, host_ia32_fred_config),
+	FIELD(HOST_IA32_FRED_RSP1, host_ia32_fred_rsp1),
+	FIELD(HOST_IA32_FRED_RSP2, host_ia32_fred_rsp2),
+	FIELD(HOST_IA32_FRED_RSP3, host_ia32_fred_rsp3),
+	FIELD(HOST_IA32_FRED_STKLVLS, host_ia32_fred_stklvls),
+	FIELD(HOST_IA32_FRED_SSP1, host_ia32_fred_ssp1),
+	FIELD(HOST_IA32_FRED_SSP2, host_ia32_fred_ssp2),
+	FIELD(HOST_IA32_FRED_SSP3, host_ia32_fred_ssp3),
 };
 const unsigned int nr_vmcs12_fields = ARRAY_SIZE(vmcs12_field_offsets);
arch/x86/kvm/vmx/vmcs12.h +36 -0
index f50f897b9b5f..edf7fcef8ccf 100644
@@ -186,6 +186,24 @@ struct __packed vmcs12 {
 	u16 host_tr_selector;
 	u16 guest_pml_index;
 	u64 secondary_vm_exit_controls;
+	u64 guest_ia32_fred_config;
+	u64 guest_ia32_fred_rsp1;
+	u64 guest_ia32_fred_rsp2;
+	u64 guest_ia32_fred_rsp3;
+	u64 guest_ia32_fred_stklvls;
+	u64 guest_ia32_fred_ssp1;
+	u64 guest_ia32_fred_ssp2;
+	u64 guest_ia32_fred_ssp3;
+	u64 host_ia32_fred_config;
+	u64 host_ia32_fred_rsp1;
+	u64 host_ia32_fred_rsp2;
+	u64 host_ia32_fred_rsp3;
+	u64 host_ia32_fred_stklvls;
+	u64 host_ia32_fred_ssp1;
+	u64 host_ia32_fred_ssp2;
+	u64 host_ia32_fred_ssp3;
+	u64 injected_event_data;
+	u64 original_event_data;
 };
 
 /*
@@ -360,6 +378,24 @@ static inline void vmx_check_vmcs12_offsets(void)
 	CHECK_OFFSET(host_tr_selector, 994);
 	CHECK_OFFSET(guest_pml_index, 996);
 	CHECK_OFFSET(secondary_vm_exit_controls, 998);
+	CHECK_OFFSET(guest_ia32_fred_config, 1006);
+	CHECK_OFFSET(guest_ia32_fred_rsp1, 1014);
+	CHECK_OFFSET(guest_ia32_fred_rsp2, 1022);
+	CHECK_OFFSET(guest_ia32_fred_rsp3, 1030);
+	CHECK_OFFSET(guest_ia32_fred_stklvls, 1038);
+	CHECK_OFFSET(guest_ia32_fred_ssp1, 1046);
+	CHECK_OFFSET(guest_ia32_fred_ssp2, 1054);
+	CHECK_OFFSET(guest_ia32_fred_ssp3, 1062);
+	CHECK_OFFSET(host_ia32_fred_config, 1070);
+	CHECK_OFFSET(host_ia32_fred_rsp1, 1078);
+	CHECK_OFFSET(host_ia32_fred_rsp2, 1086);
+	CHECK_OFFSET(host_ia32_fred_rsp3, 1094);
+	CHECK_OFFSET(host_ia32_fred_stklvls, 1102);
+	CHECK_OFFSET(host_ia32_fred_ssp1, 1110);
+	CHECK_OFFSET(host_ia32_fred_ssp2, 1118);
+	CHECK_OFFSET(host_ia32_fred_ssp3, 1126);
+	CHECK_OFFSET(injected_event_data, 1134);
+	CHECK_OFFSET(original_event_data, 1142);
 }
 
 extern const unsigned short vmcs12_field_offsets[];
arch/x86/kvm/vmx/vmcs_shadow_fields.h +4 -0
index 7f48056fe351..3885a3e0fbe8 100644
@@ -74,6 +74,10 @@ SHADOW_FIELD_RW(HOST_GS_BASE, host_gs_base, true)
 /* 64-bit */
 SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS, guest_physical_address, true)
 SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS_HIGH, guest_physical_address, true)
+SHADOW_FIELD_RO(ORIGINAL_EVENT_DATA, original_event_data, kvm_cpu_cap_has(X86_FEATURE_FRED))
+SHADOW_FIELD_RO(ORIGINAL_EVENT_DATA_HIGH, original_event_data, kvm_cpu_cap_has(X86_FEATURE_FRED))
+SHADOW_FIELD_RW(INJECTED_EVENT_DATA, injected_event_data, kvm_cpu_cap_has(X86_FEATURE_FRED))
+SHADOW_FIELD_RW(INJECTED_EVENT_DATA_HIGH, injected_event_data, kvm_cpu_cap_has(X86_FEATURE_FRED))
 
 #undef SHADOW_FIELD_RO
 #undef SHADOW_FIELD_RW
Signature · 1 line
2.43.0
#81 lore raw

Re: [PATCH v2 19/25] KVM: nVMX: Add FRED VMCS fields

Quoted 3 lines · Xin Li

Add FRED VMCS fields to nested VMX context management.

Todo: change VMCS12_REVISION, as struct vmcs12 is changed.

It actually doesn't, the comment is just stale. At this point, KVM must _never_ change VMCS12_REVISION as doing so will break backwards compatibility.

I'll post this once I've written a changelog:

---
 arch/x86/kvm/vmx/vmcs12.h | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/vmcs12.h +4 -5
index edf7fcef8ccf..d67bebb9f1c2 100644
@@ -207,11 +207,9 @@ struct __packed vmcs12 {
 };
 
 /*
- * VMCS12_REVISION is an arbitrary id that should be changed if the content or
- * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
- * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
+ * VMCS12_REVISION is KVM's arbitrary id for the layout of struct vmcs12.
  *
- * IMPORTANT: Changing this value will break save/restore compatibility with
+ * DO NOT change this value, as it will break save/restore compatibility with
  * older kvm releases.
  */
 #define VMCS12_REVISION 0x11e57ed0
@@ -225,7 +223,8 @@ struct __packed vmcs12 {
 #define VMCS12_SIZE		KVM_STATE_NESTED_VMX_VMCS_SIZE
 
 /*
- * For save/restore compatibility, the vmcs12 field offsets must not change.
+ * For save/restore compatibility, the vmcs12 field offsets must not change,
+ * although appending fields and/or filling gaps is obviously allowed.
  */
 #define CHECK_OFFSET(field, loc) \
 	ASSERT_STRUCT_OFFSET(struct vmcs12, field, loc)

base-commit: 878fe4c2f7eead383f2b306cbafd300006dd518c

Quoted 59 lines

---

Change since v1:
* Remove hyperv TLFS related changes (Jeremi Piotrowski).
* Use kvm_cpu_cap_has() instead of cpu_feature_enabled() (Chao Gao).

---
 Documentation/virt/kvm/x86/nested-vmx.rst | 18 +++++
 arch/x86/kvm/vmx/nested.c                 | 91 +++++++++++++++++++----
 arch/x86/kvm/vmx/vmcs12.c                 | 18 +++++
 arch/x86/kvm/vmx/vmcs12.h                 | 36 +++++++++
 arch/x86/kvm/vmx/vmcs_shadow_fields.h     |  4 +
 5 files changed, 152 insertions(+), 15 deletions(-)
Documentation/virt/kvm/x86/nested-vmx.rst +18 -0
index e64ef231f310..87fa9f3877ab 100644
@@ -218,6 +218,24 @@ struct shadow_vmcs is ever changed.
 		u16 host_gs_selector;
 		u16 host_tr_selector;
 		u64 secondary_vm_exit_controls;
+		u64 guest_ia32_fred_config;
+		u64 guest_ia32_fred_rsp1;
+		u64 guest_ia32_fred_rsp2;
+		u64 guest_ia32_fred_rsp3;
+		u64 guest_ia32_fred_stklvls;
+		u64 guest_ia32_fred_ssp1;
+		u64 guest_ia32_fred_ssp2;
+		u64 guest_ia32_fred_ssp3;
+		u64 host_ia32_fred_config;
+		u64 host_ia32_fred_rsp1;
+		u64 host_ia32_fred_rsp2;
+		u64 host_ia32_fred_rsp3;
+		u64 host_ia32_fred_stklvls;
+		u64 host_ia32_fred_ssp1;
+		u64 host_ia32_fred_ssp2;
+		u64 host_ia32_fred_ssp3;
+		u64 injected_event_data;
+		u64 original_event_data;
 	};
 
 
arch/x86/kvm/vmx/nested.c +3 -0
index 94da6a0a2f81..f9c1fbeac302 100644
@@ -686,6 +686,9 @@ static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
 
 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
 					 MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
+
+	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
+					 MSR_IA32_FRED_RSP0, MSR_TYPE_RW);
 #endif
 	nested_vmx_set_intercept_for_msr(vmx, msr_bitmap_l1, msr_bitmap_l0,
 					 MSR_IA32_SPEC_CTRL, MSR_TYPE_RW);

arch/x86/kvm/vmx/nested.c static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct loaded_vmcs *vmcs0 · line 2504

Quoted 4 lines
arch/x86/kvm/vmx/nested.c +1 -0
@@ -2498,6 +2501,8 @@ static void prepare_vmcs02_early(struct vcpu_vmx *vmx, struct loaded_vmcs *vmcs0
 			     vmcs12->vm_entry_instruction_len);
 		vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
 			     vmcs12->guest_interruptibility_info);
+		if (kvm_cpu_cap_has(X86_FEATURE_FRED))

This is wrong, vmcs02 should be set from vmcs12 if and only if the field is enabled in L1's VMX configuration, i.e. iff nested_cpu_has(vmcs12, ???).

Note, the ??? should be tied to whatever VMX MSR feature flag enumerates INJECTED_EVENT_DATA. KVM's clearing of X86_FEATURE_FRED when one or more pieces is missing is a software decision, i.e. not archictectural.

arch/x86/kvm/vmx/nested.c static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12) · line 2556

Quoted 9 lines
arch/x86/kvm/vmx/nested.c +2 -0
+			vmcs_write64(INJECTED_EVENT_DATA, vmcs12->injected_event_data);
 		vmx->loaded_vmcs->nmi_known_unmasked =
 			!(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
 	} else {
@@ -2548,6 +2553,17 @@ static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
 		vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
 		vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
 
+		if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {

Same thing here.

Quoted 14 lines
arch/x86/kvm/vmx/nested.c +10 -0
+			vmcs_write64(GUEST_IA32_FRED_CONFIG, vmcs12->guest_ia32_fred_config);
+			vmcs_write64(GUEST_IA32_FRED_RSP1, vmcs12->guest_ia32_fred_rsp1);
+			vmcs_write64(GUEST_IA32_FRED_RSP2, vmcs12->guest_ia32_fred_rsp2);
+			vmcs_write64(GUEST_IA32_FRED_RSP3, vmcs12->guest_ia32_fred_rsp3);
+			vmcs_write64(GUEST_IA32_FRED_STKLVLS, vmcs12->guest_ia32_fred_stklvls);
+			vmcs_write64(GUEST_IA32_FRED_SSP1, vmcs12->guest_ia32_fred_ssp1);
+			vmcs_write64(GUEST_IA32_FRED_SSP2, vmcs12->guest_ia32_fred_ssp2);
+			vmcs_write64(GUEST_IA32_FRED_SSP3, vmcs12->guest_ia32_fred_ssp3);
+		}
+
 		vmx->segment_cache.bitmask = 0;
 	}
 

arch/x86/kvm/vmx/nested.c vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) · line 3855

Quoted 5 lines
arch/x86/kvm/vmx/nested.c +2 -0
@@ -3835,6 +3851,22 @@ vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
 			vcpu->arch.cr4_guest_owned_bits));
 }
 
+static inline unsigned long
+nested_vmx_get_event_data(struct kvm_vcpu *vcpu, bool for_ex_vmexit)

Heh, two form letters for the price of one:

#1
Do not use "inline" for functions that are visible only to the local compilation unit. "inline" is just a hint, and modern compilers are smart enough to inline functions when appropriate without a hint.

A longer explanation/rant here: https://lore.kernel.org/all/[email protected]

#2
Do not wrap before the function name. Linus has a nice explanation/rant on this[*].

[*] https://lore.kernel.org/all/CAHk-=wjoLAYG446ZNHfg=GhjSY6nFmuB_wA8fYd5iLBNXjo9Bw@mail.gmail.com

arch/x86/kvm/vmx/nested.c vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) · line 3867

Quoted 12 lines
arch/x86/kvm/vmx/nested.c +12 -0
+{
+	struct kvm_queued_exception *ex = for_ex_vmexit ?
+		&vcpu->arch.exception_vmexit : &vcpu->arch.exception;
+
+	if (ex->has_payload)
+		return ex->payload;
+	else if (ex->vector == PF_VECTOR)
+		return vcpu->arch.cr2;
+	else if (ex->vector == DB_VECTOR)
+		return (vcpu->arch.dr6 & ~DR6_BT) ^ DR6_ACTIVE_LOW;
+	else
+		return 0;

I'll circle back to this on the next version, i.e. after it's reworked to account for the suggested payload changes. I highly doubt it's correct as-is.

Quoted 13 lines
arch/x86/kvm/vmx/nested.c +2 -0
 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
 				      struct vmcs12 *vmcs12,
 				      u32 vm_exit_reason, u32 exit_intr_info)
@@ -3842,6 +3874,8 @@ static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
 	u32 idt_vectoring;
 	unsigned int nr;
 
+	vmcs12->original_event_data = 0;
+
 	/*
 	 * Per the SDM, VM-Exits due to double and triple faults are never
 	 * considered to occur during event delivery, even if the double/triple

arch/x86/kvm/vmx/nested.c static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu, · line 3918

Quoted 5 lines
arch/x86/kvm/vmx/nested.c +2 -0
@@ -3880,6 +3914,12 @@ static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
 				vcpu->arch.exception.error_code;
 		}
 
+		idt_vectoring |= vcpu->arch.exception.nested ?
+				INTR_INFO_NESTED_EXCEPTION_MASK : 0;

Please stop using ternary operators this way. It's less readable and the same number of lines as:

		if (vcpu->arch.exception.nested)
			idt_vectoring |= INTR_INFO_NESTED_EXCEPTION_MASK;
Quoted 15 lines
arch/x86/kvm/vmx/nested.c +4 -4
+
+		vmcs12->original_event_data =
+			nested_vmx_get_event_data(vcpu, false);
+
 		vmcs12->idt_vectoring_info_field = idt_vectoring;
 	} else if (vcpu->arch.nmi_injected) {
 		vmcs12->idt_vectoring_info_field =
@@ -3970,19 +4010,7 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu)
 	struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit;
 	u32 intr_info = ex->vector | INTR_INFO_VALID_MASK;
 	struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
-	unsigned long exit_qual;
-
-	if (ex->has_payload) {
-		exit_qual = ex->payload;

arch/x86/kvm/vmx/nested.c static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu) · line 4013

Quoted 10 lines
arch/x86/kvm/vmx/nested.c +1 -9
-	} else if (ex->vector == PF_VECTOR) {
-		exit_qual = vcpu->arch.cr2;
-	} else if (ex->vector == DB_VECTOR) {
-		exit_qual = vcpu->arch.dr6;
-		exit_qual &= ~DR6_BT;
-		exit_qual ^= DR6_ACTIVE_LOW;
-	} else {
-		exit_qual = 0;
-	}
+	unsigned long exit_qual = nested_vmx_get_event_data(vcpu, true);

This can't possibly be correct, EXIT_QUAL and EVENT_DATA aren't equivalent, e.g. the former doesn't have XFD_ERR, but the latter does.

arch/x86/kvm/vmx/nested.c static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu) · line 4038

Quoted 13 lines
arch/x86/kvm/vmx/nested.c +3 -2
 	/*
 	 * Unlike AMD's Paged Real Mode, which reports an error code on #PF
@@ -4003,10 +4031,12 @@ static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu)
 		intr_info |= INTR_INFO_DELIVER_CODE_MASK;
 	}
 
-	if (kvm_exception_is_soft(ex->vector))
+	if (kvm_exception_is_soft(ex->vector)) {
 		intr_info |= INTR_TYPE_SOFT_EXCEPTION;
-	else
+	} else {
 		intr_info |= INTR_TYPE_HARD_EXCEPTION;
+		intr_info |= ex->nested ? INTR_INFO_NESTED_EXCEPTION_MASK : 0;

Again,

		if (ex->nested)
			intr_info |= INTR_INFO_NESTED_EXCEPTION_MASK;

arch/x86/kvm/vmx/nested.c static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu) · line 4039

Quoted 1 line
arch/x86/kvm/vmx/nested.c +1 -0
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {

And here

Quoted 14 lines
arch/x86/kvm/vmx/nested.c +10 -0
+		vmcs12->guest_ia32_fred_config = vmcs_read64(GUEST_IA32_FRED_CONFIG);
+		vmcs12->guest_ia32_fred_rsp1 = vmcs_read64(GUEST_IA32_FRED_RSP1);
+		vmcs12->guest_ia32_fred_rsp2 = vmcs_read64(GUEST_IA32_FRED_RSP2);
+		vmcs12->guest_ia32_fred_rsp3 = vmcs_read64(GUEST_IA32_FRED_RSP3);
+		vmcs12->guest_ia32_fred_stklvls = vmcs_read64(GUEST_IA32_FRED_STKLVLS);
+		vmcs12->guest_ia32_fred_ssp1 = vmcs_read64(GUEST_IA32_FRED_SSP1);
+		vmcs12->guest_ia32_fred_ssp2 = vmcs_read64(GUEST_IA32_FRED_SSP2);
+		vmcs12->guest_ia32_fred_ssp3 = vmcs_read64(GUEST_IA32_FRED_SSP3);
+	}
+
 	vmcs12->guest_pending_dbg_exceptions =
 		vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);

arch/x86/kvm/vmx/nested.c static void load_vmcs12_host_state(struct kvm_vcpu *vcpu, · line 4678

Quoted 4 lines
arch/x86/kvm/vmx/nested.c +1 -0
@@ -4625,6 +4675,17 @@ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
 	vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
 	vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
 
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED)) {

And here

author
#82 lore raw

PATCH v2 20/25 KVM: nVMX: Add support for VMX FRED controls

In reply to Xin Li

Add VMX FRED controls to nested VMX controls and set the VMX nested-exception support bit (bit 58) in the nested IA32_VMX_BASIC MSR when FRED is enabled.

---
 arch/x86/kvm/vmx/nested.c | 14 ++++++++++----
 arch/x86/kvm/vmx/vmx.c    |  1 +
 2 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/nested.c +10 -4
index f9c1fbeac302..04a9cdb0361f 100644
@@ -1239,10 +1239,12 @@ static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
 #define VMX_BASIC_FEATURES_MASK			\
 	(VMX_BASIC_DUAL_MONITOR_TREATMENT |	\
 	 VMX_BASIC_INOUT |			\
-	 VMX_BASIC_TRUE_CTLS)
+	 VMX_BASIC_TRUE_CTLS |			\
+	 VMX_BASIC_NESTED_EXCEPTION)
 
-#define VMX_BASIC_RESERVED_BITS			\
-	(GENMASK_ULL(63, 56) | GENMASK_ULL(47, 45) | BIT_ULL(31))
+#define VMX_BASIC_RESERVED_BITS				\
+	(GENMASK_ULL(63, 59) | GENMASK_ULL(57, 56) |	\
+	 GENMASK_ULL(47, 45) | BIT_ULL(31))
 
 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
 {
@@ -6988,7 +6990,8 @@ static void nested_vmx_setup_entry_ctls(struct vmcs_config *vmcs_conf,
 #ifdef CONFIG_X86_64
 		VM_ENTRY_IA32E_MODE |
 #endif
-		VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
+		VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS |
+		VM_ENTRY_LOAD_IA32_FRED;
 	msrs->entry_ctls_high |=
 		(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER |
 		 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL);
@@ -7147,6 +7150,9 @@ static void nested_vmx_setup_basic(struct nested_vmx_msrs *msrs)
 
 	if (cpu_has_vmx_basic_inout())
 		msrs->basic |= VMX_BASIC_INOUT;
+
+	if (kvm_cpu_cap_has(X86_FEATURE_FRED))
+		msrs->basic |= VMX_BASIC_NESTED_EXCEPTION;
 }
 
 static void nested_vmx_setup_cr_fixed(struct nested_vmx_msrs *msrs)
arch/x86/kvm/vmx/vmx.c +1 -0
index fc808d599493..1005b6a57d23 100644
@@ -7915,6 +7915,7 @@ static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
 
 	entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 1);
 	cr4_fixed1_update(X86_CR4_LAM_SUP,    eax, feature_bit(LAM));
+	cr4_fixed1_update(X86_CR4_FRED,       eax, feature_bit(FRED));
 
 #undef cr4_fixed1_update
 }
Signature · 1 line
2.43.0
author
#83 lore raw

PATCH v2 21/25 KVM: nVMX: Add VMCS FRED states checking

In reply to Xin Li

Add FRED related VMCS fields checkings.

As real hardware, nested VMX performs checks on various VMCS fields, including both controls and guest/host states. With the introduction of VMX FRED, add FRED related VMCS fields checkings.

---
 arch/x86/kvm/vmx/nested.c | 80 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 79 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/nested.c +79 -1
index 04a9cdb0361f..ef0bd46eb0ce 100644
@@ -2933,6 +2933,8 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 					  struct vmcs12 *vmcs12)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	bool fred_enabled = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) &&
+			    (vmcs12->guest_cr4 & X86_CR4_FRED);
 
 	if (CC(!vmx_control_verify(vmcs12->vm_entry_controls,
 				    vmx->nested.msrs.entry_ctls_low,
@@ -2951,6 +2953,7 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 		u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
 		bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
 		bool should_have_error_code;
+		bool has_nested_exception = vmx->nested.msrs.basic & VMX_BASIC_NESTED_EXCEPTION;
 		bool urg = nested_cpu_has2(vmcs12,
 					   SECONDARY_EXEC_UNRESTRICTED_GUEST);
 		bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
@@ -2964,7 +2967,9 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 		/* VM-entry interruption-info field: vector */
 		if (CC(intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
 		    CC(intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
-		    CC(intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
+		    CC(intr_type == INTR_TYPE_OTHER_EVENT &&
+		       ((!fred_enabled && vector > 0) ||
+		        (fred_enabled && vector > 2))))
 			return -EINVAL;
 
 		/* VM-entry interruption-info field: deliver error code */
@@ -2983,6 +2988,15 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 		if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
 			return -EINVAL;
 
+		/*
+		 * When the CPU enumerates VMX nested-exception support, bit 13
+		 * (set to indicate a nested exception) of the intr info field
+		 * may have value 1. Otherwise bit 13 is reserved.
+		 */
+		if (CC(!has_nested_exception &&
+		       (intr_info & INTR_INFO_NESTED_EXCEPTION_MASK)))
+			return -EINVAL;
+
 		/* VM-entry instruction length */
 		switch (intr_type) {
 		case INTR_TYPE_SOFT_EXCEPTION:
@@ -2992,6 +3006,12 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 			    CC(vmcs12->vm_entry_instruction_len == 0 &&
 			    CC(!nested_cpu_has_zero_length_injection(vcpu))))
 				return -EINVAL;
+			break;
+		case INTR_TYPE_OTHER_EVENT:
+			if (fred_enabled && (vector == 1 || vector == 2))
+				if (CC(vmcs12->vm_entry_instruction_len > 15))
+					return -EINVAL;
+			break;
 		}
 	}
 
@@ -3054,9 +3074,30 @@ static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
 	if (ia32e) {
 		if (CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
 			return -EINVAL;
+		if (vmcs12->vm_exit_controls & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS &&
+		    vmcs12->secondary_vm_exit_controls & SECONDARY_VM_EXIT_LOAD_IA32_FRED) {
+			/* Bit 11, bits 5:4, and bit 2 of the IA32_FRED_CONFIG must be zero */
+			if (CC(vmcs12->host_ia32_fred_config &
+			       (BIT_ULL(11) | GENMASK_ULL(5, 4) | BIT_ULL(2))) ||
+			    CC(vmcs12->host_ia32_fred_rsp1 & GENMASK_ULL(5, 0)) ||
+			    CC(vmcs12->host_ia32_fred_rsp2 & GENMASK_ULL(5, 0)) ||
+			    CC(vmcs12->host_ia32_fred_rsp3 & GENMASK_ULL(5, 0)) ||
+			    CC(vmcs12->host_ia32_fred_ssp1 & GENMASK_ULL(2, 0)) ||
+			    CC(vmcs12->host_ia32_fred_ssp2 & GENMASK_ULL(2, 0)) ||
+			    CC(vmcs12->host_ia32_fred_ssp3 & GENMASK_ULL(2, 0)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_config & PAGE_MASK, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_rsp1, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_rsp2, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_rsp3, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_ssp1, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_ssp2, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->host_ia32_fred_ssp3, vcpu)))
+				return -EINVAL;
+		}
 	} else {
 		if (CC(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) ||
 		    CC(vmcs12->host_cr4 & X86_CR4_PCIDE) ||
+		    CC(vmcs12->host_cr4 & X86_CR4_FRED) ||
 		    CC((vmcs12->host_rip) >> 32))
 			return -EINVAL;
 	}
@@ -3200,6 +3241,43 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
 	     CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
 		return -EINVAL;
 
+	if (ia32e) {
+		if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_FRED) {
+			/* Bit 11, bits 5:4, and bit 2 of the IA32_FRED_CONFIG must be zero */
+			if (CC(vmcs12->guest_ia32_fred_config &
+			       (BIT_ULL(11) | GENMASK_ULL(5, 4) | BIT_ULL(2))) ||
+			    CC(vmcs12->guest_ia32_fred_rsp1 & GENMASK_ULL(5, 0)) ||
+			    CC(vmcs12->guest_ia32_fred_rsp2 & GENMASK_ULL(5, 0)) ||
+			    CC(vmcs12->guest_ia32_fred_rsp3 & GENMASK_ULL(5, 0)) ||
+			    CC(vmcs12->guest_ia32_fred_ssp1 & GENMASK_ULL(2, 0)) ||
+			    CC(vmcs12->guest_ia32_fred_ssp2 & GENMASK_ULL(2, 0)) ||
+			    CC(vmcs12->guest_ia32_fred_ssp3 & GENMASK_ULL(2, 0)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_config & PAGE_MASK, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_rsp1, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_rsp2, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_rsp3, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_ssp1, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_ssp2, vcpu)) ||
+			    CC(is_noncanonical_address(vmcs12->guest_ia32_fred_ssp3, vcpu)))
+				return -EINVAL;
+		}
+		if (vmcs12->guest_cr4 & X86_CR4_FRED) {
+			unsigned int ss_dpl = VMX_AR_DPL(vmcs12->guest_ss_ar_bytes);
+			if (CC(ss_dpl == 1 || ss_dpl == 2))
+				return -EINVAL;
+			if (ss_dpl == 0 &&
+			    CC(!(vmcs12->guest_cs_ar_bytes & VMX_AR_L_MASK)))
+				return -EINVAL;
+			if (ss_dpl == 3 &&
+			    (CC(vmcs12->guest_rflags & X86_EFLAGS_IOPL) ||
+			     CC(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_STI)))
+				return -EINVAL;
+		}
+	} else {
+		if (CC(vmcs12->guest_cr4 & X86_CR4_FRED))
+			return -EINVAL;
+	}
+
 	if (nested_check_guest_non_reg_state(vmcs12))
 		return -EINVAL;
 
Signature · 1 line
2.43.0
author
#84 lore raw

PATCH v2 22/25 KVM: x86: Allow FRED/LKGS/WRMSRNS to be exposed to guests

In reply to Xin Li

Allow FRED/LKGS/WRMSRNS to be exposed to guests, thus a guest OS could see these features when the guest is configured with FRED/LKGS/WRMSRNS in Qemu.

A qemu patch is required to expose FRED/LKGS/WRMSRNS to KVM guests.

---
 arch/x86/kvm/cpuid.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/cpuid.c +2 -2
index adba49afb5fe..afc1316d78ad 100644
@@ -676,8 +676,8 @@ void kvm_set_cpu_caps(void)
 
 	kvm_cpu_cap_mask(CPUID_7_1_EAX,
 		F(AVX_VNNI) | F(AVX512_BF16) | F(CMPCCXADD) |
-		F(FZRM) | F(FSRS) | F(FSRC) |
-		F(AMX_FP16) | F(AVX_IFMA) | F(LAM)
+		F(FZRM) | F(FSRS) | F(FSRC) | F(FRED) | F(LKGS) |
+		F(WRMSRNS) | F(AMX_FP16) | F(AVX_IFMA) | F(LAM)
 	);
 
 	kvm_cpu_cap_init_kvm_defined(CPUID_7_1_EDX,
Signature · 1 line
2.43.0
#85 lore raw

Re: [PATCH v2 22/25] KVM: x86: Allow FRED/LKGS/WRMSRNS to be exposed to guests

Quoted 2 lines · Xin Li

Allow FRED/LKGS/WRMSRNS to be exposed to guests, thus a guest OS could see these features when the guest is configured with FRED/LKGS/WRMSRNS in Qemu.

(a) please describe what these features are, and (b) one patch per feature unless they _must_ be bundled together, in which case there needs to be code to enforce that.

Quoted 1 line

A qemu patch is required to expose FRED/LKGS/WRMSRNS to KVM guests.

Omit this, QEMU is not the only VMM that uses KVM.

author
#86 lore raw

PATCH v2 23/25 KVM: selftests: Run debug_regs test with FRED enabled

In reply to Xin Li

Run another round of debug_regs test with FRED enabled if FRED is available.

---
 .../selftests/kvm/include/x86_64/processor.h  |  4 ++
 .../testing/selftests/kvm/x86_64/debug_regs.c | 50 ++++++++++++++-----
 2 files changed, 41 insertions(+), 13 deletions(-)
tools/testing/selftests/kvm/include/x86_64/processor.h +4 -0
index a84863503fcb..bc5cd8628a20 100644
@@ -48,6 +48,7 @@ extern bool host_cpu_is_amd;
 #define X86_CR4_SMEP		(1ul << 20)
 #define X86_CR4_SMAP		(1ul << 21)
 #define X86_CR4_PKE		(1ul << 22)
+#define X86_CR4_FRED		(1ul << 32)
 
 struct xstate_header {
 	u64				xstate_bv;
@@ -164,6 +165,9 @@ struct kvm_x86_cpu_feature {
 #define	X86_FEATURE_SPEC_CTRL		KVM_X86_CPU_FEATURE(0x7, 0, EDX, 26)
 #define	X86_FEATURE_ARCH_CAPABILITIES	KVM_X86_CPU_FEATURE(0x7, 0, EDX, 29)
 #define	X86_FEATURE_PKS			KVM_X86_CPU_FEATURE(0x7, 0, ECX, 31)
+#define	X86_FEATURE_FRED		KVM_X86_CPU_FEATURE(0x7, 1, EAX, 17)
+#define	X86_FEATURE_LKGS		KVM_X86_CPU_FEATURE(0x7, 1, EAX, 18)
+#define	X86_FEATURE_WRMSRNS		KVM_X86_CPU_FEATURE(0x7, 1, EAX, 19)
 #define	X86_FEATURE_XTILECFG		KVM_X86_CPU_FEATURE(0xD, 0, EAX, 17)
 #define	X86_FEATURE_XTILEDATA		KVM_X86_CPU_FEATURE(0xD, 0, EAX, 18)
 #define	X86_FEATURE_XSAVES		KVM_X86_CPU_FEATURE(0xD, 1, EAX, 3)
tools/testing/selftests/kvm/x86_64/debug_regs.c +37 -13

86 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#87 lore raw

PATCH v2 24/25 KVM: selftests: Add a new VM guest mode to run user level code

In reply to Xin Li

Add a new VM guest mode VM_MODE_PXXV48_4K_USER to set the user bit of guest page table entries, thus allow user level code to run in guests.

---
 .../testing/selftests/kvm/include/kvm_util_base.h |  1 +
 tools/testing/selftests/kvm/lib/kvm_util.c        |  5 ++++-
 .../testing/selftests/kvm/lib/x86_64/processor.c  | 15 ++++++++++-----
 tools/testing/selftests/kvm/lib/x86_64/vmx.c      |  4 ++--
 4 files changed, 17 insertions(+), 8 deletions(-)
tools/testing/selftests/kvm/include/kvm_util_base.h +1 -0
index 9e5afc472c14..ea1a585ef6f4 100644
@@ -187,6 +187,7 @@ enum vm_guest_mode {
 	VM_MODE_P36V48_16K,
 	VM_MODE_P36V48_64K,
 	VM_MODE_P36V47_16K,
+	VM_MODE_PXXV48_4K_USER,	/* For 48bits VA but ANY bits PA with USER bit set */
 	NUM_VM_MODES,
 };
 
tools/testing/selftests/kvm/lib/kvm_util.c +4 -1
index e066d584c656..8b4761836b3e 100644
@@ -163,6 +163,7 @@ const char *vm_guest_mode_string(uint32_t i)
 		[VM_MODE_P36V48_16K]	= "PA-bits:36,  VA-bits:48, 16K pages",
 		[VM_MODE_P36V48_64K]	= "PA-bits:36,  VA-bits:48, 64K pages",
 		[VM_MODE_P36V47_16K]	= "PA-bits:36,  VA-bits:47, 16K pages",
+		[VM_MODE_PXXV48_4K_USER]	= "PA-bits:ANY, VA-bits:48,  4K user pages",
 	};
 	_Static_assert(sizeof(strings)/sizeof(char *) == NUM_VM_MODES,
 		       "Missing new mode strings?");
@@ -189,6 +190,7 @@ const struct vm_guest_mode_params vm_guest_mode_params[] = {
 	[VM_MODE_P36V48_16K]	= { 36, 48,  0x4000, 14 },
 	[VM_MODE_P36V48_64K]	= { 36, 48, 0x10000, 16 },
 	[VM_MODE_P36V47_16K]	= { 36, 47,  0x4000, 14 },
+	[VM_MODE_PXXV48_4K_USER]	= {  0,  0,  0x1000, 12 },
 };
 _Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES,
 	       "Missing new mode params?");
@@ -263,6 +265,7 @@ struct kvm_vm *____vm_create(struct vm_shape shape)
 		vm->pgtable_levels = 3;
 		break;
 	case VM_MODE_PXXV48_4K:
+	case VM_MODE_PXXV48_4K_USER:
 #ifdef __x86_64__
 		kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
 		/*
@@ -278,7 +281,7 @@ struct kvm_vm *____vm_create(struct vm_shape shape)
 		vm->pgtable_levels = 4;
 		vm->va_bits = 48;
 #else
-		TEST_FAIL("VM_MODE_PXXV48_4K not supported on non-x86 platforms");
+		TEST_FAIL("VM_MODE_PXXV48_4K(_USER) not supported on non-x86 platforms");
 #endif
 		break;
 	case VM_MODE_P47V64_4K:
tools/testing/selftests/kvm/lib/x86_64/processor.c +10 -5
index d8288374078e..a8e60641df53 100644
@@ -124,8 +124,8 @@ bool kvm_is_tdp_enabled(void)
 
 void virt_arch_pgd_alloc(struct kvm_vm *vm)
 {
-	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
-		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
+	TEST_ASSERT((vm->mode == VM_MODE_PXXV48_4K) || (vm->mode == VM_MODE_PXXV48_4K_USER),
+		"Attempt to use unknown or unsupported guest mode, mode: 0x%x", vm->mode);
 
 	/* If needed, create page map l4 table. */
 	if (!vm->pgd_created) {
@@ -159,6 +159,8 @@ static uint64_t *virt_create_upper_pte(struct kvm_vm *vm,
 
 	if (!(*pte & PTE_PRESENT_MASK)) {
 		*pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK;
+		if (vm->mode == VM_MODE_PXXV48_4K_USER)
+			*pte |= PTE_USER_MASK;
 		if (current_level == target_level)
 			*pte |= PTE_LARGE_MASK | (paddr & PHYSICAL_PAGE_MASK);
 		else
@@ -185,7 +187,7 @@ void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int level)
 	uint64_t *pml4e, *pdpe, *pde;
 	uint64_t *pte;
 
-	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K,
+	TEST_ASSERT((vm->mode == VM_MODE_PXXV48_4K) || (vm->mode == VM_MODE_PXXV48_4K_USER),
 		    "Unknown or unsupported guest mode, mode: 0x%x", vm->mode);
 
 	TEST_ASSERT((vaddr % pg_size) == 0,
@@ -222,6 +224,8 @@ void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int level)
 	TEST_ASSERT(!(*pte & PTE_PRESENT_MASK),
 		    "PTE already present for 4k page at vaddr: 0x%lx\n", vaddr);
 	*pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK | (paddr & PHYSICAL_PAGE_MASK);
+	if (vm->mode == VM_MODE_PXXV48_4K_USER)
+		*pte |= PTE_USER_MASK;
 }
 
 void virt_arch_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr)
@@ -268,8 +272,8 @@ uint64_t *__vm_get_page_table_entry(struct kvm_vm *vm, uint64_t vaddr,
 	TEST_ASSERT(*level >= PG_LEVEL_NONE && *level < PG_LEVEL_NUM,
 		    "Invalid PG_LEVEL_* '%d'", *level);
 
-	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
-		"unknown or unsupported guest mode, mode: 0x%x", vm->mode);
+	TEST_ASSERT((vm->mode == VM_MODE_PXXV48_4K) || (vm->mode == VM_MODE_PXXV48_4K_USER),
+		"Attempt to use unknown or unsupported guest mode, mode: 0x%x", vm->mode);
 	TEST_ASSERT(sparsebit_is_set(vm->vpages_valid,
 		(vaddr >> vm->page_shift)),
 		"Invalid virtual address, vaddr: 0x%lx",
@@ -536,6 +540,7 @@ static void vcpu_setup(struct kvm_vm *vm, struct kvm_vcpu *vcpu)
 
 	switch (vm->mode) {
 	case VM_MODE_PXXV48_4K:
+	case VM_MODE_PXXV48_4K_USER:
 		sregs.cr0 = X86_CR0_PE | X86_CR0_NE | X86_CR0_PG;
 		sregs.cr4 |= X86_CR4_PAE | X86_CR4_OSFXSR;
 		sregs.efer |= (EFER_LME | EFER_LMA | EFER_NX);
tools/testing/selftests/kvm/lib/x86_64/vmx.c +2 -2
index 59d97531c9b1..65147de6f9c0 100644
@@ -403,8 +403,8 @@ void __nested_pg_map(struct vmx_pages *vmx, struct kvm_vm *vm,
 	struct eptPageTableEntry *pt = vmx->eptp_hva, *pte;
 	uint16_t index;
 
-	TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, "Attempt to use "
-		    "unknown or unsupported guest mode, mode: 0x%x", vm->mode);
+	TEST_ASSERT((vm->mode == VM_MODE_PXXV48_4K) || (vm->mode == VM_MODE_PXXV48_4K_USER),
+		    "Attempt to use unknown or unsupported guest mode, mode: 0x%x", vm->mode);
 
 	TEST_ASSERT((nested_paddr >> 48) == 0,
 		    "Nested physical address 0x%lx requires 5-level paging",
Signature · 1 line
2.43.0
author
#88 lore raw

PATCH v2 25/25 KVM: selftests: Add fred exception tests

In reply to Xin Li

Add tests for FRED event data and VMX nested-exception.

FRED is designed to save a complete event context in its stack frame, e.g., FRED saves the faulting linear address of a #PF into a 64-bit event data field defined in FRED stack frame. As such, FRED VMX adds event data handling during VMX transitions.

Besides, FRED introduces event stack levels to dispatch an event handler onto a stack baesd on current stack level and stack levels defined in IA32_FRED_STKLVLS MSR for each exception vector. VMX nested-exception support ensures a correct event stack level is chosen when a VM entry injects a nested exception, which is regarded as occurred in ring 0.

To fully test the underlying FRED VMX code, this test should be run one more round with EPT disabled to inject page faults as nested exceptions.

---
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/include/x86_64/processor.h  |  32 ++
 .../testing/selftests/kvm/x86_64/fred_test.c  | 297 ++++++++++++++++++
 3 files changed, 330 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86_64/fred_test.c
tools/testing/selftests/kvm/Makefile +1 -0
index 492e937fab00..eaac13a605f2 100644
@@ -67,6 +67,7 @@ TEST_GEN_PROGS_x86_64 += x86_64/get_msr_index_features
 TEST_GEN_PROGS_x86_64 += x86_64/exit_on_emulation_failure_test
 TEST_GEN_PROGS_x86_64 += x86_64/fix_hypercall_test
 TEST_GEN_PROGS_x86_64 += x86_64/hwcr_msr_test
+TEST_GEN_PROGS_x86_64 += x86_64/fred_test
 TEST_GEN_PROGS_x86_64 += x86_64/hyperv_clock
 TEST_GEN_PROGS_x86_64 += x86_64/hyperv_cpuid
 TEST_GEN_PROGS_x86_64 += x86_64/hyperv_evmcs
tools/testing/selftests/kvm/include/x86_64/processor.h +32 -0
index bc5cd8628a20..ef7aaab790e0 100644
@@ -1275,4 +1275,36 @@ void virt_map_level(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
 #define PFERR_GUEST_PAGE_MASK	BIT_ULL(PFERR_GUEST_PAGE_BIT)
 #define PFERR_IMPLICIT_ACCESS	BIT_ULL(PFERR_IMPLICIT_ACCESS_BIT)
 
+/*
+ * FRED related data structures and functions
+ */
+
+#define FRED_SSX_NMI		BIT_ULL(18)
+
+struct fred_stack {
+	u64 r15;
+	u64 r14;
+	u64 r13;
+	u64 r12;
+	u64 bp;
+	u64 bx;
+	u64 r11;
+	u64 r10;
+	u64 r9;
+	u64 r8;
+	u64 ax;
+	u64 cx;
+	u64 dx;
+	u64 si;
+	u64 di;
+	u64 error_code;
+	u64 ip;
+	u64 csx;
+	u64 flags;
+	u64 sp;
+	u64 ssx;
+	u64 event_data;
+	u64 reserved;
+};
+
 #endif /* SELFTEST_KVM_PROCESSOR_H */
tools/testing/selftests/kvm/x86_64/fred_test.c new file +297 -0

297 lines not on this page · raw message

Signature · 1 line
2.43.0
#89 lore raw

Re: [PATCH v2 25/25] KVM: selftests: Add fred exception tests

Quoted 13 lines · Xin Li

Add tests for FRED event data and VMX nested-exception.

FRED is designed to save a complete event context in its stack frame, e.g., FRED saves the faulting linear address of a #PF into a 64-bit event data field defined in FRED stack frame. As such, FRED VMX adds event data handling during VMX transitions.

Besides, FRED introduces event stack levels to dispatch an event handler onto a stack baesd on current stack level and stack levels defined in IA32_FRED_STKLVLS MSR for each exception vector. VMX nested-exception support ensures a correct event stack level is chosen when a VM entry injects a nested exception, which is regarded as occurred in ring 0.

Quoted 5 lines

To fully test the underlying FRED VMX code, this test should be run one more round with EPT disabled to inject page faults as nested exceptions.

Thank you for the new test patch. We have been trying to ensure TAP conformance for tests which cannot be achieved if new tests aren't using TAP already. Please make your test TAP compliant.

Quoted 4 lines
---
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/include/x86_64/processor.h  |  32 ++
 .../testing/selftests/kvm/x86_64/fred_test.c  | 297 ++++++++++++++++++

Add generated binary object to .gitignore.

Quoted 359 lines
 3 files changed, 330 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86_64/fred_test.c
tools/testing/selftests/kvm/Makefile +1 -0
index 492e937fab00..eaac13a605f2 100644
@@ -67,6 +67,7 @@ TEST_GEN_PROGS_x86_64 += x86_64/get_msr_index_features
 TEST_GEN_PROGS_x86_64 += x86_64/exit_on_emulation_failure_test
 TEST_GEN_PROGS_x86_64 += x86_64/fix_hypercall_test
 TEST_GEN_PROGS_x86_64 += x86_64/hwcr_msr_test
+TEST_GEN_PROGS_x86_64 += x86_64/fred_test
 TEST_GEN_PROGS_x86_64 += x86_64/hyperv_clock
 TEST_GEN_PROGS_x86_64 += x86_64/hyperv_cpuid
 TEST_GEN_PROGS_x86_64 += x86_64/hyperv_evmcs
tools/testing/selftests/kvm/include/x86_64/processor.h +32 -0
index bc5cd8628a20..ef7aaab790e0 100644
@@ -1275,4 +1275,36 @@ void virt_map_level(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
 #define PFERR_GUEST_PAGE_MASK	BIT_ULL(PFERR_GUEST_PAGE_BIT)
 #define PFERR_IMPLICIT_ACCESS	BIT_ULL(PFERR_IMPLICIT_ACCESS_BIT)
 
+/*
+ * FRED related data structures and functions
+ */
+
+#define FRED_SSX_NMI		BIT_ULL(18)
+
+struct fred_stack {
+	u64 r15;
+	u64 r14;
+	u64 r13;
+	u64 r12;
+	u64 bp;
+	u64 bx;
+	u64 r11;
+	u64 r10;
+	u64 r9;
+	u64 r8;
+	u64 ax;
+	u64 cx;
+	u64 dx;
+	u64 si;
+	u64 di;
+	u64 error_code;
+	u64 ip;
+	u64 csx;
+	u64 flags;
+	u64 sp;
+	u64 ssx;
+	u64 event_data;
+	u64 reserved;
+};
+
 #endif /* SELFTEST_KVM_PROCESSOR_H */
tools/testing/selftests/kvm/x86_64/fred_test.c new file +297 -0
new file mode 100644
index 000000000000..412afa919568
@@ -0,0 +1,297 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * FRED nested exception tests
+ *
+ * Copyright (C) 2023, Intel, Inc.
+ */
+#define _GNU_SOURCE /* for program_invocation_short_name */
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <asm/msr-index.h>
+
+#include "apic.h"
+#include "kvm_util.h"
+#include "test_util.h"
+#include "guest_modes.h"
+#include "processor.h"
+
+#define IRQ_VECTOR 0xAA
+
+#define FRED_STKLVL(v,l)		(_AT(unsigned long, l) << (2 * (v)))
+#define FRED_CONFIG_ENTRYPOINT(p)	_AT(unsigned long, (p))
+
+/* This address is already mapped in guest page table. */
+#define FRED_VALID_RSP			0x8000
+
+/*
+ * The following addresses are not yet mapped in both EPT and guest page
+ * tables at the beginning.  As a result, it causes an EPT violation VM
+ * exit with an original guest #PF to access any of them for the first
+ * time.
+ *
+ * Use these addresses as guest FRED RSP0 to generate nested #PFs to test
+ * if event data are properly virtualized.
+ */
+static unsigned long fred_invalid_rsp[4] = {
+	0x0,
+	0xf0000000,
+	0xe0000000,
+	0xd0000000,
+};
+
+extern char asm_user_nop[];
+extern char asm_user_ud[];
+extern char asm_done_fault[];
+
+extern void asm_test_fault(int test);
+
+/*
+ * user level code for triggering faults.
+ */
+asm(".pushsection .text\n"
+    ".align 4096\n"
+
+    ".type asm_user_nop, @function\n"
+    "asm_user_nop:\n"
+    "1: .byte 0x90\n"
+    "jmp 1b\n"
+
+    ".fill asm_user_ud - ., 1, 0xcc\n"
+
+    ".type asm_user_ud, @function\n"
+    ".org asm_user_nop + 16\n"
+    "asm_user_ud:\n"
+    /* Trigger a #UD */
+    "ud2\n"
+
+    ".align 4096, 0xcc\n"
+    ".popsection");
+
+/* Send current stack level and #PF address */
+#define GUEST_SYNC_CSL_FA(__stage, __pf_address)		\
+	GUEST_SYNC_ARGS(__stage, __pf_address, 0, 0, 0)
+
+void fred_entry_from_user(struct fred_stack *stack)
+{
+	u32 current_stack_level = rdmsr(MSR_IA32_FRED_CONFIG) & 0x3;
+
+	GUEST_SYNC_CSL_FA(current_stack_level, stack->event_data);
+
+	/* Do NOT go back to user level, continue the next test instead */
+	stack->ssx = 0x18;
+	stack->csx = 0x10;
+	stack->ip = (u64)&asm_done_fault;
+}
+
+void fred_entry_from_kernel(struct fred_stack *stack)
+{
+	/*
+	 * Keep NMI blocked to delay the delivery of the next NMI until
+	 * returning to user level.
+	 * */
+	stack->ssx &= ~FRED_SSX_NMI;
+}
+
+#define PUSH_REGS	\
+	"push %rdi\n"	\
+	"push %rsi\n"	\
+	"push %rdx\n"	\
+	"push %rcx\n"	\
+	"push %rax\n"	\
+	"push %r8\n"	\
+	"push %r9\n"	\
+	"push %r10\n"	\
+	"push %r11\n"	\
+	"push %rbx\n"	\
+	"push %rbp\n"	\
+	"push %r12\n"	\
+	"push %r13\n"	\
+	"push %r14\n"	\
+	"push %r15\n"
+
+#define POP_REGS	\
+	"pop %r15\n"	\
+	"pop %r14\n"	\
+	"pop %r13\n"	\
+	"pop %r12\n"	\
+	"pop %rbp\n"	\
+	"pop %rbx\n"	\
+	"pop %r11\n"	\
+	"pop %r10\n"	\
+	"pop %r9\n"	\
+	"pop %r8\n"	\
+	"pop %rax\n"	\
+	"pop %rcx\n"	\
+	"pop %rdx\n"	\
+	"pop %rsi\n"	\
+	"pop %rdi\n"
+
+/*
+ * FRED entry points.
+ */
+asm(".pushsection .text\n"
+    ".type asm_fred_entrypoint_user, @function\n"
+    ".align 4096\n"
+    "asm_fred_entrypoint_user:\n"
+    "endbr64\n"
+    PUSH_REGS
+    "movq %rsp, %rdi\n"
+    "call fred_entry_from_user\n"
+    POP_REGS
+    /* Do NOT go back to user level, continue the next test instead */
+    ".byte 0xf2,0x0f,0x01,0xca\n"	/* ERETS */
+
+    ".fill asm_fred_entrypoint_kernel - ., 1, 0xcc\n"
+
+    ".type asm_fred_entrypoint_kernel, @function\n"
+    ".org asm_fred_entrypoint_user + 256\n"
+    "asm_fred_entrypoint_kernel:\n"
+    "endbr64\n"
+    PUSH_REGS
+    "movq %rsp, %rdi\n"
+    "call fred_entry_from_kernel\n"
+    POP_REGS
+    ".byte 0xf2,0x0f,0x01,0xca\n"	/* ERETS */
+    ".align 4096, 0xcc\n"
+    ".popsection");
+
+extern char asm_fred_entrypoint_user[];
+
+/*
+ * Prepare a FRED stack frame for ERETU to return to user level code,
+ * nop or ud2.
+ *
+ * Because FRED RSP0 is deliberately not mapped in guest page table,
+ * the delivery of interrupt/NMI or #UD from ring 3 causes a nested
+ * #PF, which is then delivered on FRED RSPx (x is 1, 2 or 3,
+ * determinated by MSR FRED_STKLVL[PF_VECTOR]).
+ */
+asm(".pushsection .text\n"
+    ".type asm_test_fault, @function\n"
+    ".align 4096\n"
+    "asm_test_fault:\n"
+    "endbr64\n"
+    "push %rbp\n"
+    "mov %rsp, %rbp\n"
+    "and $(~0x3f), %rsp\n"
+    "push $0\n"
+    "push $0\n"
+    "mov $0x2b, %rax\n"
+    /* Unblock NMI */
+    "bts $18, %rax\n"
+    /* Set long mode bit */
+    "bts $57, %rax\n"
+    "push %rax\n"
+    /* No stack required for the FRED user level test code */
+    "push $0\n"
+    "pushf\n"
+    "pop %rax\n"
+    /* Allow external interrupts */
+    "bts $9, %rax\n"
+    "push %rax\n"
+    "mov $0x33, %rax\n"
+    "push %rax\n"
+    "cmp $0, %edi\n"
+    "jne 1f\n"
+    "lea asm_user_nop(%rip), %rax\n"
+    "jmp 2f\n"
+    "1: lea asm_user_ud(%rip), %rax\n"
+    "2: push %rax\n"
+    "push $0\n"
+    /* ERETU to user level code to allow event delivery immediately */
+    ".byte 0xf3,0x0f,0x01,0xca\n"
+    "asm_done_fault:\n"
+    "mov %rbp, %rsp\n"
+    "pop %rbp\n"
+    "ret\n"
+    ".align 4096, 0xcc\n"
+    ".popsection");
+
+/*
+ * To fully test the underlying FRED VMX code, this test should be run one
+ * more round with EPT disabled to inject page faults as nested exceptions.
+ */
+static void guest_code(void)
+{
+	wrmsr(MSR_IA32_FRED_CONFIG,
+	      FRED_CONFIG_ENTRYPOINT(asm_fred_entrypoint_user));
+
+	wrmsr(MSR_IA32_FRED_RSP1, FRED_VALID_RSP);
+	wrmsr(MSR_IA32_FRED_RSP2, FRED_VALID_RSP);
+	wrmsr(MSR_IA32_FRED_RSP3, FRED_VALID_RSP);
+
+	/* Enable FRED */
+	set_cr4(get_cr4() | X86_CR4_FRED);
+
+	x2apic_enable();
+
+	wrmsr(MSR_IA32_FRED_STKLVLS, FRED_STKLVL(PF_VECTOR, 1));
+	wrmsr(MSR_IA32_FRED_RSP0, fred_invalid_rsp[1]);
+	/* 1: ud2 to generate #UD */
+	asm_test_fault(1);
+
+	wrmsr(MSR_IA32_FRED_STKLVLS, FRED_STKLVL(PF_VECTOR, 2));
+	wrmsr(MSR_IA32_FRED_RSP0, fred_invalid_rsp[2]);
+	asm volatile("cli");
+	/* Create a pending interrupt on current vCPU */
+	x2apic_write_reg(APIC_ICR, APIC_DEST_SELF | APIC_INT_ASSERT |
+			 APIC_DM_FIXED | IRQ_VECTOR);
+	/* Return to ring 3 */
+	asm_test_fault(0);
+	x2apic_write_reg(APIC_EOI, 0);
+
+	wrmsr(MSR_IA32_FRED_STKLVLS, FRED_STKLVL(PF_VECTOR, 3));
+	wrmsr(MSR_IA32_FRED_RSP0, fred_invalid_rsp[3]);
+	/*
+	 * The first NMI is just to have NMI blocked in ring 0, because
+	 * fred_entry_from_kernel() deliberately clears the NMI bit in
+	 * FRED stack frame.
+	 */
+	x2apic_write_reg(APIC_ICR, APIC_DEST_SELF | APIC_INT_ASSERT |
+			 APIC_DM_NMI | NMI_VECTOR);
+	/* The second NMI will be delivered after returning to ring 3 */
+	x2apic_write_reg(APIC_ICR, APIC_DEST_SELF | APIC_INT_ASSERT |
+			 APIC_DM_NMI | NMI_VECTOR);
+	/* Return to ring 3 */
+	asm_test_fault(0);
+
+	GUEST_DONE();
+}
+
+int main(int argc, char *argv[])
+{
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	struct ucall uc;
+	uint64_t expected_current_stack_level = 1;
+
+	TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_FRED));
+
+	vm = __vm_create_with_vcpus(VM_SHAPE(VM_MODE_PXXV48_4K_USER), 1, 0,
+				    guest_code, &vcpu);
+
+	while (true) {
+		uint64_t r;
+
+		vcpu_run(vcpu);
+
+		r = get_ucall(vcpu, &uc);
+
+		if (r == UCALL_DONE)
+			break;
+
+		if (r == UCALL_SYNC) {
+			TEST_ASSERT((uc.args[1] == expected_current_stack_level) &&
+				    (uc.args[2] == fred_invalid_rsp[expected_current_stack_level] - 1),
+				    "Incorrect stack level %lx and #PF address %lx\n",
+				    uc.args[1], uc.args[2]);
+			expected_current_stack_level++;
+		}
+	}
+
+	kvm_vm_free(vm);
+	return 0;
+}
Signature · 2 lines
BR,
Muhammad Usama Anjum

A message that is not in the archive (sent off-list or not yet received): 20240329201854.f24ZDY24JtVE3gfa0i3m1MOFYfXVhCKdkXd0j5c-B6I@z

#91 lore raw

Re: [PATCH v2 25/25] KVM: selftests: Add fred exception tests

Quoted 14 lines · Muhammad Usama Anjum
Quoted 13 lines · Xin Li

Add tests for FRED event data and VMX nested-exception.

FRED is designed to save a complete event context in its stack frame, e.g., FRED saves the faulting linear address of a #PF into a 64-bit event data field defined in FRED stack frame. As such, FRED VMX adds event data handling during VMX transitions.

Besides, FRED introduces event stack levels to dispatch an event handler onto a stack baesd on current stack level and stack levels defined in IA32_FRED_STKLVLS MSR for each exception vector. VMX nested-exception support ensures a correct event stack level is chosen when a VM entry injects a nested exception, which is regarded as occurred in ring 0.

Quoted 8 lines
Quoted 5 lines

To fully test the underlying FRED VMX code, this test should be run one more round with EPT disabled to inject page faults as nested exceptions.

Thank you for the new test patch. We have been trying to ensure TAP conformance for tests which cannot be achieved if new tests aren't using TAP already.

Who is "we"?

Quoted 1 line

Please make your test TAP compliant.

This isn't entirely reasonable feedback. I'm all for getting KVM selftests TAP-friendly, but the current reality is that the KVM selftests infrastructure doesn't make it easy to be TAP compliant. We're working on improving things, i.e. I do hope/want to get to a state where it's a hard requirement for KVM selftests to be TAP compliant, but we aren't there yet.

If you have specific feedback on _how_ to make a test TAP compliant, then by all means provide that feedback. But a drive-by "make your test TAP compliant" isn't super helpful.

Quoted 5 lines
Quoted 4 lines
---
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/include/x86_64/processor.h  |  32 ++
 .../testing/selftests/kvm/x86_64/fred_test.c  | 297 ++++++++++++++++++

Add generated binary object to .gitignore.

This should be unnecessary (though I haven't actually verified by building), as KVM selftests ignore most everything by default since commit 43e96957e8b8 ("KVM: selftests: Use pattern matching in .gitignore").

#92 lore raw
In reply to Xin Li
Quoted 3 lines · Xin Li

This patch set enables the Intel flexible return and event delivery (FRED) architecture with KVM VMX to allow guests to utilize FRED.

We tested this FRED KVM patch set on a 7th Intel(R) Core(TM) CPU and the Intel Simics® Simulator with the following four configurations:

The first config is the baseline on bare metal.
The second config is the baseline on Intel Simics® Simulator. The third config enables host FRED, but disables guest FRED. The last config enables both host and guest FRED.

Following are the Kselftest results on KVM guests.

+---------------------------------------------+-------+-------+-------+-------+
|                  Config                     |  Pass |  Fail |  Skip |  Hang |
+---------------------------------------------+-------+-------+-------+-------+
|the 7th Intel(R) Core(TM) CPU                |       |       |       |       |
|  L0: 6.8.0-rc3+ w/ FRED native/KVM patch set|  1775 |  526  |  332  |   6   |
|  L1: 6.8.0-rc3+                             |       |       |       |       |
+---------------------------------------------+-------+-------+-------+-------+
|Intel Simics® Simulator w/o FRED model       |       |       |       |       |
|  L0: 6.8.0-rc3+ w/ FRED native/KVM patch set|  1770 |  526  |  331  |   12  |
|  L1: 6.8.0-rc3+ w/ FRED native/KVM patch set|       |       |       |       |
+---------------------------------------------+-------+-------+-------+-------+
|Intel Simics® Simulator w/ FRED model        |       |       |       |       |
|  L0: 6.8.0-rc3+ w/ FRED native/KVM patch set|  1770 |  526  |  331  |   12  |
|  L1: 6.8.0-rc3+ w/ FRED native/KVM patch set|       |       |       |       |
|         but FRED disabled                   |       |       |       |       |
+---------------------------------------------+-------+-------+-------+-------+
|Intel Simics® Simulator w/ FRED model        |       |       |       |       |
|  L0: 6.8.0-rc3+ w/ FRED native/KVM patch set|  1769 |  528  |  330  |   12  |
|  L1: 6.8.0-rc3+ w/ FRED native/KVM patch set|       |       |       |       |
+---------------------------------------------+-------+-------+-------+-------+

First of all we don't see any major issue. One major differences come from perf tests. Another variances are from timer tests due to Intel Simics® emulator's slowness.

The tests "x86:sysret_rip_64" and "x86:sigreturn_32" fail on the last config, because they are not valid tests for FRED:
https://lore.kernel.org/lkml/[email protected]/T/#u
https://lore.kernel.org/lkml/[email protected]/

NB: Some tests pass on Intel Simics® emulator, but not bare metal. If needed, we can share the data.

We conducted local live migration tests with LKGS/FRED/WRMSRNS enabled/disabled on Intel Simics® Simulator, and see no problems.

We also tested KVM Kselftest on a nested FRED KVM guest, 48 out of 83 cases passed and the rest cases failed due to the slowness of Intel Simics® emulator.

Detailed report upon request.

#93 lore raw
Quoted 6 lines · Shan Kang
Quoted 3 lines · Xin Li

This patch set enables the Intel flexible return and event delivery (FRED) architecture with KVM VMX to allow guests to utilize FRED.

We tested this FRED KVM patch set on a 7th Intel(R) Core(TM) CPU and the Intel Simics® Simulator with the following four configurations:

That likely provides coverage for the happy cases, but I doubt it provides negative testing, e.g. for VM-Enter consistency checks. KVM-Unit-Tests are currently the best choice for concistency checks (unfortunately).

And given the insanity of event re-injection, KVM selftests needs a dedicated test for that, and another for the interactions with nVMX, e.g. a la svm_nested_soft_inject_test.c.

I haven't looked too closely at the selftest that's already provided, but my suspicion is that we'll want multiple tests, or alternatively one test that uses KVM_ONE_VCPU_TEST_SUITE().

author
#94 lore raw
Quoted 12 lines · Shan Kang
Quoted 6 lines · Xin Li
Quoted 3 lines

This patch set enables the Intel flexible return and event delivery (FRED) architecture with KVM VMX to allow guests to utilize FRED.

We tested this FRED KVM patch set on a 7th Intel(R) Core(TM) CPU and the Intel Simics® Simulator with the following four configurations:

That likely provides coverage for the happy cases, but I doubt it provides negative testing, e.g. for VM-Enter consistency checks. KVM-Unit-Tests are currently the best choice for concistency checks (unfortunately).

Quoted 7 lines

And given the insanity of event re-injection, KVM selftests needs a dedicated test for that, and another for the interactions with nVMX, e.g. a la svm_nested_soft_inject_test.c.

I haven't looked too closely at the selftest that's already provided, but my suspicion is that we'll want multiple tests, or alternatively one test that uses KVM_ONE_VCPU_TEST_SUITE().

What about posting the FRED selftests in another new patch set?

Thanks!
Xin

author
#95 lore raw
In reply to Xin Li
Quoted 3 lines

This patch set enables the Intel flexible return and event delivery (FRED) architecture with KVM VMX to allow guests to utilize FRED.

<snip>

Quoted 11 lines

Intel VMX architecture is extended to run FRED guests, and the major changes are:

1) New VMCS fields for FRED context management, which includes two new event data VMCS fields, eight new guest FRED context VMCS fields and eight new host FRED context VMCS fields.

2) VMX nested-exception support for proper virtualization of stack levels introduced with FRED architecture.

<snip>

Quoted 4 lines

Patch 1-2 are cleanups to VMX basic and misc MSRs, which were sent out earlier as a preparation for FRED changes:
https://lore.kernel.org/kvm/[email protected]/T/#u

Obviously I will drop the 2 clean patches in the next iteration.

Quoted 4 lines

Patch 3-15 add FRED support to VMX.
Patch 16-21 add FRED support to nested VMX.
Patch 22 exposes FRED and its baseline features to KVM guests. Patch 23-25 add FRED selftests.

Please help to review and comment on the FRED KVM/VMX patches.

Thanks!
Xin