Skip to contentSkip to conversation

KVM: Enable FRED support with KVM VMX

PATCH In review Sohil Mehta 12 participants 108 messages Sep 11 – Nov 21

Subsystems (7)
Documentation x86 KVM Kselftest +3 more subsystems
lore
Share & tools
lore
#0 lore raw

v10 cover KVM: Enable FRED support with KVM VMX

This series enables Intel flexible return and event delivery (FRED) with KVM VMX to allow guests to utilize FRED.

Change of personnel
-------------------
The patches are being posted after a while. Xin asked me to post the patches on his behalf but almost all the work in v10 has been done by him. Many thanks!

I mainly rebased the patches to the latest kvm-x86/next branch and fixed a handful of issues reported during internal testing and basic AI reviews. I've avoided making any major code changes or commit message updates as this is the first iteration that I am posting.

Going forward, based on the feedback, I'll rework the patches as needed. I've listed a few opens below that need additional discussion or clarification. I'm relatively new to the KVM subsystem, so please feel free to provide suggestions on the series structure, code organization as well as commit log clarity to smoothen the review process.

FRED Background
---------------
The FRED architecture defines simple new transitions that change privilege level (ring transitions), designed with two 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.

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.

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

1) New VMCS fields for FRED context management: 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 the stack levels introduced with the FRED architecture.

For details refer the latest Intel FRED specification which was released in June 2025 as version 9.0.

Patch structure
---------------
Patches 1-6: Enable the VMX controls and export the host stacks
Patches 7-19: Virtualize the FRED context and advertise it to userspace Patches 20-25: Extend FRED virtualization to nested VMX Patches 26-28: Some basic selftests

These patches are also available at:
https://github.com/sohilmeh/linux-dev/tree/fred-kvm-v10

Main changes in v10
-------------------
- New patches:
Emulator CR4 write mask (patch 15)
CR4.FRED handling on RSM (patch 17)
Three selftests (patches 26-28)
- Folded the FRED MSRs into a struct with read/write helpers, and filter all nine of them in the nested MSR bitmap instead of just RSP0
- Improved event data handling including save/restore of the event data via KVM_{GET,SET}_VCPU_EVENTS
- Restructured the nested interruption-information checks as a switch on interruption type, and reject bit 13 for non-hardware exceptions
- Cleared FRED in svm_set_cpu_caps()
- Reject vmcs12 secondary VM-exit controls KVM doesn't advertise to L1
- Added MSR_IA32_VMX_EXIT_CTLS2 to the emulated MSR list
- Updated the author field from Xin's Intel email address to the new one.
- Removed the old Tested-by tags as the base KVM code and FRED patches have changed significantly.

The per-patch changes are listed under each patch.

Testing
-------
Internal testing covered the following on real hardware:
- Basic guest boot and nested boot to verify FRED was exposed correctly
- KVM and x86 selftests on L0 and L1 guest
- KVM unit tests including the FRED ones listed below
- Guest live migration with FRED

The included selftests in this series are the ones I received from Xin. There are additional selftests that I am putting together from multiple sources. However, those are not ready for upstream review yet. The in-progress selftests are located at:
https://github.com/sohilmeh/linux-dev/commits/fred-kvm-next

Xin posted a set of FRED KVM unit tests for review at:
https://lore.kernel.org/all/[email protected]/

There are a couple of known issues worth mentioning:
- The x86 selftest sysret_rip asserts failure on FRED hosts as well as guest. The issue has been reported upstream [1] but AFAIU hasn't been resolved yet.

- The int1_fred_test KVM selftest from David mentioned below asserts failure with the wrong event type with FRED.

Intel Panther Lake systems with FRED support are now available off the shelf. Clearwater Forest and Diamond Rapids are some of the other Intel platforms that are expected to have FRED support.

Opens
-----
INT1 event type: David Woodhouse shared a selftest which shows [2] KVM re-injects an intercepted ICEBP (INT1) #DB as a hardware exception, so a FRED guest reads event type 3 instead of 5. IIUC, the issue is not FRED specific but it becomes visible due to FRED. Is that understanding correct? Also, I am unsure of where the fix should reside or if a generic fix is already in the works. Any insights here would be helpful.

uAPI: There was some resistance about adding exception event data to the uAPI [3], suggesting KVM reuse the exception payload and skip updating register state on re-injection. Xin said that he tried deriving event data from (vector, payload), but the solution was a bit messy. As exception_is_nested is needed either way, adding event data to the uAPI seemed cleaner. Please let me know if the other approach is still preferable.

Nested virtualization: Both CET and FRED can potentially leave L1 running with L2's state after a failed nested VM-entry. Zhao initiated a thread for CET [4] which is under active discussion. This series implements a solution that might need to be revised based on whatever gets settled there.

Hardware fidelity: I am unsure of the level of fidelity KVM tries to maintain with respect to the hardware. There are places (such as patch 24, nested_vmx_check_guest_state()) where KVM lets the hardware check some state instead of performing the checks itself, and cases where it may fail differently for unusual vmcs12 configurations. I would appreciate some extra eyes on that.

AMD compatibility: The SVM enabling [5] builds on the same common plumbing but I haven't had a chance to look at the series yet. Shivansh, please let me know if there are any incompatibilities. I assume most of the opens apply to SVM as well so resolutions would help both vendors.

Series split-up: With additional selftests, the number of patches in this series would exceed 30. Would it be preferable to split the selftests in to a separate series for easier review? I am inclined to keep the nested support together to let sashiko review the patches. But, please let me know if it would be preferable to split that out as well.

Links
-----
[1]: https://lore.kernel.org/lkml/[email protected]/
[2]: https://lore.kernel.org/lkml/[email protected]/
[3]: https://lore.kernel.org/all/[email protected]/
[4]: https://lore.kernel.org/all/[email protected]/
[5]: https://lore.kernel.org/all/[email protected]/

Previous versions
-----------------
v9: https://lore.kernel.org/lkml/[email protected]/
v8: https://lore.kernel.org/lkml/[email protected]/
v7: https://lore.kernel.org/lkml/[email protected]/
v6: https://lore.kernel.org/lkml/[email protected]/
v5: https://lore.kernel.org/lkml/[email protected]/
v4: https://lore.kernel.org/lkml/[email protected]/
v3: https://lore.kernel.org/lkml/[email protected]/
v2: https://lore.kernel.org/lkml/[email protected]/
v1: https://lore.kernel.org/lkml/[email protected]/

Sohil Mehta (1):
KVM: x86: Handle CR4.FRED when emulating RSM

Xin Li (4):
KVM: x86: Add a new save/restore flag for FRED metadata
KVM: x86: Include CR4.FRED in the emulator CR4 write mask
KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts
KVM: selftests: Add FRED MSRs to msrs_test

Xin Li (Intel) (23):
KVM: VMX: Enable support for secondary VM exit controls
KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config
KVM: VMX: Disable FRED if FRED consistency checks fail x86/cea: Prefix event stack names with ESTACK_
x86/cea: Use array indexing to simplify exception stack access x86/fred: Export this_cpu_fred_rsp() for KVM usage
KVM: VMX: Initialize VMCS FRED fields
KVM: VMX: Set FRED MSR intercepts
KVM: VMX: Save/restore guest FRED RSP0
KVM: VMX: Add support for saving and restoring FRED MSRs
KVM: x86: Add a helper to detect if FRED is enabled for a vCPU
KVM: VMX: Virtualize FRED nested exception tracking
KVM: VMX: Virtualize FRED event_data
KVM: x86: Mark CR4.FRED as not reserved
KVM: VMX: Dump FRED context in dump_vmcs()
KVM: x86: Advertise support for FRED
KVM: nVMX: Enable support for secondary VM exit controls
KVM: nVMX: Handle FRED VMCS fields in nested VMX context
KVM: nVMX: Shadow ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA fields
KVM: nVMX: Validate FRED-related VMCS fields
KVM: nVMX: Enable VMX FRED controls
KVM: selftests: Add a new VM guest mode to run user level code
KVM: selftests: Add fred exception tests

 Documentation/virt/kvm/api.rst                |  22 ++
 arch/x86/coco/sev/noinstr.c                   |   4 +-
 arch/x86/coco/sev/vc-handle.c                 |   2 +-
 arch/x86/include/asm/cpu_entry_area.h         |  70 ++--
 arch/x86/include/asm/fred.h                   |  10 +
 arch/x86/include/asm/kvm_host.h               |  11 +
 arch/x86/include/asm/msr-index.h              |   3 +
 arch/x86/include/asm/vmx.h                    |  48 ++-
 arch/x86/include/uapi/asm/kvm.h               |   7 +-
 arch/x86/kernel/cpu/common.c                  |  10 +-
 arch/x86/kernel/dumpstack_64.c                |  18 +-
 arch/x86/kernel/fred.c                        |  24 +-
 arch/x86/kernel/traps.c                       |   2 +-
 arch/x86/kvm/cpuid.c                          |   1 +
 arch/x86/kvm/msrs.c                           |  90 +++++-
 arch/x86/kvm/msrs.h                           |   2 +-
 arch/x86/kvm/regs.c                           |   7 +
 arch/x86/kvm/regs.h                           |  21 +-
 arch/x86/kvm/smm.c                            |  18 +-
 arch/x86/kvm/svm/svm.c                        |   5 +-
 arch/x86/kvm/vmx/capabilities.h               |  20 +-
 arch/x86/kvm/vmx/nested.c                     | 253 +++++++++++++--
 arch/x86/kvm/vmx/nested.h                     |  27 ++
 arch/x86/kvm/vmx/vmcs.h                       |  12 +
 arch/x86/kvm/vmx/vmcs12.c                     |  22 ++
 arch/x86/kvm/vmx/vmcs12.h                     |  42 ++-
 arch/x86/kvm/vmx/vmcs_shadow_fields.h         |   4 +
 arch/x86/kvm/vmx/vmx.c                        | 302 +++++++++++++++++-
 arch/x86/kvm/vmx/vmx.h                        |  36 ++-
 arch/x86/kvm/x86.c                            |  69 +++-
 arch/x86/kvm/x86.h                            |   5 +-
 arch/x86/mm/cpu_entry_area.c                  |  34 +-
 arch/x86/mm/fault.c                           |   2 +-
 include/uapi/linux/kvm.h                      |   1 +
 tools/arch/x86/include/asm/msr-index.h        |   2 +
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../testing/selftests/kvm/include/kvm_util.h  |   1 +
 .../selftests/kvm/include/x86/processor.h     |  34 ++
 tools/testing/selftests/kvm/lib/kvm_util.c    |   5 +-
 .../testing/selftests/kvm/lib/x86/processor.c |  16 +-
 tools/testing/selftests/kvm/x86/fred_test.c   | 291 +++++++++++++++++
 tools/testing/selftests/kvm/x86/msrs_test.c   |  52 ++-
 42 files changed, 1471 insertions(+), 135 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/fred_test.c

base-commit: 76671054f9a1ff6abb976583cd8da37650acdc97

Signature · 1 line
2.43.0
#1 lore raw

PATCH v10 1/28 KVM: VMX: Enable support for secondary VM exit controls

From: "Xin Li (Intel)" <[email protected]>

Introduce infrastructure to support secondary VM exit controls.

Always load the controls when supported by hardware, though all control bits remain clear in this patch.

---
v10:
- No change

---
 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           | 29 +++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/vmx.h           |  7 ++++++-
 6 files changed, 46 insertions(+), 4 deletions(-)
arch/x86/include/asm/msr-index.h +1 -0
index 18c4be75e927..ad899d9070e1 100644
@@ -1274,6 +1274,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
 
 #define MSR_IA32_MCU_STAGING_MBOX_ADDR	0x000007a5
 
arch/x86/include/asm/vmx.h +3 -0
index 3f1b3096ff04..1f7cffc118bf 100644
@@ -119,6 +119,7 @@ struct vmcs {
 #define VM_EXIT_CLEAR_IA32_RTIT_CTL		0x02000000
 #define VM_EXIT_LOAD_CET_STATE                  0x10000000
 #define VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL	0x40000000
+#define VM_EXIT_ACTIVATE_SECONDARY_CONTROLS	0x80000000
 
 #define VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR	0x00036dff
 
@@ -275,6 +276,8 @@ enum vmcs_field {
 	SHARED_EPT_POINTER		= 0x0000203C,
 	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 810119167f79..6be818ce27bf 100644
@@ -57,8 +57,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 vmexit_2nd_ctrl;
 	u64 misc;
 	struct nested_vmx_msrs nested;
 };
@@ -149,6 +150,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 1f16ddeae9cb..ca341c59bab1 100644
@@ -45,6 +45,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 +27 -2
index 504630f0eb40..b4aec4218b7d 100644
@@ -2751,8 +2751,9 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	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;
+	u32 _vmexit_control = 0;
+	u64 _vmexit2_control = 0;
 	u64 basic_msr;
 	u64 misc_msr;
 
@@ -2773,6 +2774,12 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		{ VM_ENTRY_LOAD_CET_STATE,		VM_EXIT_LOAD_CET_STATE },
 	};
 
+	struct {
+		u32 entry_control;
+		u64 exit_control;
+	} const vmcs_entry_exit2_pairs[] = {
+	};
+
 	memset(vmcs_conf, 0, sizeof(*vmcs_conf));
 
 	if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL,
@@ -2870,10 +2877,19 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 				&_vmentry_control))
 		return -EIO;
 
+	if (_vmexit_control & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS)
+		_vmexit2_control =
+			adjust_vmx_controls64(KVM_OPTIONAL_VMX_SECONDARY_VM_EXIT_CONTROLS,
+					      MSR_IA32_VMX_EXIT_CTLS2);
+
 	if (vmx_check_entry_exit_pairs(vmcs_entry_exit_pairs,
 				       _vmentry_control, _vmexit_control))
 		return -EIO;
 
+	if (vmx_check_entry_exit_pairs(vmcs_entry_exit2_pairs,
+				       _vmentry_control, _vmexit2_control))
+		return -EIO;
+
 	/*
 	 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
 	 * can't be used due to an errata where VM Exit may incorrectly clear
@@ -2922,8 +2938,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->vmexit_2nd_ctrl     = _vmexit2_control;
 	vmcs_conf->misc	= misc_msr;
 
 #if IS_ENABLED(CONFIG_HYPERV)
@@ -4617,6 +4634,11 @@ static u32 vmx_get_initial_vmexit_ctrl(void)
 		  VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL);
 }
 
+static u64 vmx_secondary_vmexit_ctrl(void)
+{
+	return vmcs_config.vmexit_2nd_ctrl;
+}
+
 void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
@@ -4960,6 +4982,9 @@ static void init_vmcs(struct vcpu_vmx *vmx)
 
 	vm_exit_controls_set(vmx, vmx_get_initial_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_get_initial_vmentry_ctrl());
 
arch/x86/kvm/vmx/vmx.h +6 -1
index dc8517f15bc4..6295f9302cd9 100644
@@ -501,7 +501,11 @@ static inline u8 vmx_get_rvi(void)
 	       VM_EXIT_PT_CONCEAL_PIP |					\
 	       VM_EXIT_CLEAR_IA32_RTIT_CTL |				\
 	       VM_EXIT_LOAD_CET_STATE |					\
-	       VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL)
+	       VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL |			\
+	       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 |					\
@@ -615,6 +619,7 @@ static __always_inline void lname##_controls_changebit(struct vcpu_vmx *vmx, u##
 }
 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
Reviewed-by on v10 1/28
#2 lore raw

Re: [PATCH v10 01/28] KVM: VMX: Enable support for secondary VM exit controls

Quoted 9 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Introduce infrastructure to support secondary VM exit controls.

Always load the controls when supported by hardware, though all control bits remain clear in this patch.

[...]

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2756

Quoted 12 lines
arch/x86/kvm/vmx/vmx.c +2 -1
index 504630f0eb40..b4aec4218b7d 100644
@@ -2751,8 +2751,9 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	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;
+	u32 _vmexit_control = 0;
+	u64 _vmexit2_control = 0;

Nit:
Could be _vmexit_2nd_control to be consistent with _cpu_based_2nd_exec_control above, as well as vmexit_2nd_control in struct vmcs_config.

Quoted 3 lines
arch/x86/kvm/vmx/vmx.c +0 -0
 	u64 basic_msr;
 	u64 misc_msr;
 
#3 lore raw

Re: [PATCH v10 01/28] KVM: VMX: Enable support for secondary VM exit controls

Quoted 6 lines · Binbin Wu
Quoted 3 lines

Thank you for reviewing the patches.

Quoted 11 lines

[...]

Quoted 9 lines
arch/x86/kvm/vmx/vmx.c +0 -1
index 504630f0eb40..b4aec4218b7d 100644
@@ -2751,8 +2751,9 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 	u32 _cpu_based_exec_control = 0;
 	u32 _cpu_based_2nd_exec_control = 0;
 	u64 _cpu_based_3rd_exec_control = 0;
-	u32 _vmexit_control = 0;
Quoted 9 lines

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2756

Quoted 3 lines
arch/x86/kvm/vmx/vmx.c +2 -0
 	u32 _vmentry_control = 0;
+	u32 _vmexit_control = 0;
+	u64 _vmexit2_control = 0;

Nit:
Could be _vmexit_2nd_control to be consistent with _cpu_based_2nd_exec_control above, as well as vmexit_2nd_control in struct vmcs_config.

Sure, will update it.

#4 lore raw

PATCH v10 2/28 KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Setup VM entry/exit FRED controls in the global vmcs_config for proper FRED VMCS fields management:
1) load guest FRED state upon VM entry.
2) save guest FRED state during VM exit.
3) load host FRED state during VM exit.

Also add FRED control consistency checks to the existing VM entry/exit consistency check framework.

---
v10:
- No change

---
 arch/x86/include/asm/vmx.h | 4 ++++
 arch/x86/kvm/vmx/vmx.c     | 2 ++
 arch/x86/kvm/vmx/vmx.h     | 7 +++++--
 3 files changed, 11 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +4 -0
index 1f7cffc118bf..682f09933612 100644
@@ -121,6 +121,9 @@ struct vmcs {
 #define VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL	0x40000000
 #define VM_EXIT_ACTIVATE_SECONDARY_CONTROLS	0x80000000
 
+#define SECONDARY_VM_EXIT_SAVE_IA32_FRED	BIT_ULL(0)
+#define SECONDARY_VM_EXIT_LOAD_IA32_FRED	BIT_ULL(1)
+
 #define VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR	0x00036dff
 
 #define VM_ENTRY_LOAD_DEBUG_CONTROLS            0x00000004
@@ -134,6 +137,7 @@ struct vmcs {
 #define VM_ENTRY_PT_CONCEAL_PIP			0x00020000
 #define VM_ENTRY_LOAD_IA32_RTIT_CTL		0x00040000
 #define VM_ENTRY_LOAD_CET_STATE                 0x00100000
+#define VM_ENTRY_LOAD_IA32_FRED			0x00800000
 
 #define VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR	0x000011ff
 
arch/x86/kvm/vmx/vmx.c +2 -0
index b4aec4218b7d..062631e2dd37 100644
@@ -2778,6 +2778,8 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		u32 entry_control;
 		u64 exit_control;
 	} const vmcs_entry_exit2_pairs[] = {
+		{ VM_ENTRY_LOAD_IA32_FRED,
+			SECONDARY_VM_EXIT_SAVE_IA32_FRED | SECONDARY_VM_EXIT_LOAD_IA32_FRED },
 	};
 
 	memset(vmcs_conf, 0, sizeof(*vmcs_conf));
arch/x86/kvm/vmx/vmx.h +5 -2
index 6295f9302cd9..7a22e1b1a273 100644
@@ -477,7 +477,8 @@ static inline u8 vmx_get_rvi(void)
 	 VM_ENTRY_LOAD_BNDCFGS |					\
 	 VM_ENTRY_PT_CONCEAL_PIP |					\
 	 VM_ENTRY_LOAD_IA32_RTIT_CTL |					\
-	 VM_ENTRY_LOAD_CET_STATE)
+	 VM_ENTRY_LOAD_CET_STATE |					\
+	 VM_ENTRY_LOAD_IA32_FRED)
 
 #define __KVM_REQUIRED_VMX_VM_EXIT_CONTROLS				\
 	(VM_EXIT_SAVE_DEBUG_CONTROLS |					\
@@ -505,7 +506,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
#5 lore raw

Re: [PATCH v10 02/28] KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] `vmx_check_entry_exit_pairs` incorrectly validates multi-bit exit controls, silently accepting…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] vmx_check_entry_exit_pairs incorrectly validates multi-bit exit controls, silently accepting partial feature enablement and exposing the host to privilege escalation. --

commit 2bf701245fc6586c07b00b47292677b65ee2dec9
Author: Xin Li (Intel) <[email protected]>

KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

This commit sets up VM entry and exit FRED controls in the global vmcs_config to ensure guest FRED state is saved and loaded correctly. It also adds a check to the existing consistency framework.

[ ... ]

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2782

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +2 -0
index b4aec4218b7da..062631e2dd376 100644
@@ -2778,6 +2778,8 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		u32 entry_control;
 		u64 exit_control;
 	} const vmcs_entry_exit2_pairs[] = {
+		{ VM_ENTRY_LOAD_IA32_FRED,
+			SECONDARY_VM_EXIT_SAVE_IA32_FRED | SECONDARY_VM_EXIT_LOAD_IA32_FRED },

[Severity: Critical]
Can this multi-bit mask bypass the validation logic in vmx_check_entry_exit_pairs?

Looking at how vmx_check_entry_exit_pairs validates these fields:

#define vmx_check_entry_exit_pairs(pairs, entry_controls, exit_controls) \
...

	if (!(entry_controls & n_ctrl) == !(exit_controls & x_ctrl))     \
		continue;

If the hardware or an L0 hypervisor provides only one of the two FRED exit bits, a bitwise AND against the multi-bit x_ctrl mask will still be non-zero.

This makes !(exit_controls & x_ctrl) evaluate to 0, which matches the entry side, bypassing the inconsistency check entirely.

Could this allow KVM to be partially configured without returning -EIO?

If only one of the exit controls is enabled, could the host resume execution after a VM-exit with guest-controlled FRED MSRs?

Would this result in a privilege escalation by allowing the next host interrupt to execute arbitrary guest-controlled code in host context?

Quoted 3 lines
arch/x86/kvm/vmx/vmx.c +0 -0
 	};
 
 	memset(vmcs_conf, 0, sizeof(*vmcs_conf));
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#6 lore raw

Re: [PATCH v10 02/28] KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

In reply to Sohil Mehta

On 9/12/2026 5:36 AM, Sohil Mehta wrote:
[...]

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2782

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +2 -0
index b4aec4218b7d..062631e2dd37 100644
@@ -2778,6 +2778,8 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		u32 entry_control;
 		u64 exit_control;
 	} const vmcs_entry_exit2_pairs[] = {
+		{ VM_ENTRY_LOAD_IA32_FRED,
+			SECONDARY_VM_EXIT_SAVE_IA32_FRED | SECONDARY_VM_EXIT_LOAD_IA32_FRED },

I think it can be break into two lines for much better readability:

	} const vmcs_entry_exit2_pairs[] = {
		{ VM_ENTRY_LOAD_IA32_FRED,	SECONDARY_VM_EXIT_SAVE_IA32_FRED },
		{ VM_ENTRY_LOAD_IA32_FRED,	SECONDARY_VM_EXIT_LOAD_IA32_FRED },
	};

Oh, it also fixes the issue reported by the sashiko.

#7 lore raw

Re: [PATCH v10 02/28] KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

Quoted 15 lines · Binbin Wu

On 9/12/2026 5:36 AM, Sohil Mehta wrote:
[...]

arch/x86/kvm/vmx/vmx.c static int setup_vmcs_config(struct vmcs_config *vmcs_conf, · line 2782

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +2 -0
index b4aec4218b7d..062631e2dd37 100644
@@ -2778,6 +2778,8 @@ static int setup_vmcs_config(struct vmcs_config *vmcs_conf,
 		u32 entry_control;
 		u64 exit_control;
 	} const vmcs_entry_exit2_pairs[] = {
+		{ VM_ENTRY_LOAD_IA32_FRED,
+			SECONDARY_VM_EXIT_SAVE_IA32_FRED | SECONDARY_VM_EXIT_LOAD_IA32_FRED },

I think it can be break into two lines for much better readability:

Quoted 6 lines
	} const vmcs_entry_exit2_pairs[] = {
		{ VM_ENTRY_LOAD_IA32_FRED,	SECONDARY_VM_EXIT_SAVE_IA32_FRED },
		{ VM_ENTRY_LOAD_IA32_FRED,	SECONDARY_VM_EXIT_LOAD_IA32_FRED },
	};

Oh, it also fixes the issue reported by the sashiko.

Agreed, splitting it improves readability. However, I am not sure if it reliably fixes the issue. Splitting the entry makes the partial case detectable, but with error_on_inconsistent_vmcs_config=0 could it still leave vmcs_config inconsistent?

For example, if the first row passes but the second row fails, it clears VM_ENTRY_LOAD_IA32_FRED but leaves SECONDARY_VM_EXIT_SAVE_IA32_FRED set. Only leaving EXIT_SAVE set is probably harmless but if the order were reversed:

{ VM_ENTRY_LOAD_IA32_FRED, SECONDARY_VM_EXIT_LOAD_IA32_FRED },
{ VM_ENTRY_LOAD_IA32_FRED, SECONDARY_VM_EXIT_SAVE_IA32_FRED },

then, leaving EXIT_LOAD uncleared would cause issues, right?

It probably doesn't matter much because error_on_inconsistent_vmcs_config is set by default. But, I feel relying on the ordering makes it a little fragile.

The other option is to leave this patch as-is and add a check to the existing one in vmx_check_entry_exit_pairs() which covers both exit controls for FRED.

if (!(entry_controls & n_ctrl) == !(exit_controls & x_ctrl) &&

    !(entry_controls & n_ctrl) == ((exit_controls & x_ctrl) != x_ctrl))
		continue;

I couldn't find any precedent for this. I don't have a strong preference here. Is it worth making future-proof?

#8 lore raw

Re: [PATCH v10 02/28] KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

Quoted 2 lines · Sohil Mehta

I couldn't find any precedent for this. I don't have a strong preference here. Is it worth making future-proof?

I did a bit of digging. The current entry in the table is the result of Sean's preference provided early on in the FRED series. See

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

IIUC, we want the FRED entry/exit controls to be consistent without depending on the ordering.

The current vmx_check_entry_exit_pairs() doesn't cover the FRED case (a single entry bit mapping to two exit bits). So, the updated check would cover this scenario.

Quoted 4 lines

if (!(entry_controls & n_ctrl) == !(exit_controls & x_ctrl) &&

    !(entry_controls & n_ctrl) == ((exit_controls & x_ctrl) != x_ctrl))
		continue;

1st line: the entry control is set if and only if *any* exit bit is set. 2nd line: the entry control is set if and only if *all* exit bits are set (which is specific to FRED for now).

Also, to make it easier to read, planning to reformat it as:

struct {
	u32 entry_control;
	u64 exit_control;
} const vmcs_entry_exit2_pairs[] = {
	{ VM_ENTRY_LOAD_IA32_FRED, SECONDARY_VM_EXIT_SAVE_IA32_FRED |
				   SECONDARY_VM_EXIT_LOAD_IA32_FRED },
};

Please let me know if you disagree with the approach.

#9 lore raw

Re: [PATCH v10 02/28] KVM: VMX: Initialize VM entry/exit FRED controls in vmcs_config

Quoted 12 lines · Sohil Mehta
Quoted 2 lines · Sohil Mehta

I couldn't find any precedent for this. I don't have a strong preference here. Is it worth making future-proof?

I did a bit of digging. The current entry in the table is the result of Sean's preference provided early on in the FRED series. See

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

Quoted 6 lines

IIUC, we want the FRED entry/exit controls to be consistent without depending on the ordering.

The current vmx_check_entry_exit_pairs() doesn't cover the FRED case (a single entry bit mapping to two exit bits). So, the updated check would cover this scenario.

OK, thanks for the info!

Quoted 21 lines
Quoted 5 lines

if (!(entry_controls & n_ctrl) == !(exit_controls & x_ctrl) &&

    !(entry_controls & n_ctrl) == ((exit_controls & x_ctrl) != x_ctrl))
		continue;

1st line: the entry control is set if and only if *any* exit bit is set. 2nd line: the entry control is set if and only if *all* exit bits are set (which is specific to FRED for now).

Also, to make it easier to read, planning to reformat it as:

struct {
	u32 entry_control;
	u64 exit_control;
} const vmcs_entry_exit2_pairs[] = {
	{ VM_ENTRY_LOAD_IA32_FRED, SECONDARY_VM_EXIT_SAVE_IA32_FRED |
				   SECONDARY_VM_EXIT_LOAD_IA32_FRED },
};
Quoted 1 line

Please let me know if you disagree with the approach.

It looks good to me.

#10 lore raw

PATCH v10 3/28 KVM: VMX: Disable FRED if FRED consistency checks fail

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Do not virtualize FRED if FRED consistency checks fail.

Either on broken hardware, or when run KVM on top of another hypervisor before the underlying hypervisor implements nested FRED correctly.

---
v10:
- Remove the comment about why not check FRED VM-exit controls in cpu_has_vmx_fred() (Sean).
- Remove redundant parentheses (Sean).

---
 arch/x86/kvm/vmx/capabilities.h | 5 +++++
 arch/x86/kvm/vmx/vmx.c          | 3 +++
 2 files changed, 8 insertions(+)
arch/x86/kvm/vmx/capabilities.h +5 -0
index 6be818ce27bf..95d22a54f856 100644
@@ -409,6 +409,11 @@ static inline bool vmx_pebs_supported(void)
 	       !enable_mediated_pmu;
 }
 
+static inline bool cpu_has_vmx_fred(void)
+{
+	return 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 +3 -0
index 062631e2dd37..2a2218e0983b 100644
@@ -8122,6 +8122,9 @@ static __init void vmx_set_cpu_caps(void)
 		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);
 	kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
Signature · 1 line
2.43.0
#11 lore raw

Re: [PATCH v10 03/28] KVM: VMX: Disable FRED if FRED consistency checks fail

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

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

Pre-existing issues:
- [High] Flawed boolean logic in vmx_check_entry_exit_pairs allows KVM to expose FRED on nested hypervisors or broken hardware with incomplete exit controls, bypassing the intended mitigation. --

commit 125b825fe12cce02b0f6ac3d6d7b8bd72cd92cfb
Author: Xin Li (Intel) <[email protected]>

KVM: VMX: Disable FRED if FRED consistency checks fail

This commit adds a check to disable the FRED CPU capability if FRED consistency checks fail during VMX initialization. It clears the X86_FEATURE_FRED capability by verifying the presence of VM_ENTRY_LOAD_IA32_FRED in the entry controls.

Quoted 3 lines
arch/x86/kvm/vmx/vmx.c +0 -0

[ ... ]

arch/x86/kvm/vmx/vmx.c static __init void vmx_set_cpu_caps(void) · line 8127

Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +3 -0
@@ -8122,6 +8122,9 @@ static __init void vmx_set_cpu_caps(void)
 		kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64);
 	}
 
+	if (!cpu_has_vmx_fred())
+		kvm_cpu_cap_clear(X86_FEATURE_FRED);
+

[Severity: High]
This isn't a bug introduced by this patch, but is it possible that this mitigation can be bypassed due to a logical flaw in the pre-existing vmx_check_entry_exit_pairs() macro?

This new mitigation clears X86_FEATURE_FRED if cpu_has_vmx_fred() returns false, which checks for VM_ENTRY_LOAD_IA32_FRED. The presence of this entry control relies on the consistency checks performed earlier.

Looking at the pre-existing vmx_check_entry_exit_pairs() macro in arch/x86/kvm/vmx/vmx.c:

        if (!(entry_controls & n_ctrl) == !(exit_controls & x_ctrl))    \
                continue;                                               \

The x_ctrl parameter used for FRED is a multi-bit mask:

{ VM_ENTRY_LOAD_IA32_FRED,
SECONDARY_VM_EXIT_SAVE_IA32_FRED | SECONDARY_VM_EXIT_LOAD_IA32_FRED },

If the underlying hardware (or a nested hypervisor) provides incomplete support and only sets one of the exit bits (for example, just SAVE), the bitwise AND (exit_controls & x_ctrl) evaluates to a non-zero value. The logical NOT of this non-zero value evaluates to 0.

If the entry control bit is present, its logical NOT is also 0. Thus, the equality check passes (0 == 0), the macro skips clearing the entry bit, and VM_ENTRY_LOAD_IA32_FRED incorrectly remains set.

Because VM_ENTRY_LOAD_IA32_FRED is still set, cpu_has_vmx_fred() evaluates to true, and this new mitigation is bypassed. This could allow a guest to escalate privileges if the CPU fails to restore the host's FRED MSRs on VM-exit due to the incomplete exit controls.

Does the macro need to be updated to ensure all bits in a multi-bit mask are present before considering the controls consistent?

Quoted 3 lines
arch/x86/kvm/vmx/vmx.c +0 -0
 	if (!enable_pmu)
 		kvm_cpu_cap_clear(X86_FEATURE_PDCM);
 	kvm_caps.supported_perf_cap = vmx_get_perf_capabilities();
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Reviewed-by on v10 3/28
#12 lore raw

Re: [PATCH v10 03/28] KVM: VMX: Disable FRED if FRED consistency checks fail

In reply to Sohil Mehta
Quoted 3 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Do not virtualize FRED if FRED consistency checks fail.

Nit:
By code, it only does one check, so it's a bit confusing about "checks" at the first glance.

Quoted 8 lines

Either on broken hardware, or when run KVM on top of another hypervisor before the underlying hypervisor implements nested FRED correctly.

Quoted 4 lines

---
v10:
- Remove the comment about why not check FRED VM-exit controls in cpu_has_vmx_fred() (Sean).

Although Sean didn't want it in the comment, but is it acceptable to put it in the changelog?

Quoted 1 line

- Remove redundant parentheses (Sean).

#13 lore raw

Re: [PATCH v10 03/28] KVM: VMX: Disable FRED if FRED consistency checks fail

Quoted 9 lines · Binbin Wu
Quoted 3 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Do not virtualize FRED if FRED consistency checks fail.

Nit:
By code, it only does one check, so it's a bit confusing about "checks" at the first glance.

Will fix it.

Quoted 5 lines
Quoted 5 lines

Either on broken hardware, or when run KVM on top of another hypervisor before the underlying hypervisor implements nested FRED correctly.

Quoted 7 lines
Quoted 4 lines

Thanks!

Quoted 8 lines
Quoted 4 lines

---
v10:
- Remove the comment about why not check FRED VM-exit controls in cpu_has_vmx_fred() (Sean).

Although Sean didn't want it in the comment, but is it acceptable to put it in the changelog?

Sure, the commit log is pretty thin. Adding it should be fine.

#14 lore raw

PATCH v10 4/28 x86/cea: Prefix event stack names with ESTACK_

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Add the ESTACK_ prefix to event stack names to improve clarity and readability. Without the prefix, names like DF, NMI, and DB are too brief and potentially ambiguous.

This renaming also prepares for converting __this_cpu_ist_top_va from a macro into a function that accepts an enum exception_stack_ordering argument, without requiring changes to existing callsites.

---
v10:
- No change

---
 arch/x86/coco/sev/noinstr.c           |  4 ++--
 arch/x86/coco/sev/vc-handle.c         |  2 +-
 arch/x86/include/asm/cpu_entry_area.h | 26 +++++++++++++-------------
 arch/x86/kernel/cpu/common.c          | 10 +++++-----
 arch/x86/kernel/dumpstack_64.c        | 14 +++++++-------
 arch/x86/kernel/fred.c                |  6 +++---
 arch/x86/kernel/traps.c               |  2 +-
 arch/x86/mm/cpu_entry_area.c          | 12 ++++++------
 arch/x86/mm/fault.c                   |  2 +-
 9 files changed, 39 insertions(+), 39 deletions(-)
arch/x86/coco/sev/noinstr.c +2 -2
index e1e03f12fc7b..8a695ab67821 100644
@@ -31,7 +31,7 @@ static __always_inline bool on_vc_stack(struct pt_regs *regs)
 	if (ip_within_syscall_gap(regs))
 		return false;
 
-	return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
+	return ((sp >= __this_cpu_ist_bottom_va(ESTACK_VC)) && (sp < __this_cpu_ist_top_va(ESTACK_VC)));
 }
 
 /*
@@ -83,7 +83,7 @@ void noinstr __sev_es_ist_exit(void)
 	/* Read IST entry */
 	ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
 
-	if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
+	if (WARN_ON(ist == __this_cpu_ist_top_va(ESTACK_VC)))
 		return;
 
 	/* Read back old IST entry and write it to the TSS */
arch/x86/coco/sev/vc-handle.c +1 -1
index 96b62b49b2b5..134c14b489ef 100644
@@ -871,7 +871,7 @@ static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
 
 static __always_inline bool is_vc2_stack(unsigned long sp)
 {
-	return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
+	return (sp >= __this_cpu_ist_bottom_va(ESTACK_VC2) && sp < __this_cpu_ist_top_va(ESTACK_VC2));
 }
 
 static __always_inline bool vc_from_invalid_context(struct pt_regs *regs)
arch/x86/include/asm/cpu_entry_area.h +13 -13
index 462fc34f1317..d0f884c28178 100644
@@ -18,19 +18,19 @@
 
 /* Macro to enforce the same ordering and stack sizes */
 #define ESTACKS_MEMBERS(guardsize, optional_stack_size)		\
-	char	DF_stack_guard[guardsize];			\
-	char	DF_stack[EXCEPTION_STKSZ];			\
-	char	NMI_stack_guard[guardsize];			\
-	char	NMI_stack[EXCEPTION_STKSZ];			\
-	char	DB_stack_guard[guardsize];			\
-	char	DB_stack[EXCEPTION_STKSZ];			\
-	char	MCE_stack_guard[guardsize];			\
-	char	MCE_stack[EXCEPTION_STKSZ];			\
-	char	VC_stack_guard[guardsize];			\
-	char	VC_stack[optional_stack_size];			\
-	char	VC2_stack_guard[guardsize];			\
-	char	VC2_stack[optional_stack_size];			\
-	char	IST_top_guard[guardsize];			\
+	char	ESTACK_DF_stack_guard[guardsize];		\
+	char	ESTACK_DF_stack[EXCEPTION_STKSZ];		\
+	char	ESTACK_NMI_stack_guard[guardsize];		\
+	char	ESTACK_NMI_stack[EXCEPTION_STKSZ];		\
+	char	ESTACK_DB_stack_guard[guardsize];		\
+	char	ESTACK_DB_stack[EXCEPTION_STKSZ];		\
+	char	ESTACK_MCE_stack_guard[guardsize];		\
+	char	ESTACK_MCE_stack[EXCEPTION_STKSZ];		\
+	char	ESTACK_VC_stack_guard[guardsize];		\
+	char	ESTACK_VC_stack[optional_stack_size];		\
+	char	ESTACK_VC2_stack_guard[guardsize];		\
+	char	ESTACK_VC2_stack[optional_stack_size];		\
+	char	ESTACK_IST_top_guard[guardsize];		\
 
 /* The exception stacks' physical storage. No guard pages required */
 struct exception_stacks {
arch/x86/kernel/cpu/common.c +5 -5
index a3df21d26460..99ec284fb829 100644
@@ -2372,12 +2372,12 @@ static inline void setup_getcpu(int cpu)
 static inline void tss_setup_ist(struct tss_struct *tss)
 {
 	/* Set up the per-CPU TSS IST stacks */
-	tss->x86_tss.ist[IST_INDEX_DF] = __this_cpu_ist_top_va(DF);
-	tss->x86_tss.ist[IST_INDEX_NMI] = __this_cpu_ist_top_va(NMI);
-	tss->x86_tss.ist[IST_INDEX_DB] = __this_cpu_ist_top_va(DB);
-	tss->x86_tss.ist[IST_INDEX_MCE] = __this_cpu_ist_top_va(MCE);
+	tss->x86_tss.ist[IST_INDEX_DF]	= __this_cpu_ist_top_va(ESTACK_DF);
+	tss->x86_tss.ist[IST_INDEX_NMI]	= __this_cpu_ist_top_va(ESTACK_NMI);
+	tss->x86_tss.ist[IST_INDEX_DB]	= __this_cpu_ist_top_va(ESTACK_DB);
+	tss->x86_tss.ist[IST_INDEX_MCE]	= __this_cpu_ist_top_va(ESTACK_MCE);
 	/* Only mapped when SEV-ES is active */
-	tss->x86_tss.ist[IST_INDEX_VC] = __this_cpu_ist_top_va(VC);
+	tss->x86_tss.ist[IST_INDEX_VC]	= __this_cpu_ist_top_va(ESTACK_VC);
 }
 #else /* CONFIG_X86_64 */
 static inline void tss_setup_ist(struct tss_struct *tss) { }
arch/x86/kernel/dumpstack_64.c +7 -7
index 6c5defd6569a..40f51e278171 100644
@@ -73,7 +73,7 @@ struct estack_pages {
 	 PFN_DOWN(CEA_ESTACK_OFFS(st) + CEA_ESTACK_SIZE(st) - 1)] = {	\
 		.offs	= CEA_ESTACK_OFFS(st),				\
 		.size	= CEA_ESTACK_SIZE(st),				\
-		.type	= STACK_TYPE_EXCEPTION + ESTACK_ ##st, }
+		.type	= STACK_TYPE_EXCEPTION + st, }
 
 /*
  * Array of exception stack page descriptors. If the stack is larger than
@@ -83,12 +83,12 @@ struct estack_pages {
  */
 static const
 struct estack_pages estack_pages[CEA_ESTACK_PAGES] ____cacheline_aligned = {
-	EPAGERANGE(DF),
-	EPAGERANGE(NMI),
-	EPAGERANGE(DB),
-	EPAGERANGE(MCE),
-	EPAGERANGE(VC),
-	EPAGERANGE(VC2),
+	EPAGERANGE(ESTACK_DF),
+	EPAGERANGE(ESTACK_NMI),
+	EPAGERANGE(ESTACK_DB),
+	EPAGERANGE(ESTACK_MCE),
+	EPAGERANGE(ESTACK_VC),
+	EPAGERANGE(ESTACK_VC2),
 };
 
 static __always_inline bool in_exception_stack(unsigned long *stack, struct stack_info *info)
arch/x86/kernel/fred.c +3 -3
index 117aa06d25ca..1c452a389a70 100644
@@ -84,7 +84,7 @@ void cpu_init_fred_rsps(void)
 	       FRED_STKLVL(X86_TRAP_DF,  FRED_DF_STACK_LEVEL));
 
 	/* The FRED equivalents to IST stacks... */
-	wrmsrq(MSR_IA32_FRED_RSP1, __this_cpu_ist_top_va(DB));
-	wrmsrq(MSR_IA32_FRED_RSP2, __this_cpu_ist_top_va(NMI));
-	wrmsrq(MSR_IA32_FRED_RSP3, __this_cpu_ist_top_va(DF));
+	wrmsrq(MSR_IA32_FRED_RSP1, __this_cpu_ist_top_va(ESTACK_DB));
+	wrmsrq(MSR_IA32_FRED_RSP2, __this_cpu_ist_top_va(ESTACK_NMI));
+	wrmsrq(MSR_IA32_FRED_RSP3, __this_cpu_ist_top_va(ESTACK_DF));
 }
arch/x86/kernel/traps.c +1 -1
index 30aa8369957e..8afd607a5873 100644
@@ -1075,7 +1075,7 @@ asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *r
 
 	if (!get_stack_info_noinstr(stack, current, &info) || info.type == STACK_TYPE_ENTRY ||
 	    info.type > STACK_TYPE_EXCEPTION_LAST)
-		sp = __this_cpu_ist_top_va(VC2);
+		sp = __this_cpu_ist_top_va(ESTACK_VC2);
 
 sync:
 	/*
arch/x86/mm/cpu_entry_area.c +6 -6
index 575f863f3c75..9fa371af8abc 100644
@@ -151,15 +151,15 @@ static void __init percpu_setup_exception_stacks(unsigned int cpu)
 	 * by guard pages so each stack must be mapped separately. DB2 is
 	 * not mapped; it just exists to catch triple nesting of #DB.
 	 */
-	cea_map_stack(DF);
-	cea_map_stack(NMI);
-	cea_map_stack(DB);
-	cea_map_stack(MCE);
+	cea_map_stack(ESTACK_DF);
+	cea_map_stack(ESTACK_NMI);
+	cea_map_stack(ESTACK_DB);
+	cea_map_stack(ESTACK_MCE);
 
 	if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) {
 		if (cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT)) {
-			cea_map_stack(VC);
-			cea_map_stack(VC2);
+			cea_map_stack(ESTACK_VC);
+			cea_map_stack(ESTACK_VC2);
 		}
 	}
 }
arch/x86/mm/fault.c +1 -1
index 45b99c3b1442..f6ee1cc3f125 100644
@@ -677,7 +677,7 @@ page_fault_oops(struct pt_regs *regs, unsigned long error_code,
 		 * and then double-fault, though, because we're likely to
 		 * break the console driver and lose most of the stack dump.
 		 */
-		call_on_stack(__this_cpu_ist_top_va(DF) - sizeof(void*),
+		call_on_stack(__this_cpu_ist_top_va(ESTACK_DF) - sizeof(void*),
 			      handle_stack_overflow,
 			      ASM_CALL_ARG3,
 			      , [arg1] "r" (regs), [arg2] "r" (address), [arg3] "r" (&info));
Signature · 1 line
2.43.0
Reviewed-by on v10 4/28
#15 lore raw

Re: [PATCH v10 04/28] x86/cea: Prefix event stack names with ESTACK_

Quoted 6 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Add the ESTACK_ prefix to event stack names to improve clarity and readability. Without the prefix, names like DF, NMI, and DB are too brief and potentially ambiguous.

Quoted 7 lines

This renaming also prepares for converting __this_cpu_ist_top_va from a macro into a function that accepts an enum exception_stack_ordering argument, without requiring changes to existing callsites.

#16 lore raw

PATCH v10 5/28 x86/cea: Use array indexing to simplify exception stack access

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Refactor struct cea_exception_stacks to leverage array indexing for exception stack access, improving code clarity and eliminating the need for the ESTACKS_MEMBERS() macro.

Convert __this_cpu_ist_{bottom,top}_va() from macros to functions, allowing removal of the now-obsolete CEA_ESTACK_BOT and CEA_ESTACK_TOP macros.

Also drop CEA_ESTACK_SIZE, which just duplicated EXCEPTION_STKSZ.

---
v10:
- Check if the stack argument is within the array bounds of event_stacks (Boris).

v9:
- Refactor first and then export in a separate patch (Dave Hansen).

---
 arch/x86/include/asm/cpu_entry_area.h | 52 ++++++++++++---------------
 arch/x86/kernel/dumpstack_64.c        |  4 +--
 arch/x86/mm/cpu_entry_area.c          | 22 +++++++++++-
 3 files changed, 45 insertions(+), 33 deletions(-)
arch/x86/include/asm/cpu_entry_area.h +22 -30
index d0f884c28178..509e52fc3a0f 100644
@@ -16,6 +16,19 @@
 #define VC_EXCEPTION_STKSZ	0
 #endif
 
+/*
+ * The exception stack ordering in [cea_]exception_stacks
+ */
+enum exception_stack_ordering {
+	ESTACK_DF,
+	ESTACK_NMI,
+	ESTACK_DB,
+	ESTACK_MCE,
+	ESTACK_VC,
+	ESTACK_VC2,
+	N_EXCEPTION_STACKS
+};
+
 /* Macro to enforce the same ordering and stack sizes */
 #define ESTACKS_MEMBERS(guardsize, optional_stack_size)		\
 	char	ESTACK_DF_stack_guard[guardsize];		\
@@ -39,37 +52,22 @@ struct exception_stacks {
 
 /* The effective cpu entry area mapping with guard pages. */
 struct cea_exception_stacks {
-	ESTACKS_MEMBERS(PAGE_SIZE, EXCEPTION_STKSZ)
+	struct {
+		char stack_guard[PAGE_SIZE];
+		char stack[EXCEPTION_STKSZ];
+	} event_stacks[N_EXCEPTION_STACKS];
+	char IST_top_guard[PAGE_SIZE];
 };
 
-/*
- * The exception stack ordering in [cea_]exception_stacks
- */
-enum exception_stack_ordering {
-	ESTACK_DF,
-	ESTACK_NMI,
-	ESTACK_DB,
-	ESTACK_MCE,
-	ESTACK_VC,
-	ESTACK_VC2,
-	N_EXCEPTION_STACKS
-};
-
-#define CEA_ESTACK_SIZE(st)					\
-	sizeof(((struct cea_exception_stacks *)0)->st## _stack)
-
-#define CEA_ESTACK_BOT(ceastp, st)				\
-	((unsigned long)&(ceastp)->st## _stack)
-
-#define CEA_ESTACK_TOP(ceastp, st)				\
-	(CEA_ESTACK_BOT(ceastp, st) + CEA_ESTACK_SIZE(st))
-
 #define CEA_ESTACK_OFFS(st)					\
-	offsetof(struct cea_exception_stacks, st## _stack)
+	offsetof(struct cea_exception_stacks, event_stacks[st].stack)
 
 #define CEA_ESTACK_PAGES					\
 	(sizeof(struct cea_exception_stacks) / PAGE_SIZE)
 
+extern unsigned long __this_cpu_ist_top_va(enum exception_stack_ordering stack);
+extern unsigned long __this_cpu_ist_bottom_va(enum exception_stack_ordering stack);
+
 #endif
 
 #ifdef CONFIG_X86_32
@@ -144,10 +142,4 @@ static __always_inline struct entry_stack *cpu_entry_stack(int cpu)
 	return &get_cpu_entry_area(cpu)->entry_stack_page.stack;
 }
 
-#define __this_cpu_ist_top_va(name)					\
-	CEA_ESTACK_TOP(__this_cpu_read(cea_exception_stacks), name)
-
-#define __this_cpu_ist_bottom_va(name)					\
-	CEA_ESTACK_BOT(__this_cpu_read(cea_exception_stacks), name)
-
 #endif
arch/x86/kernel/dumpstack_64.c +2 -2
index 40f51e278171..93b10b264e53 100644
@@ -70,9 +70,9 @@ struct estack_pages {
 
 #define EPAGERANGE(st)							\
 	[PFN_DOWN(CEA_ESTACK_OFFS(st)) ...				\
-	 PFN_DOWN(CEA_ESTACK_OFFS(st) + CEA_ESTACK_SIZE(st) - 1)] = {	\
+	 PFN_DOWN(CEA_ESTACK_OFFS(st) + EXCEPTION_STKSZ - 1)] = {	\
 		.offs	= CEA_ESTACK_OFFS(st),				\
-		.size	= CEA_ESTACK_SIZE(st),				\
+		.size	= EXCEPTION_STKSZ,				\
 		.type	= STACK_TYPE_EXCEPTION + st, }
 
 /*
arch/x86/mm/cpu_entry_area.c +21 -1
index 9fa371af8abc..a47dfd686bd3 100644
@@ -18,6 +18,26 @@ static DEFINE_PER_CPU_PAGE_ALIGNED(struct entry_stack_page, entry_stack_storage)
 static DEFINE_PER_CPU_PAGE_ALIGNED(struct exception_stacks, exception_stacks);
 DEFINE_PER_CPU(struct cea_exception_stacks*, cea_exception_stacks);
 
+/*
+ * Typically invoked by entry code, so must be noinstr.
+ */
+noinstr unsigned long __this_cpu_ist_bottom_va(enum exception_stack_ordering stack)
+{
+	struct cea_exception_stacks *s;
+
+	BUILD_BUG_ON(ESTACK_DF != 0);
+	BUG_ON(stack >= N_EXCEPTION_STACKS);
+
+	s = __this_cpu_read(cea_exception_stacks);
+
+	return (unsigned long)&s->event_stacks[stack].stack;
+}
+
+noinstr unsigned long __this_cpu_ist_top_va(enum exception_stack_ordering stack)
+{
+	return __this_cpu_ist_bottom_va(stack) + EXCEPTION_STKSZ;
+}
+
 static DEFINE_PER_CPU_READ_MOSTLY(unsigned long, _cea_offset);
 
 static __always_inline unsigned int cea_offset(unsigned int cpu)
@@ -132,7 +152,7 @@ static void __init percpu_setup_debug_store(unsigned int cpu)
 
 #define cea_map_stack(name) do {					\
 	npages = sizeof(estacks->name## _stack) / PAGE_SIZE;		\
-	cea_map_percpu_pages(cea->estacks.name## _stack,		\
+	cea_map_percpu_pages(cea->estacks.event_stacks[name].stack,	\
 			estacks->name## _stack, npages, PAGE_KERNEL);	\
 	} while (0)
 
Signature · 1 line
2.43.0
#17 lore raw

Re: [PATCH v10 05/28] x86/cea: Use array indexing to simplify exception stack access

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Unnecessary out-of-line function calls and runtime bounds checks introduced in highly…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Unnecessary out-of-line function calls and runtime bounds checks introduced in highly performance-sensitive #VC exception entry paths. --

commit 6ef3745e3d1d46a5989ce999cb84609a2d082888
Author: Xin Li (Intel) <[email protected]>

x86/cea: Use array indexing to simplify exception stack access

Refactors struct cea_exception_stacks to leverage array indexing for exception stack access, improving code clarity. Converts __this_cpu_ist_{bottom,top}_va() from macros to functions.

Quoted 7 lines
arch/x86/mm/cpu_entry_area.c +0 -0
index 9fa371af8abc7..a47dfd686bd33 100644
@@ -18,6 +18,26 @@ static DEFINE_PER_CPU_PAGE_ALIGNED(struct entry_stack_page, entry_stack_storage)
 static DEFINE_PER_CPU_PAGE_ALIGNED(struct exception_stacks, exception_stacks);
 DEFINE_PER_CPU(struct cea_exception_stacks*, cea_exception_stacks);

arch/x86/mm/cpu_entry_area.c static DEFINE_PER_CPU_PAGE_ALIGNED(struct entry_stack_page, entry_stack_storage) · line 29

Quoted 10 lines
arch/x86/mm/cpu_entry_area.c +9 -0
 
+/*
+ * Typically invoked by entry code, so must be noinstr.
+ */
+noinstr unsigned long __this_cpu_ist_bottom_va(enum exception_stack_ordering stack)
+{
+	struct cea_exception_stacks *s;
+
+	BUILD_BUG_ON(ESTACK_DF != 0);
+	BUG_ON(stack >= N_EXCEPTION_STACKS);

[Severity: Medium]
Does moving these helpers from macros in the header to out-of-line functions introduce an unintended performance regression?

Because the functions are defined out-of-line in a different translation unit, the compiler cannot statically evaluate the BUG_ON(stack >= N_EXCEPTION_STACKS) bounds checks nor inline the pointer math.

This incurs a penalty of multiple function calls and dynamic checks in performance-sensitive #VC exception entry paths. For example, hot paths like is_vc2_stack() in arch/x86/coco/sev/vc-handle.c repeatedly call these functions, which are evaluated on every #VC exception:

arch/x86/coco/sev/vc-handle.c:is_vc2_stack() {
    ...
    return (sp >= __this_cpu_ist_bottom_va(ESTACK_VC2) &&
            sp < __this_cpu_ist_top_va(ESTACK_VC2));
}

Could this regression in a noinstr entry path be avoided by defining these helpers as static __always_inline in the header instead?

Quoted 5 lines
arch/x86/mm/cpu_entry_area.c +5 -0
+
+	s = __this_cpu_read(cea_exception_stacks);
+
+	return (unsigned long)&s->event_stacks[stack].stack;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#18 lore raw

Re: [PATCH v10 05/28] x86/cea: Use array indexing to simplify exception stack access

Quoted 23 lines · On 9/11/2026 2:57 PM, [email protected] wrote:

arch/x86/mm/cpu_entry_area.c static DEFINE_PER_CPU_PAGE_ALIGNED(struct entry_stack_page, entry_stack_storage) · line 29

Quoted 9 lines
arch/x86/mm/cpu_entry_area.c +9 -0
+/*
+ * Typically invoked by entry code, so must be noinstr.
+ */
+noinstr unsigned long __this_cpu_ist_bottom_va(enum exception_stack_ordering stack)
+{
+	struct cea_exception_stacks *s;
+
+	BUILD_BUG_ON(ESTACK_DF != 0);
+	BUG_ON(stack >= N_EXCEPTION_STACKS);

[Severity: Medium]
Does moving these helpers from macros in the header to out-of-line functions introduce an unintended performance regression?

Because the functions are defined out-of-line in a different translation unit, the compiler cannot statically evaluate the BUG_ON(stack >= N_EXCEPTION_STACKS) bounds checks nor inline the pointer math.

This incurs a penalty of multiple function calls and dynamic checks in performance-sensitive #VC exception entry paths. For example, hot paths like is_vc2_stack() in arch/x86/coco/sev/vc-handle.c repeatedly call these functions, which are evaluated on every #VC exception:

Quoted 9 lines
arch/x86/coco/sev/vc-handle.c:is_vc2_stack() {
    ...
    return (sp >= __this_cpu_ist_bottom_va(ESTACK_VC2) &&
            sp < __this_cpu_ist_top_va(ESTACK_VC2));
}

Could this regression in a noinstr entry path be avoided by defining these helpers as static __always_inline in the header instead?

The performance regression concern seems overblown to me. The #VC handling has other heavy-handed things such as GHCB and VMGEXIT. The extra cycles for __this_cpu_ist_bottom_va() and __this_cpu_ist_top_va() shouldn't have any meaningful impact.

I am thinking of avoiding the __always_inline directive unless someone has a strong reason/preference.

Quoted 6 lines
Quoted 5 lines
arch/x86/mm/cpu_entry_area.c +5 -0
+
+	s = __this_cpu_read(cea_exception_stacks);
+
+	return (unsigned long)&s->event_stacks[stack].stack;
+}
Reviewed-by on v10 5/28
#19 lore raw

Re: [PATCH v10 05/28] x86/cea: Use array indexing to simplify exception stack access

In reply to Sohil Mehta
Quoted 10 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Refactor struct cea_exception_stacks to leverage array indexing for exception stack access, improving code clarity and eliminating the need for the ESTACKS_MEMBERS() macro.

Convert __this_cpu_ist_{bottom,top}_va() from macros to functions, allowing removal of the now-obsolete CEA_ESTACK_BOT and CEA_ESTACK_TOP macros.

Quoted 5 lines

Also drop CEA_ESTACK_SIZE, which just duplicated EXCEPTION_STKSZ.

One nit below.

[...]>

Quoted 4 lines
arch/x86/include/asm/cpu_entry_area.h +4 -0
+/*
+ * The exception stack ordering in [cea_]exception_stacks
+ */
+enum exception_stack_ordering {

arch/x86/include/asm/cpu_entry_area.h line 32

Quoted 10 lines
arch/x86/include/asm/cpu_entry_area.h +9 -0
+	ESTACK_DF,
+	ESTACK_NMI,
+	ESTACK_DB,
+	ESTACK_MCE,
+	ESTACK_VC,
+	ESTACK_VC2,
+	N_EXCEPTION_STACKS
+};
+
 /* Macro to enforce the same ordering and stack sizes */

Nit:
Is this still hold ? ...

arch/x86/include/asm/cpu_entry_area.h struct exception_stacks { · line 59

Quoted 12 lines

#define ESTACKS_MEMBERS(guardsize, optional_stack_size) \

arch/x86/include/asm/cpu_entry_area.h +5 -1
 	char	ESTACK_DF_stack_guard[guardsize];		\
@@ -39,37 +52,22 @@ struct exception_stacks {
 
 /* The effective cpu entry area mapping with guard pages. */
 struct cea_exception_stacks {
-	ESTACKS_MEMBERS(PAGE_SIZE, EXCEPTION_STKSZ)
+	struct {
+		char stack_guard[PAGE_SIZE];
+		char stack[EXCEPTION_STKSZ];
+	} event_stacks[N_EXCEPTION_STACKS];
+	char IST_top_guard[PAGE_SIZE];

... Before this change, ESTACKS_MEMBERS() is used both in exception_stacks and cea_exception_stacks, so ESTACKS_MEMBERS() can enforce the order and stack sizes.

After the change, ESTACKS_MEMBERS() only used in one place, so it doesn't have the capability to enforce them.

The order consistency depends on the consistency b/t ESTACKS_MEMBERS and enum exception_stack_ordering now.

Quoted 1 line
(quoted diff) +0 -0
 };

[...]

#20 lore raw

Re: [PATCH v10 05/28] x86/cea: Use array indexing to simplify exception stack access

Quoted 11 lines · Binbin Wu
Quoted 10 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Refactor struct cea_exception_stacks to leverage array indexing for exception stack access, improving code clarity and eliminating the need for the ESTACKS_MEMBERS() macro.

Convert __this_cpu_ist_{bottom,top}_va() from macros to functions, allowing removal of the now-obsolete CEA_ESTACK_BOT and CEA_ESTACK_TOP macros.

Quoted 8 lines
Quoted 5 lines

Also drop CEA_ESTACK_SIZE, which just duplicated EXCEPTION_STKSZ.

Thanks!

Quoted 12 lines

One nit below.

[...]>

Quoted 9 lines
(quoted diff) +9 -0
+/*
+ * The exception stack ordering in [cea_]exception_stacks
+ */
+enum exception_stack_ordering {
+	ESTACK_DF,
+	ESTACK_NMI,
+	ESTACK_DB,
+	ESTACK_MCE,
+	ESTACK_VC,
Quoted 9 lines

Review

Quoted 5 lines
(quoted diff) +4 -0
+	ESTACK_VC2,
+	N_EXCEPTION_STACKS
+};
+
 /* Macro to enforce the same ordering and stack sizes */

Nit:
Is this still hold ? ...

You are right. The comment is stale now. Overall, as the changelog says the ESTACKS_MEMBERS marco itself is redundant.

I am wondering if the remaining single use of ESTACKS_MEMBERS() should be simplified as follows:

(quoted diff) +0 -0

b/arch/x86/include/asm/cpu_entry_area.h
index 509e52fc3a0f..f34062c7bde1 100644

arch/x86/include/asm/cpu_entry_area.h +6 -17
@@ -31,21 +31,10 @@ enum exception_stack_ordering {
 
-/* Macro to enforce the same ordering and stack sizes */
-#define ESTACKS_MEMBERS(guardsize, optional_stack_size)                \
-       char    ESTACK_DF_stack_guard[guardsize];               \
-       char    ESTACK_DF_stack[EXCEPTION_STKSZ];               \
-       char    ESTACK_NMI_stack_guard[guardsize];              \
-       char    ESTACK_NMI_stack[EXCEPTION_STKSZ];              \
-       char    ESTACK_DB_stack_guard[guardsize];               \
-       char    ESTACK_DB_stack[EXCEPTION_STKSZ];               \
-       char    ESTACK_MCE_stack_guard[guardsize];              \
-       char    ESTACK_MCE_stack[EXCEPTION_STKSZ];              \
-       char    ESTACK_VC_stack_guard[guardsize];               \
-       char    ESTACK_VC_stack[optional_stack_size];           \
-       char    ESTACK_VC2_stack_guard[guardsize];              \
-       char    ESTACK_VC2_stack[optional_stack_size];          \
-       char    ESTACK_IST_top_guard[guardsize];                \
-
 /* The exception stacks' physical storage. No guard pages required */
 struct exception_stacks {
-       ESTACKS_MEMBERS(0, VC_EXCEPTION_STKSZ)
+       char    ESTACK_DF_stack[EXCEPTION_STKSZ];
+       char    ESTACK_NMI_stack[EXCEPTION_STKSZ];
+       char    ESTACK_DB_stack[EXCEPTION_STKSZ];
+       char    ESTACK_MCE_stack[EXCEPTION_STKSZ];
+       char    ESTACK_VC_stack[VC_EXCEPTION_STKSZ];
+       char    ESTACK_VC2_stack[VC_EXCEPTION_STKSZ];
 };
Quoted 17 lines

Review struct exception_stacks { · line 59

Quoted 12 lines

#define ESTACKS_MEMBERS(guardsize, optional_stack_size) \

(quoted diff) +5 -1
 	char	ESTACK_DF_stack_guard[guardsize];		\
@@ -39,37 +52,22 @@ struct exception_stacks {
 
 /* The effective cpu entry area mapping with guard pages. */
 struct cea_exception_stacks {
-	ESTACKS_MEMBERS(PAGE_SIZE, EXCEPTION_STKSZ)
+	struct {
+		char stack_guard[PAGE_SIZE];
+		char stack[EXCEPTION_STKSZ];
+	} event_stacks[N_EXCEPTION_STACKS];
+	char IST_top_guard[PAGE_SIZE];

... Before this change, ESTACKS_MEMBERS() is used both in exception_stacks and cea_exception_stacks, so ESTACKS_MEMBERS() can enforce the order and stack sizes.

Quoted 6 lines

After the change, ESTACKS_MEMBERS() only used in one place, so it doesn't have the capability to enforce them.

The order consistency depends on the consistency b/t ESTACKS_MEMBERS and enum exception_stack_ordering now.

IIUC, there is no ordering requirement left to enforce. The mapping is done per stack by name in cea_map_stack(), right? Also, the size is already inconsistent due to VC_EXCEPTION_STKSZ being config-dependent.

I think the change in this patch doesn't change any behavior. It only refactors the macros to improve clarity and converts a couple of them into functions.

Quoted 3 lines
Quoted 1 line
(quoted diff) +0 -0
 };

[...]

#21 lore raw

Re: [PATCH v10 05/28] x86/cea: Use array indexing to simplify exception stack access

In reply to Sohil Mehta
Quoted 7 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Refactor struct cea_exception_stacks to leverage array indexing for exception stack access, improving code clarity and eliminating the need for the ESTACKS_MEMBERS() macro.

Convert __this_cpu_ist_{bottom,top}_va() from macros to functions,

While, separating out these patches, I realized that this is no longer needed. this_cpu_fred_rsp() is planned to be exported instead of __this_cpu_ist_top_va().

So the FRED KVM enabling doesn't depend on patches 4 and 5 anymore. Even without the macro conversion the cleanups are useful. So, I posted them separately.

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

Planning to stop carrying the CEA patches in the FRED KVM series.

Quoted 7 lines
arch/x86/include/asm/cpu_entry_area.h +0 -6
-#define __this_cpu_ist_top_va(name)					\
-	CEA_ESTACK_TOP(__this_cpu_read(cea_exception_stacks), name)
-
-#define __this_cpu_ist_bottom_va(name)					\
-	CEA_ESTACK_BOT(__this_cpu_read(cea_exception_stacks), name)
-
 #endif

...

Quoted 21 lines
arch/x86/mm/cpu_entry_area.c +20 -0
+/*
+ * Typically invoked by entry code, so must be noinstr.
+ */
+noinstr unsigned long __this_cpu_ist_bottom_va(enum exception_stack_ordering stack)
+{
+	struct cea_exception_stacks *s;
+
+	BUILD_BUG_ON(ESTACK_DF != 0);
+	BUG_ON(stack >= N_EXCEPTION_STACKS);
+
+	s = __this_cpu_read(cea_exception_stacks);
+
+	return (unsigned long)&s->event_stacks[stack].stack;
+}
+
+noinstr unsigned long __this_cpu_ist_top_va(enum exception_stack_ordering stack)
+{
+	return __this_cpu_ist_bottom_va(stack) + EXCEPTION_STKSZ;
+}
+
 static DEFINE_PER_CPU_READ_MOSTLY(unsigned long, _cea_offset);
#22 lore raw

PATCH v10 6/28 x86/fred: Export this_cpu_fred_rsp() for KVM usage

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Introduce and export this_cpu_fred_rsp() to provide KVM with a self- explanatory interface for retrieving per-CPU FRED regular stacks for stack levels 1->3.

FRED introduced new fields in the VMCS host-state area for stack levels 1–>3 (HOST_IA32_FRED_RSP[123]), which correspond to the per-CPU FRED regular stacks for stack levels 1->3. KVM must populate these fields each time a vCPU is loaded onto a CPU to ensure a complete valid FRED event delivery context immediately after any VM-Exits.

---
v10:
- Replace direct, raw use of __this_cpu_ist_top_va() with a self- explanatory this_cpu_fred_rsp() helper for better readability (Sean).

---
 arch/x86/include/asm/fred.h | 10 ++++++++++
 arch/x86/kernel/fred.c      | 24 +++++++++++++++++++++---
 2 files changed, 31 insertions(+), 3 deletions(-)
arch/x86/include/asm/fred.h +10 -0
index 18a2f811c358..85b851f16bae 100644
@@ -35,6 +35,13 @@
 
 #ifndef __ASSEMBLER__
 
+enum fred_stack_level {
+	FRED_STACK_LEVEL_0,
+	FRED_STACK_LEVEL_1,
+	FRED_STACK_LEVEL_2,
+	FRED_STACK_LEVEL_3
+};
+
 #ifdef CONFIG_X86_FRED
 #include <linux/kernel.h>
 #include <linux/sched/task_stack.h>
@@ -105,6 +112,8 @@ static __always_inline void fred_update_rsp0(void)
 		__this_cpu_write(fred_rsp0, rsp0);
 	}
 }
+
+unsigned long this_cpu_fred_rsp(enum fred_stack_level lvl);
 #else /* CONFIG_X86_FRED */
 static __always_inline unsigned long fred_event_data(struct pt_regs *regs) { return 0; }
 static inline void cpu_init_fred_exceptions(void) { }
@@ -112,6 +121,7 @@ static inline void cpu_init_fred_rsps(void) { }
 static inline void fred_complete_exception_setup(void) { }
 static inline void fred_sync_rsp0(unsigned long rsp0) { }
 static inline void fred_update_rsp0(void) { }
+static inline unsigned long this_cpu_fred_rsp(enum fred_stack_level lvl) { return 0; }
 #endif /* CONFIG_X86_FRED */
 #endif /* !__ASSEMBLER__ */
 
arch/x86/kernel/fred.c +21 -3
index 1c452a389a70..68947c53a494 100644
@@ -1,5 +1,6 @@
 /* SPDX-License-Identifier: GPL-2.0 */
 #include <linux/kernel.h>
+#include <linux/kvm_types.h>
 
 #include <asm/desc.h>
 #include <asm/fred.h>
@@ -69,6 +70,23 @@ void cpu_init_fred_exceptions(void)
 	setup_clear_cpu_cap(X86_FEATURE_SYSCALL32);
 }
 
+unsigned long this_cpu_fred_rsp(enum fred_stack_level lvl)
+{
+	switch (lvl) {
+	case FRED_STACK_LEVEL_0:
+		return __this_cpu_read(fred_rsp0);
+	case FRED_STACK_LEVEL_1:
+		return __this_cpu_ist_top_va(ESTACK_DB);
+	case FRED_STACK_LEVEL_2:
+		return __this_cpu_ist_top_va(ESTACK_NMI);
+	case FRED_STACK_LEVEL_3:
+		return __this_cpu_ist_top_va(ESTACK_DF);
+	default:
+		BUG();
+	}
+}
+EXPORT_SYMBOL_FOR_KVM(this_cpu_fred_rsp);
+
 /* Must be called after setup_cpu_entry_areas() */
 void cpu_init_fred_rsps(void)
 {
@@ -84,7 +102,7 @@ void cpu_init_fred_rsps(void)
 	       FRED_STKLVL(X86_TRAP_DF,  FRED_DF_STACK_LEVEL));
 
 	/* The FRED equivalents to IST stacks... */
-	wrmsrq(MSR_IA32_FRED_RSP1, __this_cpu_ist_top_va(ESTACK_DB));
-	wrmsrq(MSR_IA32_FRED_RSP2, __this_cpu_ist_top_va(ESTACK_NMI));
-	wrmsrq(MSR_IA32_FRED_RSP3, __this_cpu_ist_top_va(ESTACK_DF));
+	wrmsrq(MSR_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+	wrmsrq(MSR_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+	wrmsrq(MSR_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
 }
Signature · 1 line
2.43.0
Reviewed-by on v10 6/28
#23 lore raw

Re: [PATCH v10 06/28] x86/fred: Export this_cpu_fred_rsp() for KVM usage

Quoted 6 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Introduce and export this_cpu_fred_rsp() to provide KVM with a self- explanatory interface for retrieving per-CPU FRED regular stacks for stack levels 1->3.

Quoted 8 lines

FRED introduced new fields in the VMCS host-state area for stack levels 1–>3 (HOST_IA32_FRED_RSP[123]), which correspond to the per-CPU FRED regular stacks for stack levels 1->3. KVM must populate these fields each time a vCPU is loaded onto a CPU to ensure a complete valid FRED event delivery context immediately after any VM-Exits.

Two nits below.

[...]

Quoted 8 lines
arch/x86/include/asm/fred.h +7 -0
+enum fred_stack_level {
+	FRED_STACK_LEVEL_0,
+	FRED_STACK_LEVEL_1,
+	FRED_STACK_LEVEL_2,
+	FRED_STACK_LEVEL_3
+};
+

[...]

arch/x86/kernel/fred.c void cpu_init_fred_exceptions(void) · line 81

Quoted 10 lines
arch/x86/kernel/fred.c +9 -0
+unsigned long this_cpu_fred_rsp(enum fred_stack_level lvl)
+{
+	switch (lvl) {
+	case FRED_STACK_LEVEL_0:
+		return __this_cpu_read(fred_rsp0);
+	case FRED_STACK_LEVEL_1:
+		return __this_cpu_ist_top_va(ESTACK_DB);
+	case FRED_STACK_LEVEL_2:
+		return __this_cpu_ist_top_va(ESTACK_NMI);

Nit:
How about adding a comment to state NMI and MC share this one?

Also, currently, FRED_{DB,NMI,MC,DF}_STACK_LEVEL are defined as number, may be it can be defined using the new added FRED_STACK_LEVEL_{1,2,3}

Quoted 22 lines
arch/x86/kernel/fred.c +11 -3
+	case FRED_STACK_LEVEL_3:
+		return __this_cpu_ist_top_va(ESTACK_DF);
+	default:
+		BUG();
+	}
+}
+EXPORT_SYMBOL_FOR_KVM(this_cpu_fred_rsp);
+
 /* Must be called after setup_cpu_entry_areas() */
 void cpu_init_fred_rsps(void)
 {
@@ -84,7 +102,7 @@ void cpu_init_fred_rsps(void)
 	       FRED_STKLVL(X86_TRAP_DF,  FRED_DF_STACK_LEVEL));
 
 	/* The FRED equivalents to IST stacks... */
-	wrmsrq(MSR_IA32_FRED_RSP1, __this_cpu_ist_top_va(ESTACK_DB));
-	wrmsrq(MSR_IA32_FRED_RSP2, __this_cpu_ist_top_va(ESTACK_NMI));
-	wrmsrq(MSR_IA32_FRED_RSP3, __this_cpu_ist_top_va(ESTACK_DF));
+	wrmsrq(MSR_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+	wrmsrq(MSR_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+	wrmsrq(MSR_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
 }
#24 lore raw

Re: [PATCH v10 06/28] x86/fred: Export this_cpu_fred_rsp() for KVM usage

Quoted 17 lines

Two nits below.

[...]

Quoted 8 lines
arch/x86/include/asm/fred.h +7 -0
+enum fred_stack_level {
+	FRED_STACK_LEVEL_0,
+	FRED_STACK_LEVEL_1,
+	FRED_STACK_LEVEL_2,
+	FRED_STACK_LEVEL_3
+};
+

[...]

Quoted 1 line
Quoted 13 lines

arch/x86/kernel/fred.c void cpu_init_fred_exceptions(void) · line 81

Quoted 9 lines
arch/x86/kernel/fred.c +9 -0
+unsigned long this_cpu_fred_rsp(enum fred_stack_level lvl)
+{
+	switch (lvl) {
+	case FRED_STACK_LEVEL_0:
+		return __this_cpu_read(fred_rsp0);
+	case FRED_STACK_LEVEL_1:
+		return __this_cpu_ist_top_va(ESTACK_DB);
+	case FRED_STACK_LEVEL_2:
+		return __this_cpu_ist_top_va(ESTACK_NMI);

Nit:
How about adding a comment to state NMI and MC share this one?

Sure, I'll add one.

Quoted 5 lines

Also, currently, FRED_{DB,NMI,MC,DF}_STACK_LEVEL are defined as number, may be it can be defined using the new added FRED_STACK_LEVEL_{1,2,3}

Good point. Something like this?

#define FRED_DB_STACK_LEVEL FRED_STACK_LEVEL_1
#define FRED_NMI_STACK_LEVEL FRED_STACK_LEVEL_2
#define FRED_MC_STACK_LEVEL FRED_STACK_LEVEL_2
#define FRED_DF_STACK_LEVEL FRED_STACK_LEVEL_3

By itself that leads to a compile issue with the macro FRED_STKLVL() which needs the following change.

-#define FRED_STKLVL(vector, lvl) ((lvl) << (2 * (vector)))
+#define FRED_STKLVL(vector, lvl) (_AT(unsigned long, lvl) << (2 *
(vector)))

It seems reasonable to me.

Quoted 23 lines
Quoted 22 lines
arch/x86/kernel/fred.c +11 -3
+	case FRED_STACK_LEVEL_3:
+		return __this_cpu_ist_top_va(ESTACK_DF);
+	default:
+		BUG();
+	}
+}
+EXPORT_SYMBOL_FOR_KVM(this_cpu_fred_rsp);
+
 /* Must be called after setup_cpu_entry_areas() */
 void cpu_init_fred_rsps(void)
 {
@@ -84,7 +102,7 @@ void cpu_init_fred_rsps(void)
 	       FRED_STKLVL(X86_TRAP_DF,  FRED_DF_STACK_LEVEL));
 
 	/* The FRED equivalents to IST stacks... */
-	wrmsrq(MSR_IA32_FRED_RSP1, __this_cpu_ist_top_va(ESTACK_DB));
-	wrmsrq(MSR_IA32_FRED_RSP2, __this_cpu_ist_top_va(ESTACK_NMI));
-	wrmsrq(MSR_IA32_FRED_RSP3, __this_cpu_ist_top_va(ESTACK_DF));
+	wrmsrq(MSR_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+	wrmsrq(MSR_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+	wrmsrq(MSR_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
 }
#25 lore raw

Re: [PATCH v10 06/28] x86/fred: Export this_cpu_fred_rsp() for KVM usage

In reply to Sohil Mehta
Quoted 15 lines · Sohil Mehta
arch/x86/include/asm/fred.h +7 -0
index 18a2f811c358..85b851f16bae 100644
@@ -35,6 +35,13 @@
 
 #ifndef __ASSEMBLER__
 
+enum fred_stack_level {
+	FRED_STACK_LEVEL_0,
+	FRED_STACK_LEVEL_1,
+	FRED_STACK_LEVEL_2,
+	FRED_STACK_LEVEL_3
+};
+

...

Quoted 7 lines
arch/x86/include/asm/fred.h +7 -0
+unsigned long this_cpu_fred_rsp(enum fred_stack_level lvl)
+{
+	switch (lvl) {
+	case FRED_STACK_LEVEL_0:
+		return __this_cpu_read(fred_rsp0);
+	case FRED_STACK_LEVEL_1:
+		return __this_cpu_ist_top_va(ESTACK_DB);

arch/x86/include/asm/fred.h

Quoted 10 lines
arch/x86/include/asm/fred.h +10 -0
+	case FRED_STACK_LEVEL_2:
+		return __this_cpu_ist_top_va(ESTACK_NMI);
+	case FRED_STACK_LEVEL_3:
+		return __this_cpu_ist_top_va(ESTACK_DF);
+	default:
+		BUG();
+	}
+}
+EXPORT_SYMBOL_FOR_KVM(this_cpu_fred_rsp);
+

I am not sure if the FRED_STACK_LEVEL_* abstraction is really helpful. It makes the KVM interface a bit convoluted I think. So right now we need to expose this_cpu_fred_rsp() as well as enum fred_stack_level for KVM to get the kernel stack information.

Sean suggested in v9 keying based on the MSR itself which makes more sense. https://lore.kernel.org/lkml/[email protected]/

It avoids exposing the enum and makes it future-proof with supervisor shadow stacks. KVM will need similar information for MSR_IA32_FRED_SSP1..3. With the current approach we would have to add another export for the SSP:

	unsigned long this_cpu_fred_ssp(enum fred_stack_level lvl);

Keying on the MSR index makes this simpler and can be easily expanded to SSP MSRs. We can name is this_cpu_fred_sp() to prevent Xin's rename concern in the above thread.

	unsigned long this_cpu_fred_sp(u32 msr);

So, the below would become

  wrmsrq(MSR_IA32_FRED_RSP1, this_cpu_fred_sp(MSR_IA32_FRED_RSP1));

Any concerns?

Quoted 14 lines

/* Must be called after setup_cpu_entry_areas() */ void cpu_init_fred_rsps(void)
{

arch/x86/include/asm/fred.h +3 -3
@@ -84,7 +102,7 @@ void cpu_init_fred_rsps(void)
 	       FRED_STKLVL(X86_TRAP_DF,  FRED_DF_STACK_LEVEL));
 
 	/* The FRED equivalents to IST stacks... */
-	wrmsrq(MSR_IA32_FRED_RSP1, __this_cpu_ist_top_va(ESTACK_DB));
-	wrmsrq(MSR_IA32_FRED_RSP2, __this_cpu_ist_top_va(ESTACK_NMI));
-	wrmsrq(MSR_IA32_FRED_RSP3, __this_cpu_ist_top_va(ESTACK_DF));
+	wrmsrq(MSR_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+	wrmsrq(MSR_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+	wrmsrq(MSR_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
 }
#26 lore raw

PATCH v10 7/28 KVM: VMX: Initialize VMCS FRED fields

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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

FRED CPU state is managed in 9 new FRED MSRs:

        IA32_FRED_CONFIG,
        IA32_FRED_STKLVLS,
        IA32_FRED_RSP0,
        IA32_FRED_RSP1,
        IA32_FRED_RSP2,
        IA32_FRED_RSP3,
        IA32_FRED_SSP1,
        IA32_FRED_SSP2,
        IA32_FRED_SSP3,
as well as a few existing CPU registers and MSRs:
        CR4.FRED,
        IA32_STAR,
        IA32_KERNEL_GS_BASE,
        IA32_PL0_SSP (also known as IA32_FRED_SSP0).

CR4, IA32_KERNEL_GS_BASE and IA32_STAR are already well managed. Except IA32_FRED_RSP0 and IA32_FRED_SSP0, all other FRED CPU state MSRs have corresponding VMCS fields in both the host-state and guest-state areas. So KVM just needs to initialize them, and with proper VM entry/exit FRED controls, a FRED CPU will keep tracking host and guest FRED CPU state in VMCS automatically.

---
v10:
- s/rdmsrl/rdmsrq (Chao)
- Remove a terse comment which doesn't help at all (Sean).
- Replace direct, raw use of __this_cpu_ist_top_va() with a self- explanatory this_cpu_fred_rsp() helper for better readability (Sean).
- Add cpu_feature_enabled(X86_FEATURE_FRED) to patch out accesses to VMCS FRED fields (Sean).
- Remove "#ifdef CONFIG_X86_64" after switching to this_cpu_fred_rsp() (Sean).

---
 arch/x86/include/asm/kvm_host.h |  3 +++
 arch/x86/include/asm/vmx.h      | 32 ++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/vmx.c          | 33 +++++++++++++++++++++++++++++++++
 3 files changed, 68 insertions(+)
arch/x86/include/asm/kvm_host.h +3 -0
index 683bb8bf43a9..8d3999772ac2 100644
@@ -294,6 +294,9 @@ struct kvm_host_values {
 	u64 xss;
 	u64 s_cet;
 	u64 arch_capabilities;
+
+	u64 fred_config;
+	u64 fred_stklvls;
 };
 extern struct kvm_host_values kvm_host;
 
arch/x86/include/asm/vmx.h +32 -0
index 682f09933612..4720619f09ac 100644
@@ -306,12 +306,44 @@ 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_CONFIG_HIGH	= 0x0000281b,
+	GUEST_IA32_FRED_RSP1		= 0x0000281c,
+	GUEST_IA32_FRED_RSP1_HIGH	= 0x0000281d,
+	GUEST_IA32_FRED_RSP2		= 0x0000281e,
+	GUEST_IA32_FRED_RSP2_HIGH	= 0x0000281f,
+	GUEST_IA32_FRED_RSP3		= 0x00002820,
+	GUEST_IA32_FRED_RSP3_HIGH	= 0x00002821,
+	GUEST_IA32_FRED_STKLVLS		= 0x00002822,
+	GUEST_IA32_FRED_STKLVLS_HIGH	= 0x00002823,
+	GUEST_IA32_FRED_SSP1		= 0x00002824,
+	GUEST_IA32_FRED_SSP1_HIGH	= 0x00002825,
+	GUEST_IA32_FRED_SSP2		= 0x00002826,
+	GUEST_IA32_FRED_SSP2_HIGH	= 0x00002827,
+	GUEST_IA32_FRED_SSP3		= 0x00002828,
+	GUEST_IA32_FRED_SSP3_HIGH	= 0x00002829,
 	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_CONFIG_HIGH	= 0x00002c09,
+	HOST_IA32_FRED_RSP1		= 0x00002c0a,
+	HOST_IA32_FRED_RSP1_HIGH	= 0x00002c0b,
+	HOST_IA32_FRED_RSP2		= 0x00002c0c,
+	HOST_IA32_FRED_RSP2_HIGH	= 0x00002c0d,
+	HOST_IA32_FRED_RSP3		= 0x00002c0e,
+	HOST_IA32_FRED_RSP3_HIGH	= 0x00002c0f,
+	HOST_IA32_FRED_STKLVLS		= 0x00002c10,
+	HOST_IA32_FRED_STKLVLS_HIGH	= 0x00002c11,
+	HOST_IA32_FRED_SSP1		= 0x00002c12,
+	HOST_IA32_FRED_SSP1_HIGH	= 0x00002c13,
+	HOST_IA32_FRED_SSP2		= 0x00002c14,
+	HOST_IA32_FRED_SSP2_HIGH	= 0x00002c15,
+	HOST_IA32_FRED_SSP3		= 0x00002c16,
+	HOST_IA32_FRED_SSP3_HIGH	= 0x00002c17,
 	PIN_BASED_VM_EXEC_CONTROL       = 0x00004000,
 	CPU_BASED_VM_EXEC_CONTROL       = 0x00004002,
 	EXCEPTION_BITMAP                = 0x00004004,
arch/x86/kvm/vmx/vmx.c +33 -0
index 2a2218e0983b..dc80ca5f804d 100644
@@ -1562,6 +1562,12 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu)
 				    (unsigned long)(cpu_entry_stack(cpu) + 1));
 		}
 
+		if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+			vmcs_write64(HOST_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+			vmcs_write64(HOST_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+			vmcs_write64(HOST_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
+		}
+
 		vmx->loaded_vmcs->cpu = cpu;
 	}
 }
@@ -4500,6 +4506,17 @@ void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
 	 */
 	vmcs_write16(HOST_DS_SELECTOR, 0);
 	vmcs_write16(HOST_ES_SELECTOR, 0);
+
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		/* FRED CONFIG and STKLVLS are the same on all CPUs */
+		vmcs_write64(HOST_IA32_FRED_CONFIG, kvm_host.fred_config);
+		vmcs_write64(HOST_IA32_FRED_STKLVLS, kvm_host.fred_stklvls);
+
+		/* Linux doesn't support kernel shadow stacks, thus SSPs are 0s */
+		vmcs_write64(HOST_IA32_FRED_SSP1, 0);
+		vmcs_write64(HOST_IA32_FRED_SSP2, 0);
+		vmcs_write64(HOST_IA32_FRED_SSP3, 0);
+	}
 #else
 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
@@ -5030,6 +5047,17 @@ static void init_vmcs(struct vcpu_vmx *vmx)
 	}
 
 	vmx_setup_uret_msrs(vmx);
+
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && 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);
+	}
 }
 
 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
@@ -8883,6 +8911,11 @@ __init int vmx_hardware_setup(void)
 
 	kvm_caps.inapplicable_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
 
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		rdmsrq(MSR_IA32_FRED_CONFIG, kvm_host.fred_config);
+		rdmsrq(MSR_IA32_FRED_STKLVLS, kvm_host.fred_stklvls);
+	}
+
 	return 0;
 }
 
Signature · 1 line
2.43.0
#27 lore raw

Re: [PATCH v10 07/28] KVM: VMX: Initialize VMCS FRED fields

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [Critical] Host FRED MSRs are left uninitialized/corrupted on VM-Exit if KVM skips explicit…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [Critical] Host FRED MSRs are left uninitialized/corrupted on VM-Exit if KVM skips explicit initialization while the hardware capabilities dictate loading them.
- [Critical] VM-Exit unconditionally corrupts the host's IA32_FRED_RSP0 MSR (alias for IA32_SYSENTER_ESP), causing host ring-3 to ring-0 transitions to use the wrong stack in FRED-enabled hosts when non-FRED guests run.
- [Critical] Guest FRED state is not explicitly initialized when the host has disabled FRED in software, leaving VMCS fields undefined.
--

commit 81aa8f5538dba9476f74b76b06da72ada534dd41
Author: Xin Li (Intel) <[email protected]>
Subject: KVM: VMX: Initialize VMCS FRED fields

This commit initializes host and guest VMCS fields for FRED (Flexible Return and Event Delivery). It populates the host fields with host MSR values and sets the guest fields to zero. The initialization is gated by checking if the X86_FEATURE_FRED CPU feature is enabled.

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

Quoted 6 lines
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -1562,6 +1562,12 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu)
 				    (unsigned long)(cpu_entry_stack(cpu) + 1));
 		}

[Severity: Critical]
Could unconditionally writing to HOST_IA32_SYSENTER_ESP corrupt the host's IA32_FRED_RSP0 MSR?

Because MSR_IA32_FRED_RSP0 is architecturally aliased to MSR_IA32_SYSENTER_ESP, every VM-Exit will load this small trampoline stack into MSR_IA32_FRED_RSP0.

If a guest does not have FRED enabled, KVM's vmx_prepare_switch_to_host() skips syncing the RSP0 state. The per-CPU cache __this_cpu_read(fred_rsp0) is never updated to reflect the hardware change, meaning fred_update_rsp0() assumes the MSR is already correct.

When the host returns to userspace and takes a syscall or interrupt, won't FRED deliver the event to ring 0 using this tiny trampoline stack instead of the proper task stack?

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

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +5 -0
+		if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+			vmcs_write64(HOST_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+			vmcs_write64(HOST_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+			vmcs_write64(HOST_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
+		}

[Severity: Critical]
Does checking cpu_feature_enabled(X86_FEATURE_FRED) here leave host VMCS fields uninitialized if the host booted with FRED disabled in software (e.g., via clearcpuid=fred)?

The SECONDARY_VM_EXIT_LOAD_IA32_FRED control is set statically in setup_vmcs_config() based purely on hardware capability MSRs. If KVM enables the exit control but skips initializing these fields because of this software check, the CPU will validate uninitialized memory (left over from VMCLEAR) on VM-Exit.

Can this cause a fatal VM-Exit failure due to non-canonical addresses or reserved bits in the uninitialized Host-State area?

[ ... ]

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

Quoted 6 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -4500,6 +4506,17 @@ void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
 	 */
 	vmcs_write16(HOST_DS_SELECTOR, 0);
 	vmcs_write16(HOST_ES_SELECTOR, 0);
+
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {

[Severity: Critical]
Does this condition share the same risk as vmx_vcpu_load_vmcs(), where a software-disabled FRED still forces a hardware VM-Exit load of these uninitialized host fields?

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +9 -0
+		/* FRED CONFIG and STKLVLS are the same on all CPUs */
+		vmcs_write64(HOST_IA32_FRED_CONFIG, kvm_host.fred_config);
+		vmcs_write64(HOST_IA32_FRED_STKLVLS, kvm_host.fred_stklvls);
+
+		/* Linux doesn't support kernel shadow stacks, thus SSPs are 0s */
+		vmcs_write64(HOST_IA32_FRED_SSP1, 0);
+		vmcs_write64(HOST_IA32_FRED_SSP2, 0);
+		vmcs_write64(HOST_IA32_FRED_SSP3, 0);
+	}
 #else

[ ... ]

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

Quoted 6 lines
arch/x86/kvm/vmx/vmx.c +2 -0
@@ -5030,6 +5047,17 @@ static void init_vmcs(struct vcpu_vmx *vmx)
 	}
 
 	vmx_setup_uret_msrs(vmx);
+
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {

[Severity: Critical]
Similarly to the host state, does this condition skip initializing the guest FRED fields if FRED is disabled in software?

If the hardware supports it, setup_vmcs_config() statically sets VM_ENTRY_LOAD_IA32_FRED. Skipping vmcs_write64() here leaves these fields architecturally undefined after a VMCLEAR operation.

Will this trigger an immediate VM-Entry failure when the CPU attempts to load the uninitialized guest FRED fields from the VMCS?

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +9 -0
+		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);
+	}
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#28 lore raw

Re: [PATCH v10 07/28] KVM: VMX: Initialize VMCS FRED fields

In reply to Sohil Mehta
Quoted 42 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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

FRED CPU state is managed in 9 new FRED MSRs:

        IA32_FRED_CONFIG,
        IA32_FRED_STKLVLS,
        IA32_FRED_RSP0,
        IA32_FRED_RSP1,
        IA32_FRED_RSP2,
        IA32_FRED_RSP3,
        IA32_FRED_SSP1,
        IA32_FRED_SSP2,
        IA32_FRED_SSP3,
as well as a few existing CPU registers and MSRs:
        CR4.FRED,
        IA32_STAR,
        IA32_KERNEL_GS_BASE,
        IA32_PL0_SSP (also known as IA32_FRED_SSP0).

CR4, IA32_KERNEL_GS_BASE and IA32_STAR are already well managed. Except IA32_FRED_RSP0 and IA32_FRED_SSP0, all other FRED CPU state MSRs have corresponding VMCS fields in both the host-state and guest-state areas. So KVM just needs to initialize them, and with proper VM entry/exit FRED controls, a FRED CPU will keep tracking host and guest FRED CPU state in VMCS automatically.

---
v10:
- s/rdmsrl/rdmsrq (Chao)
- Remove a terse comment which doesn't help at all (Sean).
- Replace direct, raw use of __this_cpu_ist_top_va() with a self- explanatory this_cpu_fred_rsp() helper for better readability (Sean).
- Add cpu_feature_enabled(X86_FEATURE_FRED) to patch out accesses to VMCS FRED fields (Sean).
- Remove "#ifdef CONFIG_X86_64" after switching to this_cpu_fred_rsp() (Sean).

[...]

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

Quoted 9 lines
arch/x86/kvm/vmx/vmx.c +1 -0
index 2a2218e0983b..dc80ca5f804d 100644
@@ -1562,6 +1562,12 @@ void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu)
 				    (unsigned long)(cpu_entry_stack(cpu) + 1));
 		}
 
+		if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {

Nit:
I was wondering why cpu_feature_enabled(X86_FEATURE_FRED) was needed for a while. Sorry I missed the version history :(

This seems to be the first time this cpu_feature_enabled() && kvm_cpu_cap_has() combination is used, maybe have a mention in the changelog?

Quoted 56 lines
arch/x86/kvm/vmx/vmx.c +32 -0
+			vmcs_write64(HOST_IA32_FRED_RSP1, this_cpu_fred_rsp(FRED_STACK_LEVEL_1));
+			vmcs_write64(HOST_IA32_FRED_RSP2, this_cpu_fred_rsp(FRED_STACK_LEVEL_2));
+			vmcs_write64(HOST_IA32_FRED_RSP3, this_cpu_fred_rsp(FRED_STACK_LEVEL_3));
+		}
+
 		vmx->loaded_vmcs->cpu = cpu;
 	}
 }
@@ -4500,6 +4506,17 @@ void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
 	 */
 	vmcs_write16(HOST_DS_SELECTOR, 0);
 	vmcs_write16(HOST_ES_SELECTOR, 0);
+
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		/* FRED CONFIG and STKLVLS are the same on all CPUs */
+		vmcs_write64(HOST_IA32_FRED_CONFIG, kvm_host.fred_config);
+		vmcs_write64(HOST_IA32_FRED_STKLVLS, kvm_host.fred_stklvls);
+
+		/* Linux doesn't support kernel shadow stacks, thus SSPs are 0s */
+		vmcs_write64(HOST_IA32_FRED_SSP1, 0);
+		vmcs_write64(HOST_IA32_FRED_SSP2, 0);
+		vmcs_write64(HOST_IA32_FRED_SSP3, 0);
+	}
 #else
 	vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
 	vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
@@ -5030,6 +5047,17 @@ static void init_vmcs(struct vcpu_vmx *vmx)
 	}
 
 	vmx_setup_uret_msrs(vmx);
+
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && 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);
+	}
 }
 
 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu)
@@ -8883,6 +8911,11 @@ __init int vmx_hardware_setup(void)
 
 	kvm_caps.inapplicable_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT;
 
+	if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {
+		rdmsrq(MSR_IA32_FRED_CONFIG, kvm_host.fred_config);
+		rdmsrq(MSR_IA32_FRED_STKLVLS, kvm_host.fred_stklvls);
+	}
+
 	return 0;
 }
 
#29 lore raw

Re: [PATCH v10 07/28] KVM: VMX: Initialize VMCS FRED fields

Quoted 10 lines

Review

Quoted 2 lines
(quoted diff) +1 -0
+		if (cpu_feature_enabled(X86_FEATURE_FRED) && kvm_cpu_cap_has(X86_FEATURE_FRED)) {

Nit:
I was wondering why cpu_feature_enabled(X86_FEATURE_FRED) was needed for a while. Sorry I missed the version history :(

This seems to be the first time this cpu_feature_enabled() && kvm_cpu_cap_has() combination is used, maybe have a mention in the changelog?

Sure will add a line or two in the changelog. It is mainly to patch out when FRED isn't supported.

#30 lore raw

PATCH v10 8/28 KVM: VMX: Set FRED MSR intercepts

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

On a userspace MSR filter change, set FRED MSR intercepts.

Because the following eight FRED MSRs,

        MSR_IA32_FRED_RSP[123], MSR_IA32_FRED_STKLVLS,
        MSR_IA32_FRED_SSP[123], MSR_IA32_FRED_CONFIG,

are used by the kernel itself to take an exception at any time, they should be context-switched by Intel VT-x automatically in order to preserve the FRED architectural invariant that there should NEVER be a "gap" during which it is unsafe to take an exception.

KVM leverages Intel VT-x hardware to automatically context switch the eight FRED MSRs using:

1) Dedicated host and guest VMCS fields for each MSR.

2) VM-entry/exit controls to manage the automated loading and saving of the eight FRED MSRs.

Consequently, passing these MSRs through to the guest would only add unnecessary handling code without benefit.

Both MSR_IA32_FRED_RSP0 and MSR_IA32_FRED_SSP0 (aka MSR_IA32_PL0_SSP) are dedicated for userspace event delivery, IOW they are NOT used in any kernel event delivery and the execution of ERETS. Thus KVM can run safely with guest values in the two MSRs. As a result, save and restore of their guest values are deferred until vCPU context switch, Host MSR_IA32_FRED_RSP0 is restored upon returning to userspace, and Host MSR_IA32_PL0_SSP is managed with XRSTORS/XSAVES.

MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) is part of CET supervisor state, but all four FRED SSP MSRs are architecturally visible on any processor that enumerates FRED. Even if CET is absent, these MSRs remain accessible via RDMSR/WRMSR, though FRED transitions will not use them.

Intercept MSR_IA32_PL0_SSP if CET shadow stacks are unsupported (even with FRED present). Since this MSR is rarely accessed and ignored by XSAVES in this configuration, interception avoids the overhead of manually context switching the hardware MSR during vcpu_load/put.

This behavior is consistent with the current setup in vmx_recalc_msr_intercepts(), so no change is needed to the interception logic for MSR_IA32_PL0_SSP.

---
v10:
- Improve the commit message and code comment with an explanation from hpa (Chao Gao and Dave Hansen).

---
 arch/x86/kvm/vmx/vmx.c | 67 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
arch/x86/kvm/vmx/vmx.c +67 -0
index dc80ca5f804d..09bbbc680aa7 100644
@@ -4304,6 +4304,72 @@ static void vmx_recalc_pmu_msr_intercepts(struct kvm_vcpu *vcpu)
 				  MSR_TYPE_RW, intercept);
 }
 
+static void vmx_set_intercept_for_fred_msr(struct kvm_vcpu *vcpu)
+{
+	bool intercept = !guest_cpu_cap_has(vcpu, X86_FEATURE_FRED);
+
+	if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+		return;
+
+	/*
+	 * Because the following eight FRED MSRs,
+	 * 	MSR_IA32_FRED_RSP[123], MSR_IA32_FRED_STKLVLS,
+	 * 	MSR_IA32_FRED_SSP[123], MSR_IA32_FRED_CONFIG,
+	 * are used by the kernel itself to take an exception at any time, they
+	 * should be context-switched by Intel VT-x automatically in order to
+	 * preserve the FRED architectural invariant that there should NEVER be
+	 * a "gap" during which it is unsafe to take an exception.
+	 *
+	 * KVM leverages Intel VT-x hardware to automatically context switch the
+	 * eight FRED MSRs using:
+	 *
+	 *   1) Dedicated host and guest VMCS fields for each MSR.
+	 *
+	 *   2) VM-entry/exit controls to manage the automated loading and saving
+	 *      of the eight FRED MSRs.
+	 *
+	 * Consequently, passing these MSRs through to the guest would only add
+	 * unnecessary handling code without benefit.
+	 */
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, intercept);
+
+	/*
+	 * MSR_IA32_FRED_RSP0 and MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) are
+	 * designed for event delivery while executing in userspace.  Since KVM
+	 * operates entirely in kernel mode (CPL is always 0 after any VM exit),
+	 * it can safely retain and operate with guest-defined values for these
+	 * MSRs.
+	 *
+	 * Disabling interception of the two MSRs offers two advantages:
+	 *   1) Simplicity: Eliminates dedicated MSR handling code.
+	 *   2) Performance: Avoids frequent VM-exits since the two MSRs are
+	 *      per user thread variables and frequently accessed.
+	 *
+	 * MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) is part of CET supervisor
+	 * state, but all four FRED SSP MSRs are architecturally visible on any
+	 * processor that enumerates FRED.  Even if CET is absent, these MSRs
+	 * remain accessible via RDMSR/WRMSR, though FRED transitions will not
+	 * use them.
+	 *
+	 * Intercept MSR_IA32_PL0_SSP if CET shadow stacks are unsupported (even
+	 * with FRED present).  Since this MSR is rarely accessed and ignored by
+	 * XSAVES in this configuration, interception avoids the overhead of
+	 * manually context switching the hardware MSR during vcpu_load/put.
+	 *
+	 * This behavior is consistent with the current setup in
+	 * vmx_recalc_msr_intercepts(), so no change is needed to the interception
+	 * logic for MSR_IA32_PL0_SSP.
+	 */
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, intercept);
+}
+
 static void vmx_recalc_msr_intercepts(struct kvm_vcpu *vcpu)
 {
 	bool intercept;
@@ -4371,6 +4437,7 @@ static void vmx_recalc_msr_intercepts(struct kvm_vcpu *vcpu)
 	}
 
 	vmx_recalc_pmu_msr_intercepts(vcpu);
+	vmx_set_intercept_for_fred_msr(vcpu);
 
 	/*
 	 * x2APIC and LBR MSR intercepts are modified on-demand and cannot be
Signature · 1 line
2.43.0
#31 lore raw

Re: [PATCH v10 08/28] KVM: VMX: Set FRED MSR intercepts

Quoted 15 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

On a userspace MSR filter change, set FRED MSR intercepts.

Because the following eight FRED MSRs,

        MSR_IA32_FRED_RSP[123], MSR_IA32_FRED_STKLVLS,
        MSR_IA32_FRED_SSP[123], MSR_IA32_FRED_CONFIG,

are used by the kernel itself to take an exception at any time, they should be context-switched by Intel VT-x automatically in order to preserve the FRED architectural invariant that there should NEVER be a "gap" during which it is unsafe to take an exception.

KVM leverages Intel VT-x hardware to automatically context switch the eight FRED MSRs using:

Quoted 6 lines

1) Dedicated host and guest VMCS fields for each MSR.

2) VM-entry/exit controls to manage the automated loading and saving of the eight FRED MSRs.

Consequently, passing these MSRs through to the guest would only add

                  ^

"passing" or "intercepting"?
The sentence says "... add unnecessary handling code without benefit"

Quoted 40 lines

unnecessary handling code without benefit.

Both MSR_IA32_FRED_RSP0 and MSR_IA32_FRED_SSP0 (aka MSR_IA32_PL0_SSP) are dedicated for userspace event delivery, IOW they are NOT used in any kernel event delivery and the execution of ERETS. Thus KVM can run safely with guest values in the two MSRs. As a result, save and restore of their guest values are deferred until vCPU context switch, Host MSR_IA32_FRED_RSP0 is restored upon returning to userspace, and Host MSR_IA32_PL0_SSP is managed with XRSTORS/XSAVES.

MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) is part of CET supervisor state, but all four FRED SSP MSRs are architecturally visible on any processor that enumerates FRED. Even if CET is absent, these MSRs remain accessible via RDMSR/WRMSR, though FRED transitions will not use them.

Intercept MSR_IA32_PL0_SSP if CET shadow stacks are unsupported (even with FRED present). Since this MSR is rarely accessed and ignored by XSAVES in this configuration, interception avoids the overhead of manually context switching the hardware MSR during vcpu_load/put.

This behavior is consistent with the current setup in vmx_recalc_msr_intercepts(), so no change is needed to the interception logic for MSR_IA32_PL0_SSP.

---
v10:
- Improve the commit message and code comment with an explanation from hpa (Chao Gao and Dave Hansen).

---
 arch/x86/kvm/vmx/vmx.c | 67 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
arch/x86/kvm/vmx/vmx.c +0 -0
index dc80ca5f804d..09bbbc680aa7 100644

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

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +1 -0
@@ -4304,6 +4304,72 @@ static void vmx_recalc_pmu_msr_intercepts(struct kvm_vcpu *vcpu)
 				  MSR_TYPE_RW, intercept);
 }
 
+static void vmx_set_intercept_for_fred_msr(struct kvm_vcpu *vcpu)

Nit:
Maybe follow the name of the function above, i.e. vmx_recalc_xxx_intercepts(). vmx_recalc_fred_msr_intercepts()?

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

Quoted 2 lines
arch/x86/kvm/vmx/vmx.c +2 -0
+{
+	bool intercept = !guest_cpu_cap_has(vcpu, X86_FEATURE_FRED);

This assignment could be moved after the check below.

Quoted 12 lines
arch/x86/kvm/vmx/vmx.c +12 -0
+
+	if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+		return;
+
+	/*
+	 * Because the following eight FRED MSRs,
+	 * 	MSR_IA32_FRED_RSP[123], MSR_IA32_FRED_STKLVLS,
+	 * 	MSR_IA32_FRED_SSP[123], MSR_IA32_FRED_CONFIG,
+	 * are used by the kernel itself to take an exception at any time, they
+	 * should be context-switched by Intel VT-x automatically in order to
+	 * preserve the FRED architectural invariant that there should NEVER be
+	 * a "gap" during which it is unsafe to take an exception.

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

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	 *
+	 * KVM leverages Intel VT-x hardware to automatically context switch the
+	 * eight FRED MSRs using:
+	 *
+	 *   1) Dedicated host and guest VMCS fields for each MSR.
+	 *
+	 *   2) VM-entry/exit controls to manage the automated loading and saving
+	 *      of the eight FRED MSRs.
+	 *
+	 * Consequently, passing these MSRs through to the guest would only add
                           ^

Ditto.> + * unnecessary handling code without benefit.

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

Quoted 1 line
arch/x86/kvm/vmx/vmx.c +1 -0
+	 */

I am not sure whether it needs to repeats the changelog almost the same description. But I see the version history mentions it was suggested by Dave and Chao?

Can this be just a summary instead?

Quoted 50 lines
arch/x86/kvm/vmx/vmx.c +40 -0
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP1, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP2, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP3, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_STKLVLS, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP1, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP2, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_SSP3, MSR_TYPE_RW, intercept);
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_CONFIG, MSR_TYPE_RW, intercept);
+
+	/*
+	 * MSR_IA32_FRED_RSP0 and MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) are
+	 * designed for event delivery while executing in userspace.  Since KVM
+	 * operates entirely in kernel mode (CPL is always 0 after any VM exit),
+	 * it can safely retain and operate with guest-defined values for these
+	 * MSRs.
+	 *
+	 * Disabling interception of the two MSRs offers two advantages:
+	 *   1) Simplicity: Eliminates dedicated MSR handling code.
+	 *   2) Performance: Avoids frequent VM-exits since the two MSRs are
+	 *      per user thread variables and frequently accessed.
+	 *
+	 * MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) is part of CET supervisor
+	 * state, but all four FRED SSP MSRs are architecturally visible on any
+	 * processor that enumerates FRED.  Even if CET is absent, these MSRs
+	 * remain accessible via RDMSR/WRMSR, though FRED transitions will not
+	 * use them.
+	 *
+	 * Intercept MSR_IA32_PL0_SSP if CET shadow stacks are unsupported (even
+	 * with FRED present).  Since this MSR is rarely accessed and ignored by
+	 * XSAVES in this configuration, interception avoids the overhead of
+	 * manually context switching the hardware MSR during vcpu_load/put.
+	 *
+	 * This behavior is consistent with the current setup in
+	 * vmx_recalc_msr_intercepts(), so no change is needed to the interception
+	 * logic for MSR_IA32_PL0_SSP.
+	 */
+	vmx_set_intercept_for_msr(vcpu, MSR_IA32_FRED_RSP0, MSR_TYPE_RW, intercept);
+}
+
 static void vmx_recalc_msr_intercepts(struct kvm_vcpu *vcpu)
 {
 	bool intercept;
@@ -4371,6 +4437,7 @@ static void vmx_recalc_msr_intercepts(struct kvm_vcpu *vcpu)
 	}
 
 	vmx_recalc_pmu_msr_intercepts(vcpu);
+	vmx_set_intercept_for_fred_msr(vcpu);
 
 	/*
 	 * x2APIC and LBR MSR intercepts are modified on-demand and cannot be
#32 lore raw

Re: [PATCH v10 08/28] KVM: VMX: Set FRED MSR intercepts

Quoted 3 lines · Binbin Wu
Quoted 1 line

Consequently, passing these MSRs through to the guest would only add

                  ^

"passing" or "intercepting"?

Yup, it's a typo. I had it on my list of fixes already :)

Quoted 6 lines
Quoted 1 line

+static void vmx_set_intercept_for_fred_msr(struct kvm_vcpu *vcpu)

Nit:
Maybe follow the name of the function above, i.e. vmx_recalc_xxx_intercepts(). vmx_recalc_fred_msr_intercepts()?

Sure, I'll change it to make it consistent.

Quoted 5 lines

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

Quoted 2 lines
arch/x86/kvm/vmx/vmx.c +2 -0
+{
+	bool intercept = !guest_cpu_cap_has(vcpu, X86_FEATURE_FRED);

This assignment could be moved after the check below.

The compiler should take care of it automatically, right? I think it's a style preference that saves a line. Other functions such as vmx_recalc_pmu_msr_intercepts() follow a similar pattern. I would prefer to leave this as-is unless you have a strong preference.

Quoted 23 lines
Quoted 12 lines
arch/x86/kvm/vmx/vmx.c +12 -0
+
+	if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+		return;
+
+	/*
+	 * Because the following eight FRED MSRs,
+	 * 	MSR_IA32_FRED_RSP[123], MSR_IA32_FRED_STKLVLS,
+	 * 	MSR_IA32_FRED_SSP[123], MSR_IA32_FRED_CONFIG,
+	 * are used by the kernel itself to take an exception at any time, they
+	 * should be context-switched by Intel VT-x automatically in order to
+	 * preserve the FRED architectural invariant that there should NEVER be
+	 * a "gap" during which it is unsafe to take an exception.

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

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	 *
+	 * KVM leverages Intel VT-x hardware to automatically context switch the
+	 * eight FRED MSRs using:
+	 *
+	 *   1) Dedicated host and guest VMCS fields for each MSR.
+	 *
+	 *   2) VM-entry/exit controls to manage the automated loading and saving
+	 *      of the eight FRED MSRs.
+	 *
+	 * Consequently, passing these MSRs through to the guest would only add
                           ^
Quoted 9 lines

Ditto.> + * unnecessary handling code without benefit.

Review

Quoted 1 line
(quoted diff) +1 -0
+	 */

I am not sure whether it needs to repeats the changelog almost the same description. But I see the version history mentions it was suggested by Dave and Chao?

Can this be just a summary instead?

I will try to shorten this one and the next paragraph a bit. But RSP0 treatment can be confusing to a first time reader so it makes sense to explain it in code as well. The next paragraph also has wording that makes more sense in the changelog ".. so no change is needed to the interception logic.. "

Quoted 27 lines
Quoted 27 lines
arch/x86/kvm/vmx/vmx.c +27 -0
+	/*
+	 * MSR_IA32_FRED_RSP0 and MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) are
+	 * designed for event delivery while executing in userspace.  Since KVM
+	 * operates entirely in kernel mode (CPL is always 0 after any VM exit),
+	 * it can safely retain and operate with guest-defined values for these
+	 * MSRs.
+	 *
+	 * Disabling interception of the two MSRs offers two advantages:
+	 *   1) Simplicity: Eliminates dedicated MSR handling code.
+	 *   2) Performance: Avoids frequent VM-exits since the two MSRs are
+	 *      per user thread variables and frequently accessed.
+	 *
+	 * MSR_IA32_PL0_SSP (aka MSR_IA32_FRED_SSP0) is part of CET supervisor
+	 * state, but all four FRED SSP MSRs are architecturally visible on any
+	 * processor that enumerates FRED.  Even if CET is absent, these MSRs
+	 * remain accessible via RDMSR/WRMSR, though FRED transitions will not
+	 * use them.
+	 *
+	 * Intercept MSR_IA32_PL0_SSP if CET shadow stacks are unsupported (even
+	 * with FRED present).  Since this MSR is rarely accessed and ignored by
+	 * XSAVES in this configuration, interception avoids the overhead of
+	 * manually context switching the hardware MSR during vcpu_load/put.
+	 *
+	 * This behavior is consistent with the current setup in
+	 * vmx_recalc_msr_intercepts(), so no change is needed to the interception
+	 * logic for MSR_IA32_PL0_SSP.
+	 */
#33 lore raw

PATCH v10 9/28 KVM: VMX: Save/restore guest FRED RSP0

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Save guest FRED RSP0 in vmx_prepare_switch_to_host() and restore it in vmx_prepare_switch_to_guest() because MSR_IA32_FRED_RSP0 is passed through to the guest, thus is volatile/unknown.

Note, host FRED RSP0 is restored in arch_exit_to_user_mode_prepare(), regardless of whether it is modified in KVM.

---
v10:
- No change

Note, an equivalent TDX side implementation is missing. No TDX module with FRED support exists yet so this would be an issue for future platforms. A generic discussion regarding this is ongoing at:
https://lore.kernel.org/kvm/[email protected]/

---
 arch/x86/kvm/vmx/vmx.c | 13 +++++++++++++
 arch/x86/kvm/vmx/vmx.h |  1 +
 2 files changed, 14 insertions(+)
arch/x86/kvm/vmx/vmx.c +13 -0
index 09bbbc680aa7..b6b73ab9cfb7 100644
@@ -1395,6 +1395,9 @@ void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
 	}
 
 	wrmsrq(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
+
+	if (guest_cpu_cap_has(vcpu, X86_FEATURE_FRED))
+		wrmsrns(MSR_IA32_FRED_RSP0, vmx->msr_guest_fred_rsp0);
 #else
 	savesegment(fs, fs_sel);
 	savesegment(gs, gs_sel);
@@ -1439,6 +1442,16 @@ static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
 	invalidate_tss_limit();
 #ifdef CONFIG_X86_64
 	wrmsrq(MSR_KERNEL_GS_BASE, vmx->vt.msr_host_kernel_gs_base);
+
+	if (guest_cpu_cap_has(&vmx->vcpu, X86_FEATURE_FRED)) {
+		vmx->msr_guest_fred_rsp0 = read_msr(MSR_IA32_FRED_RSP0);
+		/*
+		 * Synchronize the current value in hardware to the kernel's
+		 * local cache.  The desired host RSP0 will be set when the
+		 * CPU exits to userspace (RSP0 is a per-task value).
+		 */
+		fred_sync_rsp0(vmx->msr_guest_fred_rsp0);
+	}
 #endif
 	load_fixmap_gdt(raw_smp_processor_id());
 	vmx->vt.guest_state_loaded = false;
arch/x86/kvm/vmx/vmx.h +1 -0
index 7a22e1b1a273..14fd3f57d5c1 100644
@@ -222,6 +222,7 @@ struct vcpu_vmx {
 	bool                  guest_uret_msrs_loaded;
 #ifdef CONFIG_X86_64
 	u64		      msr_guest_kernel_gs_base;
+	u64		      msr_guest_fred_rsp0;
 #endif
 
 	u64		      spec_ctrl;
Signature · 1 line
2.43.0
#34 lore raw

Re: [PATCH v10 09/28] KVM: VMX: Save/restore guest FRED RSP0

Quoted 13 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Save guest FRED RSP0 in vmx_prepare_switch_to_host() and restore it in vmx_prepare_switch_to_guest() because MSR_IA32_FRED_RSP0 is passed through to the guest, thus is volatile/unknown.

Note, host FRED RSP0 is restored in arch_exit_to_user_mode_prepare(), regardless of whether it is modified in KVM.

Quoted 8 lines

---
v10:
- No change

Note, an equivalent TDX side implementation is missing. No TDX module with FRED support exists yet so this would be an issue for future platforms. A generic discussion regarding this is ongoing at:
https://lore.kernel.org/kvm/[email protected]/

For old KVM versions, we want to defer the opt-in design or backport decision.
(https://lore.kernel.org/kvm/[email protected]/)

We may finally choose to backport the TDX CPUID filtering patch series to stable kernels. If this patch series lands first, should we add FRED in the deny list for TDX as a temporary solution to avoid having some version(s) that allow FRED for TDX without FRED support in KVM?

#35 lore raw

Re: [PATCH v10 09/28] KVM: VMX: Save/restore guest FRED RSP0

Quoted 10 lines · Binbin Wu
Quoted 4 lines

Note, an equivalent TDX side implementation is missing. No TDX module with FRED support exists yet so this would be an issue for future platforms. A generic discussion regarding this is ongoing at:
https://lore.kernel.org/kvm/[email protected]/

For old KVM versions, we want to defer the opt-in design or backport decision. (
https://lore.kernel.org/kvm/[email protected]
m/)

Quoted 4 lines

We may finally choose to backport the TDX CPUID filtering patch series to stable kernels. If this patch series lands first, should we add FRED in the deny list for TDX as a temporary solution to avoid having some version(s) that allow FRED for TDX without FRED support in KVM?

The specific FRED problem starts with FRED host usage + TDX, so I don't think there is a reason to tie and temporary fixups to VMX FRED support, in any case. Or were you thinking to blame userspace for not respecting KVM_GET_SUPPORTED_CPUID, which would change after this series?

Since there are plenty of released kernels with FRED host support already, I'd think to wait until we settle the opt-in question. Which doesn't seem like it should be too much longer. It will be less thrash.

#36 lore raw

Re: [PATCH v10 09/28] KVM: VMX: Save/restore guest FRED RSP0

Quoted 16 lines · Rick P
Quoted 10 lines · Binbin Wu
Quoted 4 lines

Note, an equivalent TDX side implementation is missing. No TDX module with FRED support exists yet so this would be an issue for future platforms. A generic discussion regarding this is ongoing at:
https://lore.kernel.org/kvm/[email protected]/

For old KVM versions, we want to defer the opt-in design or backport decision. (
https://lore.kernel.org/kvm/[email protected]
m/)

Quoted 4 lines

We may finally choose to backport the TDX CPUID filtering patch series to stable kernels. If this patch series lands first, should we add FRED in the deny list for TDX as a temporary solution to avoid having some version(s) that allow FRED for TDX without FRED support in KVM?

Quoted 4 lines

The specific FRED problem starts with FRED host usage + TDX, so I don't think there is a reason to tie and temporary fixups to VMX FRED support, in any case. Or were you thinking to blame userspace for not respecting KVM_GET_SUPPORTED_CPUID, which would change after this series?

My concern is if there is a release x with this patch set, but the release is not a LTS/stable kernel branch. Then backporting of TDX CPUID filtering patch series will skip this release. When the TDX module with FRED support released and work with the kernel release, it will have problem.

Quoted 4 lines

Since there are plenty of released kernels with FRED host support already, I'd think to wait until we settle the opt-in question. Which doesn't seem like it should be too much longer. It will be less thrash.

OK

#37 lore raw

PATCH v10 10/28 KVM: VMX: Add support for saving and restoring FRED MSRs

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Introduce support for handling FRED MSR access requests, enabling both host and guest to read and write FRED MSRs, which is essential for VM save/restore and live migration, and allows userspace tools such as QEMU to access the relevant MSRs.

Specially, intercept accesses to the FRED SSP0 MSR (IA32_PL0_SSP), which remains accessible when FRED is enumerated even if CET is not. This ensures the guest value is fully virtual and does not alter the hardware FRED SSP0 MSR.

---
v10:
- Fix a corner case identified by Chao Gao.

---
 arch/x86/include/asm/kvm_host.h  |  5 ++
 arch/x86/include/asm/msr-index.h |  2 +
 arch/x86/kvm/msrs.c              | 89 ++++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/vmx.c           | 45 ++++++++++++++++
 4 files changed, 138 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +5 -0
index 8d3999772ac2..0fd5d4edeebb 100644
@@ -1032,6 +1032,11 @@ struct kvm_vcpu_arch {
 #if IS_ENABLED(CONFIG_HYPERV)
 	hpa_t hv_root_tdp;
 #endif
+	/*
+	 * Stores the FRED SSP0 MSR when CET is not supported, prompting KVM
+	 * to intercept its accesses.
+	 */
+	u64 fred_ssp0_fallback;
 };
 
 struct kvm_lpage_info {
arch/x86/include/asm/msr-index.h +2 -0
index ad899d9070e1..b386709515c4 100644
@@ -64,6 +64,8 @@
 #define MSR_IA32_FRED_SSP3	0x1d3			/* Level 3 shadow stack pointer */
 #define MSR_IA32_FRED_CONFIG	0x1d4			/* Entrypoint and interrupt stack level */
 
+#define FRED_CONFIG_RESERVED	(BIT_ULL(2) | GENMASK_ULL(5, 4) | BIT_ULL(11))
+
 /* Intel MSRs. Some also available on other CPUs */
 #define MSR_TEST_CTRL				0x00000033
 #define MSR_TEST_CTRL_SPLIT_LOCK_DETECT_BIT	29
arch/x86/kvm/msrs.c +86 -3

139 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.c +45 -0

69 lines not on this page · raw message

Signature · 1 line
2.43.0
#38 lore raw

Re: [PATCH v10 10/28] KVM: VMX: Add support for saving and restoring FRED MSRs

Quoted 9 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Introduce support for handling FRED MSR access requests, enabling both host and guest to read and write FRED MSRs, which is essential for VM save/restore and live migration, and allows userspace tools such as QEMU to access the relevant MSRs.

Specially, intercept accesses to the FRED SSP0 MSR (IA32_PL0_SSP), which remains accessible when FRED is enumerated even if CET is not.

Nit:
It sounds like the patch adds interception. But the patch emulates the access of the MSR.

Quoted 22 lines

This
ensures the guest value is fully virtual and does not alter the hardware FRED SSP0 MSR.

---
v10:
- Fix a corner case identified by Chao Gao.

---
 arch/x86/include/asm/kvm_host.h  |  5 ++
 arch/x86/include/asm/msr-index.h |  2 +
 arch/x86/kvm/msrs.c              | 89 ++++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/vmx.c           | 45 ++++++++++++++++
 4 files changed, 138 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +0 -0
index 8d3999772ac2..0fd5d4edeebb 100644

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch { · line 1036

Quoted 5 lines
arch/x86/include/asm/kvm_host.h +2 -0
@@ -1032,6 +1032,11 @@ struct kvm_vcpu_arch {
 #if IS_ENABLED(CONFIG_HYPERV)
 	hpa_t hv_root_tdp;
 #endif
+	/*
+	 * Stores the FRED SSP0 MSR when CET is not supported, prompting KVM

Nit:
CET could be more specific, i.e. SHSTK. I am not sure if there is a situation that one is supported, but the other is not.

"prompting KVM to intercept its accesses" is confusing to me.

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +3 -0
+	 * to intercept its accesses.
+	 */
+	u64 fred_ssp0_fallback;
 };

[...]

#39 lore raw

Re: [PATCH v10 10/28] KVM: VMX: Add support for saving and restoring FRED MSRs

Quoted 8 lines
Quoted 3 lines

Specially, intercept accesses to the FRED SSP0 MSR (IA32_PL0_SSP), which remains accessible when FRED is enumerated even if CET is not.

Nit:
It sounds like the patch adds interception. But the patch emulates the access of the MSR.

Yes, will change the wording to reflect that only the emulation of the access is being added.

Quoted 4 lines
Quoted 4 lines

This
ensures the guest value is fully virtual and does not alter the hardware FRED SSP0 MSR.

...

Quoted 5 lines
Quoted 5 lines
arch/x86/include/asm/kvm_host.h +0 -0
index 8d3999772ac2..0fd5d4edeebb 100644
@@ -1032,6 +1032,11 @@ struct kvm_vcpu_arch {
Quoted 9 lines

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch { · line 1036

Quoted 5 lines
arch/x86/include/asm/kvm_host.h +2 -0
 #if IS_ENABLED(CONFIG_HYPERV)
 	hpa_t hv_root_tdp;
 #endif
+	/*
+	 * Stores the FRED SSP0 MSR when CET is not supported, prompting KVM

Nit:
CET could be more specific, i.e. SHSTK. I am not sure if there is a situation that one is supported, but the other is not.

Agreed SHSTK is more precise that CET. I think KVM can clear SHSTK but keep IBT in some situations.

Quoted 1 line

"prompting KVM to intercept its accesses" is confusing to me.

I believe it meant to say that fred_ssp0_fallback stores the SSP0 MSR value and the intercepted accesses are emulated using this field. I'll reword it to be less ambiguous.

Quoted 6 lines
Quoted 4 lines
arch/x86/include/asm/kvm_host.h +3 -0
+	 * to intercept its accesses.
+	 */
+	u64 fred_ssp0_fallback;
 };

[...]

#40 lore raw

PATCH v10 11/28 KVM: x86: Add a helper to detect if FRED is enabled for a vCPU

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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

[ Sean: removed the "kvm_" prefix from the function name ]

---
v10:
- Add back the change log (Binbin Wu and Sean).

---
 arch/x86/kvm/regs.h | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
arch/x86/kvm/regs.h +15 -0
index 447f0ec3e63e..4e641a6c20f9 100644
@@ -364,6 +364,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_REG_CR3))
Signature · 1 line
2.43.0
#41 lore raw

Re: [PATCH v10 11/28] KVM: x86: Add a helper to detect if FRED is enabled for a vCPU

Quoted 23 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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

[ Sean: removed the "kvm_" prefix from the function name ]

---
v10:
- Add back the change log (Binbin Wu and Sean).

---
 arch/x86/kvm/regs.h | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
arch/x86/kvm/regs.h +0 -0
index 447f0ec3e63e..4e641a6c20f9 100644

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

Quoted 8 lines
arch/x86/kvm/regs.h +5 -0
@@ -364,6 +364,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.

It seems KVM doesn't enforce it in kvm_set_cr0() for 2).

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

Quoted 4 lines
arch/x86/kvm/regs.h +4 -0
+ */
+static inline bool is_fred_enabled(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_X86_64

Nit:
This seems to be unnecessary.
X86_CR4_FRED is defined as 0 in non 64-bit build.

Quoted 9 lines
arch/x86/kvm/regs.h +6 -0
+	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_REG_CR3))
#42 lore raw

Re: [PATCH v10 11/28] KVM: x86: Add a helper to detect if FRED is enabled for a vCPU

Quoted 9 lines · Binbin Wu
Quoted 5 lines · Sohil Mehta

+/*
+ * 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.

It seems KVM doesn't enforce it in kvm_set_cr0() for 2).

I think the comment is slightly misleading. The spec doesn't directly enforce leaving IA-32e mode with CR4.FRED. It is just expected to be unreachable.

1) Based on FRED spec section 4.2 Enabling in CR4, setting CR4.FRED prevents compatibility mode entry while CPL = 0.

2) But leaving IA-32e can only happen when CR0.PG is cleared which can only be done in compatibility mode while CPL = 0.

Currently, for KVM, the CPU enforces the first one and the second one is enforced by kvm_set_cr0().

Is the suggestion to add an explicit check in kvm_set_cr0() that mirrors the PCIDE one? But there isn't a fault specified by the spec for this case.

Sean also requested negative tests for things like leaving 64-bit mode with FRED=1. But, I am not sure how to test this.

AI tells me such a mode change can happen with emulated far transfer through an MMIO far pointer. "em_jmp_far(), em_call_far(), em_ret_far() and __load_segment_descriptor() have no FRED checks, so none of them raise the #GP that FRED spec 8.2 requires."

Chao had brought up enhancing emulator code and making it FRED aware [1]. I am wondering if we should revisit it?

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

Please let me know if I misunderstood something.

Quoted 9 lines

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

Quoted 4 lines

+ */

arch/x86/kvm/regs.h +3 -0
+static inline bool is_fred_enabled(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_X86_64

Nit:
This seems to be unnecessary.
X86_CR4_FRED is defined as 0 in non 64-bit build.

Unfortunately, that 0 is exactly why it's needed. kvm_is_cr4_bit_set() has

	BUILD_BUG_ON(!is_power_of_2(cr4_bit));

So, compilation fails on i386 :(

Though, it would be better to get rid of the #ifdef and change it to:

return IS_ENABLED(CONFIG_X86_64) && kvm_is_cr4_bit_set(vcpu,
X86_CR4_FRED);

Quoted 6 lines
Quoted 6 lines
arch/x86/kvm/regs.h +6 -0
+	return kvm_is_cr4_bit_set(vcpu, X86_CR4_FRED);
+#else
+	return false;
+#endif
+}
+
#43 lore raw

Re: [PATCH v10 11/28] KVM: x86: Add a helper to detect if FRED is enabled for a vCPU

Quoted 15 lines · Sohil Mehta
Quoted 9 lines · Binbin Wu
Quoted 5 lines · Sohil Mehta

+/*
+ * 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.

It seems KVM doesn't enforce it in kvm_set_cr0() for 2).

I think the comment is slightly misleading. The spec doesn't directly enforce leaving IA-32e mode with CR4.FRED. It is just expected to be unreachable.

Quoted 6 lines

1) Based on FRED spec section 4.2 Enabling in CR4, setting CR4.FRED prevents compatibility mode entry while CPL = 0.

2) But leaving IA-32e can only happen when CR0.PG is cleared which can only be done in compatibility mode while CPL = 0.

Right, on bare metal, if CR4.FRED = 1, it is impossible to enter compatibility mode while CPL = 0.

Quoted 6 lines

Currently, for KVM, the CPU enforces the first one and the second one is enforced by kvm_set_cr0().

Is the suggestion to add an explicit check in kvm_set_cr0() that mirrors the PCIDE one? But there isn't a fault specified by the spec for this case.

Had a second thought. As you mentioned below, if em_{jmp,call,ret}_far() is triggered and CS.L is cleared on ring 0, even KVM doesn't check FRED status on far transitions, the next VM entry would fail. So I think it's not needed to mirror the PCIDE for FRED in kvm_set_cr0().

Quoted 3 lines

Sean also requested negative tests for things like leaving 64-bit mode with FRED=1. But, I am not sure how to test this.

Maybe it can use KVM_FEP to force the instruction emulation in kvm sefltest when force_emulation_prefix for KVM.

Quoted 8 lines

AI tells me such a mode change can happen with emulated far transfer through an MMIO far pointer. "em_jmp_far(), em_call_far(), em_ret_far() and __load_segment_descriptor() have no FRED checks, so none of them raise the #GP that FRED spec 8.2 requires."

Chao had brought up enhancing emulator code and making it FRED aware [1]. I am wondering if we should revisit it?

Without the check the next VM-entry fails the guest-state check according to FRED spec 11.5.2.3 ("If the DPL value in the SS attributes field is 0, the L bit in the CS attributes field (bit 13) must be 1") VS. With the check, raise #GP instead.

Not sure about the maintainers' preference. But a check on FRED in __load_segment_descriptor() looks simple though.

Quoted 4 lines

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

Please let me know if I misunderstood something.

#44 lore raw

Re: [PATCH v10 11/28] KVM: x86: Add a helper to detect if FRED is enabled for a vCPU

Quoted 9 lines · Binbin Wu
Quoted 3 lines

Is the suggestion to add an explicit check in kvm_set_cr0() that mirrors the PCIDE one? But there isn't a fault specified by the spec for this case.

Had a second thought. As you mentioned below, if em_{jmp,call,ret}_far() is triggered and CS.L is cleared on ring 0, even KVM doesn't check FRED status on far transitions, the next VM entry would fail. So I think it's not needed to mirror the PCIDE for FRED in kvm_set_cr0().

Yes, agreed. I'll avoid the check in kvm_set_cr0().

Quoted 7 lines
Quoted 3 lines

Sean also requested negative tests for things like leaving 64-bit mode with FRED=1. But, I am not sure how to test this.

Maybe it can use KVM_FEP to force the instruction emulation in kvm sefltest when force_emulation_prefix for KVM.

Okay. I'll add a FEP test that validates the emulator's far jmp/call/ret behavior.

Quoted 9 lines
Quoted 8 lines

AI tells me such a mode change can happen with emulated far transfer through an MMIO far pointer. "em_jmp_far(), em_call_far(), em_ret_far() and __load_segment_descriptor() have no FRED checks, so none of them raise the #GP that FRED spec 8.2 requires."

Chao had brought up enhancing emulator code and making it FRED aware [1]. I am wondering if we should revisit it?

Quoted 8 lines

Without the check the next VM-entry fails the guest-state check according to FRED spec 11.5.2.3 ("If the DPL value in the SS attributes field is 0, the L bit in the CS attributes field (bit 13) must be 1") VS. With the check, raise #GP instead.

Not sure about the maintainers' preference. But a check on FRED in __load_segment_descriptor() looks simple though.

I am inclined to add the check as well. So, I'll include it unless someone says otherwise (or it gets complicated during implementation).

#45 lore raw

PATCH v10 12/28 KVM: x86: Add a new save/restore flag for FRED metadata

In reply to Sohil Mehta

From: Xin Li <[email protected]>

Introduce a new save/restore flag for FRED metadata (specifically, the event nested flag and data) being saved and restored during VM save/ restore and live migration.

---
v10:
- Advertise KVM_CAP_X86_FRED_EVENT only when KVM can virtualize FRED, and return -EINVAL from KVM_ENABLE_CAP otherwise.
- Document the new return value in api.rst.

---
 Documentation/virt/kvm/api.rst  | 22 ++++++++++++++++++++++
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/include/uapi/asm/kvm.h |  1 +
 arch/x86/kvm/x86.c              | 18 ++++++++++++++++++
 include/uapi/linux/kvm.h        |  1 +
 5 files changed, 43 insertions(+)
Documentation/virt/kvm/api.rst +22 -0
index 4eb7e75a7473..22ef94f3eb3a 100644
@@ -1199,6 +1199,10 @@ The following bits are defined in the flags field:
   triple_fault_pending field contains a valid state. This bit will
   be set whenever KVM_CAP_X86_TRIPLE_FAULT_EVENT is enabled.
 
+- KVM_VCPUEVENT_VALID_FRED_STATE may be set to inform that the exception
+  state includes FRED state (specifically, the event nested flag and data).
+  This bit will be set whenever KVM_CAP_X86_FRED_EVENT is enabled.
+
 ARM64:
 ^^^^^^
 
@@ -1301,6 +1305,11 @@ If KVM_CAP_X86_TRIPLE_FAULT_EVENT is enabled, KVM_VCPUEVENT_VALID_TRIPLE_FAULT
 can be set in flags field to signal that the triple_fault field contains
 a valid state and shall be written into the VCPU.
 
+If KVM_CAP_X86_FRED_EVENT is enabled, KVM_VCPUEVENT_VALID_FRED_STATE can be set
+in the flags field to inform that the exception state contains FRED state
+(specifically, the event nested flag and data), which shall be written into the
+VCPU.
+
 ARM64:
 ^^^^^^
 
@@ -8979,6 +8988,19 @@ enabled, cmma can't be enabled anymore and pfmfi and the storage key
 interpretation are disabled. If cmma has already been enabled or the
 hpage_2g module parameter is not set to 1, -EINVAL is returned.
 
+7.48 KVM_CAP_X86_FRED_EVENT
+---------------------------
+
+:Architectures: x86
+:Parameters: args[0] whether feature should be enabled or not
+:Returns: 0 on success; -EINVAL if KVM cannot virtualize FRED.
+
+With this capability enabled, KVM allows exception save and restore operations
+to include FRED event context (specifically, the event nested flag and data).
+When injecting a FRED exception during VM entry, FRED event delivery relies
+on this information to select the correct event stack level and apply proper
+event data.
+
 8. Other capabilities.
 ======================
 
arch/x86/include/asm/kvm_host.h +1 -0
index 0fd5d4edeebb..dd68db17fdae 100644
@@ -1286,6 +1286,7 @@ struct kvm_arch {
 	bool has_mapped_host_mmio;
 	bool guest_can_read_msr_platform_info;
 	bool exception_payload_enabled;
+	bool exception_fred_state_enabled;
 
 	bool triple_fault_event;
 
arch/x86/include/uapi/asm/kvm.h +1 -0
index 1585ec804066..6a67832c59bb 100644
@@ -331,6 +331,7 @@ struct kvm_reinject_control {
 #define KVM_VCPUEVENT_VALID_SMM		0x00000008
 #define KVM_VCPUEVENT_VALID_PAYLOAD	0x00000010
 #define KVM_VCPUEVENT_VALID_TRIPLE_FAULT	0x00000020
+#define KVM_VCPUEVENT_VALID_FRED_STATE	0x00000040
 
 /* Interrupt shadow states */
 #define KVM_X86_SHADOW_INT_MOV_SS	0x01
arch/x86/kvm/x86.c +18 -0
index 4b3681796c75..01198aba27cf 100644
@@ -2288,6 +2288,9 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 	case KVM_CAP_PRE_FAULT_MEMORY:
 		r = tdp_enabled;
 		break;
+	case KVM_CAP_X86_FRED_EVENT:
+		r = kvm_cpu_cap_has(X86_FEATURE_FRED);
+		break;
 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
 		r = kvm ? kvm->arch.apic_bus_cycle_ns : APIC_BUS_CYCLE_NS_DEFAULT;
 		break;
@@ -3022,6 +3025,8 @@ static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
 			 | KVM_VCPUEVENT_VALID_SMM);
 	if (vcpu->kvm->arch.exception_payload_enabled)
 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
+	if (vcpu->kvm->arch.exception_fred_state_enabled)
+		events->flags |= KVM_VCPUEVENT_VALID_FRED_STATE;
 	if (vcpu->kvm->arch.triple_fault_event) {
 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
@@ -3036,6 +3041,7 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 			      | KVM_VCPUEVENT_VALID_SHADOW
 			      | KVM_VCPUEVENT_VALID_SMM
 			      | KVM_VCPUEVENT_VALID_PAYLOAD
+			      | KVM_VCPUEVENT_VALID_FRED_STATE
 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
 		return -EINVAL;
 
@@ -3051,6 +3057,11 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 		events->exception_has_payload = 0;
 	}
 
+	if (events->flags & KVM_VCPUEVENT_VALID_FRED_STATE) {
+		if (!vcpu->kvm->arch.exception_fred_state_enabled)
+			return -EINVAL;
+	}
+
 	if ((events->exception.injected || events->exception.pending) &&
 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
 		return -EINVAL;
@@ -4038,6 +4049,13 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
 		kvm->arch.exception_payload_enabled = cap->args[0];
 		r = 0;
 		break;
+	case KVM_CAP_X86_FRED_EVENT:
+		r = -EINVAL;
+		if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+			break;
+		kvm->arch.exception_fred_state_enabled = cap->args[0];
+		r = 0;
+		break;
 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
 		kvm->arch.triple_fault_event = cap->args[0];
 		r = 0;
include/uapi/linux/kvm.h +1 -0
index 9fc8dfdfd65f..c5ffc4e7ddb1 100644
@@ -998,6 +998,7 @@ struct kvm_enable_cap {
 #define KVM_CAP_S390_VSIE_ESAMODE 248
 #define KVM_CAP_S390_HPAGE_2G 249
 #define KVM_CAP_ARM_PMU_V3_STRICT 250
+#define KVM_CAP_X86_FRED_EVENT 251
 
 struct kvm_irq_routing_irqchip {
 	__u32 irqchip;
Signature · 1 line
2.43.0
#46 lore raw

Re: [PATCH v10 12/28] KVM: x86: Add a new save/restore flag for FRED metadata

Quoted 5 lines · Sohil Mehta

From: Xin Li <[email protected]>

Introduce a new save/restore flag for FRED metadata (specifically, the event nested flag and data) being saved and restored during VM save/ restore and live migration.

Nit:
Would it be more natural to move this patch after patches 13 and 14? The commit message and the document reference changes introduced in later patches.

Quoted 156 lines

---
v10:
- Advertise KVM_CAP_X86_FRED_EVENT only when KVM can virtualize FRED, and return -EINVAL from KVM_ENABLE_CAP otherwise.
- Document the new return value in api.rst.

---
 Documentation/virt/kvm/api.rst  | 22 ++++++++++++++++++++++
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/include/uapi/asm/kvm.h |  1 +
 arch/x86/kvm/x86.c              | 18 ++++++++++++++++++
 include/uapi/linux/kvm.h        |  1 +
 5 files changed, 43 insertions(+)
Documentation/virt/kvm/api.rst +22 -0
index 4eb7e75a7473..22ef94f3eb3a 100644
@@ -1199,6 +1199,10 @@ The following bits are defined in the flags field:
   triple_fault_pending field contains a valid state. This bit will
   be set whenever KVM_CAP_X86_TRIPLE_FAULT_EVENT is enabled.
 
+- KVM_VCPUEVENT_VALID_FRED_STATE may be set to inform that the exception
+  state includes FRED state (specifically, the event nested flag and data).
+  This bit will be set whenever KVM_CAP_X86_FRED_EVENT is enabled.
+
 ARM64:
 ^^^^^^
 
@@ -1301,6 +1305,11 @@ If KVM_CAP_X86_TRIPLE_FAULT_EVENT is enabled, KVM_VCPUEVENT_VALID_TRIPLE_FAULT
 can be set in flags field to signal that the triple_fault field contains
 a valid state and shall be written into the VCPU.
 
+If KVM_CAP_X86_FRED_EVENT is enabled, KVM_VCPUEVENT_VALID_FRED_STATE can be set
+in the flags field to inform that the exception state contains FRED state
+(specifically, the event nested flag and data), which shall be written into the
+VCPU.
+
 ARM64:
 ^^^^^^
 
@@ -8979,6 +8988,19 @@ enabled, cmma can't be enabled anymore and pfmfi and the storage key
 interpretation are disabled. If cmma has already been enabled or the
 hpage_2g module parameter is not set to 1, -EINVAL is returned.
 
+7.48 KVM_CAP_X86_FRED_EVENT
+---------------------------
+
+:Architectures: x86
+:Parameters: args[0] whether feature should be enabled or not
+:Returns: 0 on success; -EINVAL if KVM cannot virtualize FRED.
+
+With this capability enabled, KVM allows exception save and restore operations
+to include FRED event context (specifically, the event nested flag and data).
+When injecting a FRED exception during VM entry, FRED event delivery relies
+on this information to select the correct event stack level and apply proper
+event data.
+
 8. Other capabilities.
 ======================
 
arch/x86/include/asm/kvm_host.h +1 -0
index 0fd5d4edeebb..dd68db17fdae 100644
@@ -1286,6 +1286,7 @@ struct kvm_arch {
 	bool has_mapped_host_mmio;
 	bool guest_can_read_msr_platform_info;
 	bool exception_payload_enabled;
+	bool exception_fred_state_enabled;
 
 	bool triple_fault_event;
 
arch/x86/include/uapi/asm/kvm.h +1 -0
index 1585ec804066..6a67832c59bb 100644
@@ -331,6 +331,7 @@ struct kvm_reinject_control {
 #define KVM_VCPUEVENT_VALID_SMM		0x00000008
 #define KVM_VCPUEVENT_VALID_PAYLOAD	0x00000010
 #define KVM_VCPUEVENT_VALID_TRIPLE_FAULT	0x00000020
+#define KVM_VCPUEVENT_VALID_FRED_STATE	0x00000040
 
 /* Interrupt shadow states */
 #define KVM_X86_SHADOW_INT_MOV_SS	0x01
arch/x86/kvm/x86.c +18 -0
index 4b3681796c75..01198aba27cf 100644
@@ -2288,6 +2288,9 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
 	case KVM_CAP_PRE_FAULT_MEMORY:
 		r = tdp_enabled;
 		break;
+	case KVM_CAP_X86_FRED_EVENT:
+		r = kvm_cpu_cap_has(X86_FEATURE_FRED);
+		break;
 	case KVM_CAP_X86_APIC_BUS_CYCLES_NS:
 		r = kvm ? kvm->arch.apic_bus_cycle_ns : APIC_BUS_CYCLE_NS_DEFAULT;
 		break;
@@ -3022,6 +3025,8 @@ static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
 			 | KVM_VCPUEVENT_VALID_SMM);
 	if (vcpu->kvm->arch.exception_payload_enabled)
 		events->flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
+	if (vcpu->kvm->arch.exception_fred_state_enabled)
+		events->flags |= KVM_VCPUEVENT_VALID_FRED_STATE;
 	if (vcpu->kvm->arch.triple_fault_event) {
 		events->triple_fault.pending = kvm_test_request(KVM_REQ_TRIPLE_FAULT, vcpu);
 		events->flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
@@ -3036,6 +3041,7 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 			      | KVM_VCPUEVENT_VALID_SHADOW
 			      | KVM_VCPUEVENT_VALID_SMM
 			      | KVM_VCPUEVENT_VALID_PAYLOAD
+			      | KVM_VCPUEVENT_VALID_FRED_STATE
 			      | KVM_VCPUEVENT_VALID_TRIPLE_FAULT))
 		return -EINVAL;
 
@@ -3051,6 +3057,11 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 		events->exception_has_payload = 0;
 	}
 
+	if (events->flags & KVM_VCPUEVENT_VALID_FRED_STATE) {
+		if (!vcpu->kvm->arch.exception_fred_state_enabled)
+			return -EINVAL;
+	}
+
 	if ((events->exception.injected || events->exception.pending) &&
 	    (events->exception.nr > 31 || events->exception.nr == NMI_VECTOR))
 		return -EINVAL;
@@ -4038,6 +4049,13 @@ int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
 		kvm->arch.exception_payload_enabled = cap->args[0];
 		r = 0;
 		break;
+	case KVM_CAP_X86_FRED_EVENT:
+		r = -EINVAL;
+		if (!kvm_cpu_cap_has(X86_FEATURE_FRED))
+			break;
+		kvm->arch.exception_fred_state_enabled = cap->args[0];
+		r = 0;
+		break;
 	case KVM_CAP_X86_TRIPLE_FAULT_EVENT:
 		kvm->arch.triple_fault_event = cap->args[0];
 		r = 0;
include/uapi/linux/kvm.h +1 -0
index 9fc8dfdfd65f..c5ffc4e7ddb1 100644
@@ -998,6 +998,7 @@ struct kvm_enable_cap {
 #define KVM_CAP_S390_VSIE_ESAMODE 248
 #define KVM_CAP_S390_HPAGE_2G 249
 #define KVM_CAP_ARM_PMU_V3_STRICT 250
+#define KVM_CAP_X86_FRED_EVENT 251
 
 struct kvm_irq_routing_irqchip {
 	__u32 irqchip;
#47 lore raw

Re: [PATCH v10 12/28] KVM: x86: Add a new save/restore flag for FRED metadata

Quoted 12 lines · Binbin Wu
Quoted 5 lines · Sohil Mehta

From: Xin Li <[email protected]>

Introduce a new save/restore flag for FRED metadata (specifically, the event nested flag and data) being saved and restored during VM save/ restore and live migration.

Nit:
Would it be more natural to move this patch after patches 13 and 14? The commit message and the document reference changes introduced in later patches.

It is arguable. I think Xin's idea was to introduce the interface first and then provide the implementation. Chang also had some suggestions on the structure of the series. I'll reevaluate the ordering once I am through all the feedback.

Thanks!

#48 lore raw

PATCH v10 13/28 KVM: VMX: Virtualize FRED nested exception tracking

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Set the VMX nested exception bit in VM-entry interruption information field when injecting a nested exception using FRED event delivery to ensure:
1) A 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 an earlier 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 the stack pointed by IA32_FRED_RSP1 MSR when encountered in ring 3 and ring 0.
- normal #PF will be delivered on the stack pointed by IA32_FRED_RSP0 MSR when encountered in ring 3.

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

In addition, save/restore the nested flag of an exception during VM save/restore and live migration to ensure a correct event stack level is chosen when a nested exception is injected through FRED event delivery across VM save/restore and live migration.

Note, like the other fields of struct kvm_queued_exception, the nested flag is meaningful only while the exception is pending or injected. It is not consulted otherwise, and so doesn't need to be cleared when an exception is dropped.

[ Sean: reworked kvm_requeue_exception() to simply the code changes ]

---
v10:
- Rename exception status member variable nested to is_nested (Sean).
- Rename KVM_CAP_EXCEPTION_NESTED_FLAG to KVM_CAP_X86_FRED_EVENT, to include both FRED event nested flag and data.
- Track the nested flag of an exception being queued in a local variable (so that a flag left over from a no-longer-live exception can't be folded into a new one).

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/include/asm/vmx.h      |  5 ++++-
 arch/x86/include/uapi/asm/kvm.h |  3 ++-
 arch/x86/kvm/svm/svm.c          |  2 +-
 arch/x86/kvm/vmx/vmx.c          | 10 ++++++++--
 arch/x86/kvm/x86.c              | 18 +++++++++++++++++-
 arch/x86/kvm/x86.h              |  4 +++-
 7 files changed, 36 insertions(+), 7 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -0
index dd68db17fdae..994c354dc47b 100644
@@ -695,6 +695,7 @@ struct kvm_queued_exception {
 	u32 error_code;
 	unsigned long payload;
 	bool has_payload;
+	bool is_nested;
 };
 
 /*
arch/x86/include/asm/vmx.h +4 -1
index 4720619f09ac..7eb08f84a7e5 100644
@@ -152,6 +152,7 @@ struct vmcs {
 #define VMX_BASIC_INOUT				BIT_ULL(54)
 #define VMX_BASIC_TRUE_CTLS			BIT_ULL(55)
 #define VMX_BASIC_NO_HW_ERROR_CODE_CC		BIT_ULL(56)
+#define VMX_BASIC_NESTED_EXCEPTION		BIT_ULL(58)
 #define VMX_BASIC_NO_SEAMRET_INVD_VMCS		BIT_ULL(60)
 
 static inline u32 vmx_basic_vmcs_revision_id(u64 vmx_basic)
@@ -451,13 +452,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/include/uapi/asm/kvm.h +2 -1
index 6a67832c59bb..659c8391d40e 100644
@@ -369,7 +369,8 @@ struct kvm_vcpu_events {
 	struct {
 		__u8 pending;
 	} triple_fault;
-	__u8 reserved[26];
+	__u8 reserved[25];
+	__u8 exception_is_nested;
 	__u8 exception_has_payload;
 	__u64 exception_payload;
 };
arch/x86/kvm/svm/svm.c +1 -1
index ea647938a2a6..7762db655b28 100644
@@ -4392,7 +4392,7 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 
 		kvm_requeue_exception(vcpu, vector,
 				      exitintinfo & SVM_EXITINTINFO_VALID_ERR,
-				      error_code);
+				      error_code, false);
 		break;
 	}
 	case SVM_EXITINTINFO_TYPE_INTR:
arch/x86/kvm/vmx/vmx.c +8 -2
index 362bd4dda298..25c3301e137b 100644
@@ -2008,8 +2008,13 @@ 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 (is_fred_enabled(vcpu)) {
+			if (ex->is_nested)
+				intr_info |= INTR_INFO_NESTED_EXCEPTION_MASK;
+		}
+	}
 
 	vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
 
@@ -7501,7 +7506,8 @@ static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
 
 		kvm_requeue_exception(vcpu, vector,
 				      idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK,
-				      error_code);
+				      error_code,
+				      idt_vectoring_info & VECTORING_INFO_NESTED_EXCEPTION_MASK);
 		break;
 	}
 	case INTR_TYPE_SOFT_INTR:
arch/x86/kvm/x86.c +17 -1
index 01198aba27cf..94d684210cf6 100644
@@ -461,6 +461,7 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 				   bool has_error, u32 error_code,
 				   bool has_payload, unsigned long payload)
 {
+	bool is_nested = false;
 	u32 prev_nr;
 	int class1, class2;
 
@@ -487,6 +488,11 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 		vcpu->arch.exception.error_code = error_code;
 		vcpu->arch.exception.has_payload = has_payload;
 		vcpu->arch.exception.payload = payload;
+		/* #DF is NOT a nested event, per its definition. */
+		vcpu->arch.exception.is_nested = (nr != DF_VECTOR) &&
+						 (is_nested ||
+						  vcpu->arch.nmi_injected ||
+						  vcpu->arch.interrupt.injected);
 		return;
 	}
 
@@ -510,6 +516,9 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 
 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
 	} else {
+		/* The new exception arrived while delivering the previous one. */
+		is_nested = true;
+
 		/* replace previous exception with a new one in a hope
 		   that instruction re-execution will regenerate lost
 		   exception */
@@ -538,7 +547,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)
+			   bool has_error_code, u32 error_code,
+			   bool is_nested)
 {
 
 	/*
@@ -563,6 +573,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.is_nested = is_nested;
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
 
@@ -3000,6 +3011,7 @@ static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
 	events->exception.error_code = ex->error_code;
 	events->exception_has_payload = ex->has_payload;
 	events->exception_payload = ex->payload;
+	events->exception_is_nested = ex->is_nested;
 
 	events->interrupt.injected =
 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
@@ -3060,6 +3072,8 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 	if (events->flags & KVM_VCPUEVENT_VALID_FRED_STATE) {
 		if (!vcpu->kvm->arch.exception_fred_state_enabled)
 			return -EINVAL;
+	} else {
+		events->exception_is_nested = 0;
 	}
 
 	if ((events->exception.injected || events->exception.pending) &&
@@ -3087,6 +3101,7 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 	vcpu->arch.exception.error_code = events->exception.error_code;
 	vcpu->arch.exception.has_payload = events->exception_has_payload;
 	vcpu->arch.exception.payload = events->exception_payload;
+	vcpu->arch.exception.is_nested = events->exception_is_nested;
 
 	vcpu->arch.interrupt.injected = events->interrupt.injected;
 	vcpu->arch.interrupt.nr = events->interrupt.nr;
@@ -8978,6 +8993,7 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 					   ex->has_payload, ex->payload);
 		ex->injected = false;
 		ex->pending = false;
+		ex->is_nested = false;
 	}
 	vcpu->arch.exception_from_userspace = false;
 
arch/x86/kvm/x86.h +3 -1
index 0f5919b092e4..2d6bae66cfae 100644
@@ -158,6 +158,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.is_nested = false;
 	vcpu->arch.exception_vmexit.pending = false;
 }
 
@@ -502,7 +503,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);
+			   bool has_error_code, u32 error_code,
+			   bool is_nested);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault,
 			   bool from_hardware);
 void __kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
Signature · 1 line
2.43.0
#49 lore raw

Re: [PATCH v10 13/28] KVM: VMX: Virtualize FRED nested exception tracking

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] KVM incorrectly flags an exception as nested when it replaces an un-injected, merely pending…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] KVM incorrectly flags an exception as nested when it replaces an un-injected, merely pending exception. --

commit a3ba5314358330c25b6d179842584793ca6f0e34
Author: Xin Li (Intel) <[email protected]>

KVM: VMX: Virtualize FRED nested exception tracking

This commit adds virtualization support for FRED nested exception tracking in KVM by setting the VMX nested exception bit in the VM-entry interruption information field. It also updates exception queueing to track and save the nested flag across VM migrations.

Quoted 4 lines
arch/x86/kvm/x86.c +0 -0
index 01198aba27cf0..94d684210cf6c 100644

[ ... ]

arch/x86/kvm/x86.c static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr, · line 521

Quoted 7 lines
arch/x86/kvm/x86.c +3 -0
@@ -510,6 +516,9 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 
 		kvm_queue_exception_e(vcpu, DF_VECTOR, 0);
 	} else {
+		/* The new exception arrived while delivering the previous one. */
+		is_nested = true;
+

[Severity: High]
Is it correct to unconditionally set is_nested = true here even if the previous exception was only pending and not yet injected?

If KVM queues an exception in software (vcpu->arch.exception.pending = true, injected = false) and a second exception is queued before the next VM-entry (e.g., a #PF during subsequent KVM request processing or emulation), this path replaces the purely pending exception with the new one.

Since an exception that hasn't commenced hardware delivery cannot cause a nested exception, setting is_nested = true here will inject the new exception with INTR_INFO_NESTED_EXCEPTION_MASK. Could this violate the FRED architecture specification by causing the guest hardware to incorrectly interpret the event as occurring during event delivery, pushing a FRED stack frame with the nested bit set and potentially selecting an incorrect ring 0 stack level (such as IA32_FRED_RSP1 instead of IA32_FRED_RSP0)?

Quoted 4 lines
arch/x86/kvm/x86.c +0 -0
 		/* replace previous exception with a new one in a hope
 		   that instruction re-execution will regenerate lost
 		   exception */
@@ -538,7 +547,8 @@ static void kvm_queue_exception_e_p(struct kvm_vcpu *vcpu, unsigned nr,
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#50 lore raw

Re: [PATCH v10 13/28] KVM: VMX: Virtualize FRED nested exception tracking

In reply to Sohil Mehta
Quoted 26 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Set the VMX nested exception bit in VM-entry interruption information field when injecting a nested exception using FRED event delivery to ensure:
1) A 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 an earlier 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 the stack pointed by IA32_FRED_RSP1 MSR when encountered in ring 3 and ring 0.
- normal #PF will be delivered on the stack pointed by IA32_FRED_RSP0 MSR when encountered in ring 3.

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

In addition, save/restore the nested flag of an exception during VM save/restore and live migration to ensure a correct event stack level is chosen when a nested exception is injected through FRED event delivery across VM save/restore and live migration.

Quoted 4 lines

Note, like the other fields of struct kvm_queued_exception, the nested flag is meaningful only while the exception is pending or injected. It is not consulted otherwise, and so doesn't need to be cleared when an exception is dropped.

Just try to understand the sentence.
The patch clears is_nested alongside pending/injected in two places:
1. kvm_clear_exception_queue()
2. When the exception from userspace is converted to a nested vm exit.

So are they needed?

Quoted 3 lines
[ Sean: reworked kvm_requeue_exception() to simply the code changes ]
                                                ^

simplify

Quoted 3 lines

[...]

Quoted 19 lines
arch/x86/kvm/x86.c +1 -0
@@ -8978,6 +8993,7 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 					   ex->has_payload, ex->payload);
 		ex->injected = false;
 		ex->pending = false;
+		ex->is_nested = false;
 	}
 	vcpu->arch.exception_from_userspace = false;
 
arch/x86/kvm/x86.h +1 -0
index 0f5919b092e4..2d6bae66cfae 100644
@@ -158,6 +158,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.is_nested = false;
 	vcpu->arch.exception_vmexit.pending = false;
 }
#51 lore raw

Re: [PATCH v10 13/28] KVM: VMX: Virtualize FRED nested exception tracking

Quoted 5 lines · Binbin Wu
Quoted 4 lines

Note, like the other fields of struct kvm_queued_exception, the nested flag is meaningful only while the exception is pending or injected. It is not consulted otherwise, and so doesn't need to be cleared when an exception is dropped.

Quoted 7 lines

Just try to understand the sentence.
The patch clears is_nested alongside pending/injected in two places:
1. kvm_clear_exception_queue()
2. When the exception from userspace is converted to a nested vm exit.

So are they needed?

I don't think they are needed any longer. v9 needed the clear in kvm_clear_exception_queue() because the old flag was ORed into the new one. But, now kvm_multiple_exception() uses a local variable. So both the above clears can be removed.

Quoted 6 lines
Quoted 3 lines
[ Sean: reworked kvm_requeue_exception() to simply the code changes ]
                                                ^

simplify

This handler comment that got added early on in the series seems a bit out of place now. I'll drop it or maybe change it to a Co-developed-by if the original code that Sean suggested is still being used.

Quoted 26 lines
Quoted 3 lines

[...]

Quoted 19 lines
arch/x86/kvm/x86.c +1 -0
@@ -8978,6 +8993,7 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu)
 					   ex->has_payload, ex->payload);
 		ex->injected = false;
 		ex->pending = false;
+		ex->is_nested = false;
 	}
 	vcpu->arch.exception_from_userspace = false;
 
arch/x86/kvm/x86.h +1 -0
index 0f5919b092e4..2d6bae66cfae 100644
@@ -158,6 +158,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.is_nested = false;
 	vcpu->arch.exception_vmexit.pending = false;
 }
#52 lore raw

PATCH v10 14/28 KVM: VMX: Virtualize FRED event_data

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Set injected-event data when injecting a #PF, #DB, or #NM due to 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.

In addition, save/restore the event data of an exception during VM save/restore and live migration to ensure it's properly saved and restored across VM save/restore and live migration. Clear the injected-event data field when injecting an IRQ or an NMI as no event data is currently defined for them.

[ Sean: reworked event data injection for nested ]

---
v10:
- Reset event data in kvm_clear_exception_queue() (Chao).
- Clear event data to 0 to prevent stale data leakage when injecting a hardware exception that doesn't require FRED event data.
- Save/restore event data for properly restoring it for #PF (CR2), #DB (DR6) and #NM due to extended feature disable (IA32_XFD_ERR) (Chao).
- Clear the INJECTED_EVENT_DATA VMCS field during NMI and IRQ injection. (Zhao)

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/include/asm/vmx.h      |  4 +++
 arch/x86/include/uapi/asm/kvm.h |  5 ++-
 arch/x86/kvm/svm/svm.c          |  2 +-
 arch/x86/kvm/vmx/vmx.c          | 58 ++++++++++++++++++++++++++++++---
 arch/x86/kvm/x86.c              | 23 ++++++++++++-
 arch/x86/kvm/x86.h              |  3 +-
 7 files changed, 88 insertions(+), 8 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -0
index 994c354dc47b..21d12d86a18b 100644
@@ -696,6 +696,7 @@ struct kvm_queued_exception {
 	unsigned long payload;
 	bool has_payload;
 	bool is_nested;
+	u64 event_data;
 };
 
 /*
arch/x86/include/asm/vmx.h +4 -0
index 7eb08f84a7e5..6633988a84da 100644
@@ -283,8 +283,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/include/uapi/asm/kvm.h +4 -1
index 659c8391d40e..c8a6149fcf63 100644
@@ -369,7 +369,10 @@ struct kvm_vcpu_events {
 	struct {
 		__u8 pending;
 	} triple_fault;
-	__u8 reserved[25];
+	__u8 reserved0[11];
+	/* Aligned to a 64-bit boundary */
+	__u64 exception_event_data;
+	__u8 reserved1[6];
 	__u8 exception_is_nested;
 	__u8 exception_has_payload;
 	__u64 exception_payload;
arch/x86/kvm/svm/svm.c +1 -1
index 7762db655b28..f254a5ff570d 100644
@@ -4392,7 +4392,7 @@ static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
 
 		kvm_requeue_exception(vcpu, vector,
 				      exitintinfo & SVM_EXITINTINFO_VALID_ERR,
-				      error_code, false);
+				      error_code, false, 0);
 		break;
 	}
 	case SVM_EXITINTINFO_TYPE_INTR:
arch/x86/kvm/vmx/vmx.c +54 -4

122 lines not on this page · raw message

arch/x86/kvm/x86.c +22 -1
index 94d684210cf6..e10ac6b280f6 100644
@@ -431,9 +431,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;
 	}
 
@@ -493,6 +506,10 @@ static void kvm_multiple_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 						 (is_nested ||
 						  vcpu->arch.nmi_injected ||
 						  vcpu->arch.interrupt.injected);
+		/*
+		 * Do not update the event data, as the current value may have
+		 * just been restored during a VM save/restore or live migration.
+		 */
 		return;
 	}
 
@@ -548,7 +565,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 is_nested)
+			   bool is_nested, u64 event_data)
 {
 
 	/*
@@ -574,6 +591,7 @@ void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned int nr,
 	vcpu->arch.exception.has_payload = false;
 	vcpu->arch.exception.payload = 0;
 	vcpu->arch.exception.is_nested = is_nested;
+	vcpu->arch.exception.event_data = event_data;
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_requeue_exception);
 
@@ -3012,6 +3030,7 @@ static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
 	events->exception_has_payload = ex->has_payload;
 	events->exception_payload = ex->payload;
 	events->exception_is_nested = ex->is_nested;
+	events->exception_event_data = ex->event_data;
 
 	events->interrupt.injected =
 		vcpu->arch.interrupt.injected && !vcpu->arch.interrupt.soft;
@@ -3074,6 +3093,7 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 			return -EINVAL;
 	} else {
 		events->exception_is_nested = 0;
+		events->exception_event_data = 0;
 	}
 
 	if ((events->exception.injected || events->exception.pending) &&
@@ -3102,6 +3122,7 @@ static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
 	vcpu->arch.exception.has_payload = events->exception_has_payload;
 	vcpu->arch.exception.payload = events->exception_payload;
 	vcpu->arch.exception.is_nested = events->exception_is_nested;
+	vcpu->arch.exception.event_data = events->exception_event_data;
 
 	vcpu->arch.interrupt.injected = events->interrupt.injected;
 	vcpu->arch.interrupt.nr = events->interrupt.nr;
arch/x86/kvm/x86.h +2 -1
index 2d6bae66cfae..43c5c08f5d5c 100644
@@ -159,6 +159,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.is_nested = false;
+	vcpu->arch.exception.event_data = 0;
 	vcpu->arch.exception_vmexit.pending = false;
 }
 
@@ -504,7 +505,7 @@ 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 is_nested);
+			   bool is_nested, u64 event_data);
 void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault,
 			   bool from_hardware);
 void __kvm_inject_emulated_page_fault(struct kvm_vcpu *vcpu,
Signature · 1 line
2.43.0
#53 lore raw

Re: [PATCH v10 14/28] KVM: VMX: Virtualize FRED event_data

arch/x86/kvm/x86.c void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,

Quoted 6 lines · Sohil Mehta
arch/x86/kvm/x86.c +0 -0
index 94d684210cf6..e10ac6b280f6 100644
@@ -431,9 +431,22 @@ void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,

kvm_deliver_exception_payload() returns early if !ex->has_payload.

For example, if a #PF is injected, kvm_deliver_exception_payload() sets ex->event_data to cr2.
Later, if a #DB without payload is queued via KVM_GUESTDBG_INJECT_DB, the event_data is not updated.
It seems the stale #PF event_data will be write to INJECTED_EVENT_DATA and delivered to #DB handler in the guest.

Quoted 22 lines
arch/x86/kvm/x86.c +13 -0
 		 * 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;
 	}
 
#54 lore raw

Re: [PATCH v10 14/28] KVM: VMX: Virtualize FRED event_data

Quoted 10 lines · Binbin Wu

arch/x86/kvm/x86.c void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,

Quoted 6 lines · Sohil Mehta
arch/x86/kvm/x86.c +0 -0
index 94d684210cf6..e10ac6b280f6 100644
@@ -431,9 +431,22 @@ void kvm_deliver_exception_payload(struct kvm_vcpu *vcpu,

kvm_deliver_exception_payload() returns early if !ex->has_payload.

Quoted 7 lines

For example, if a #PF is injected, kvm_deliver_exception_payload() sets ex->event_data to cr2.
Later, if a #DB without payload is queued via KVM_GUESTDBG_INJECT_DB, the event_data is not updated.
It seems the stale #PF event_data will be write to INJECTED_EVENT_DATA and delivered to #DB handler in the guest.

AFAIU, if the #PF is injected, the next VM exit would call vm_clear_exception_queue() which would zero out the event_data. Also, based on commit e907b4e72488 ("KVM: x86: Check for injected exceptions before queuing a debug exception"), even if the exit interrupted the #PF delivery it shouldn't be an issue.

But, I agree with you in principle. kvm_multiple_exception() leaves event_data alone when it queues an exception, so an exception without a payload would inherit the old event data which makes it a little fragile.

To solidify this, I am thinking that event_data can be zeroed in kvm_multiple_exception() similar to how is_nested is handled. Later, kvm_deliver_exception_payload() can fill it from the payload.

Quoted 23 lines
Quoted 22 lines
arch/x86/kvm/x86.c +13 -0
 		 * 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;
 	}
 
#55 lore raw

PATCH v10 15/28 KVM: x86: Include CR4.FRED in the emulator CR4 write mask

In reply to Sohil Mehta

From: Xin Li <[email protected]>

Add CR4.FRED to the emulator's CR4 write mask. Historically, CR4 was restricted to its lower 32 bits in the x86 architecture. With the introduction of FRED, CR4 is expanded to use its higher 32 bits to accommodate the FRED enablement bit at position 32. Update the mask to ensure the emulator correctly handles FRED initialization and prevents the inadvertent truncation of high-order bits.

---
v10:
- New patch

---
 arch/x86/kvm/regs.h |  2 +-
 arch/x86/kvm/x86.c  | 12 +++++++++---
 2 files changed, 10 insertions(+), 4 deletions(-)
arch/x86/kvm/regs.h +1 -1
index 4e641a6c20f9..ef46918daf43 100644
@@ -8,7 +8,7 @@
 #define KVM_POSSIBLE_CR4_GUEST_BITS				  \
 	(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR  \
 	 | X86_CR4_OSXMMEXCPT | X86_CR4_PGE | X86_CR4_TSD | X86_CR4_FSGSBASE \
-	 | X86_CR4_CET)
+	 | X86_CR4_CET | X86_CR4_FRED)
 
 #define X86_CR0_PDPTR_BITS    (X86_CR0_CD | X86_CR0_NW | X86_CR0_PG)
 #define X86_CR4_TLBFLUSH_BITS (X86_CR4_PGE | X86_CR4_PCIDE | X86_CR4_PAE | X86_CR4_SMEP)
arch/x86/kvm/x86.c +9 -3
index e10ac6b280f6..f264bc9c35f9 100644
@@ -5552,11 +5552,17 @@ static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
 }
 
-static u64 mk_cr_64(u64 curr_cr, u32 new_val)
+static u64 mk_cr0_64(u64 curr_cr, u32 new_val)
 {
 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
 }
 
+static u64 mk_cr4_64(struct kvm_vcpu *vcpu, u64 curr_cr, u64 new_val)
+{
+	u32 shift = guest_cpu_cap_has(vcpu, X86_FEATURE_FRED) ? 33 : 32;
+	return (curr_cr & ~((1ULL << shift) - 1)) | new_val;
+}
+
 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
 {
 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
@@ -5593,7 +5599,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
 
 	switch (cr) {
 	case 0:
-		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
+		res = kvm_set_cr0(vcpu, mk_cr0_64(kvm_read_cr0(vcpu), val));
 		break;
 	case 2:
 		vcpu->arch.cr2 = val;
@@ -5602,7 +5608,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
 		res = kvm_set_cr3(vcpu, val);
 		break;
 	case 4:
-		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
+		res = kvm_set_cr4(vcpu, mk_cr4_64(vcpu, kvm_read_cr4(vcpu), val));
 		break;
 	case 8:
 		res = kvm_set_cr8(vcpu, val);
Signature · 1 line
2.43.0
#56 lore raw

Re: [PATCH v10 15/28] KVM: x86: Include CR4.FRED in the emulator CR4 write mask

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] `mk_cr4_64` erroneously attempts to preserve the upper bits of CR4, contradicting x86…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mk_cr4_64 erroneously attempts to preserve the upper bits of CR4, contradicting x86 architecture and breaking future higher-order CR4 bits. --

commit 3026fdc333b24532424b51db68dd9e65b0a1065c
Author: Xin Li <[email protected]>

KVM: x86: Include CR4.FRED in the emulator CR4 write mask

This commit updates the emulator's CR4 write mask to accommodate the FRED enablement bit, expanding CR4 support to use its higher 32 bits when the feature is present.

Quoted 3 lines
arch/x86/kvm/x86.c +0 -0

[ ... ]

Quoted 5 lines
arch/x86/kvm/x86.c +0 -1
@@ -5552,11 +5552,17 @@ static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
 }
 
-static u64 mk_cr_64(u64 curr_cr, u32 new_val)

arch/x86/kvm/x86.c static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, · line 5564

Quoted 10 lines
arch/x86/kvm/x86.c +6 -0
+static u64 mk_cr0_64(u64 curr_cr, u32 new_val)
 {
 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
 }
 
+static u64 mk_cr4_64(struct kvm_vcpu *vcpu, u64 curr_cr, u64 new_val)
+{
+	u32 shift = guest_cpu_cap_has(vcpu, X86_FEATURE_FRED) ? 33 : 32;
+	return (curr_cr & ~((1ULL << shift) - 1)) | new_val;
+}

[Severity: Medium]
Does this bitwise logic incorrectly preserve the upper bits of CR4?

The x86 architecture specifies that a 64-bit MOV to CR4 overwrites the entire register, and a 32-bit MOV to CR4 clears the upper 32 bits. The val passed into emulator_set_cr() already contains the correct architectural value (zero-extended if 32-bit, or the full 64-bit value).

By preserving bits above the shift boundary, this could prevent a guest from clearing future higher-order CR4 bits once they are set. Since the bitwise AND mask will preserve the 1 from curr_cr and OR it with the new value, those upper bits would remain permanently set if they were already present.

Could emulator_set_cr() simply pass val directly to kvm_set_cr4() without attempting to merge it with the current CR4 value?

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
#57 lore raw

Re: [PATCH v10 15/28] KVM: x86: Include CR4.FRED in the emulator CR4 write mask

In reply to Sohil Mehta
Quoted 41 lines · Sohil Mehta

From: Xin Li <[email protected]>

Add CR4.FRED to the emulator's CR4 write mask. Historically, CR4 was restricted to its lower 32 bits in the x86 architecture. With the introduction of FRED, CR4 is expanded to use its higher 32 bits to accommodate the FRED enablement bit at position 32. Update the mask to ensure the emulator correctly handles FRED initialization and prevents the inadvertent truncation of high-order bits.

---
v10:
- New patch

---
 arch/x86/kvm/regs.h |  2 +-
 arch/x86/kvm/x86.c  | 12 +++++++++---
 2 files changed, 10 insertions(+), 4 deletions(-)
arch/x86/kvm/regs.h +1 -1
index 4e641a6c20f9..ef46918daf43 100644
@@ -8,7 +8,7 @@
 #define KVM_POSSIBLE_CR4_GUEST_BITS				  \
 	(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR  \
 	 | X86_CR4_OSXMMEXCPT | X86_CR4_PGE | X86_CR4_TSD | X86_CR4_FSGSBASE \
-	 | X86_CR4_CET)
+	 | X86_CR4_CET | X86_CR4_FRED)
 
 #define X86_CR0_PDPTR_BITS    (X86_CR0_CD | X86_CR0_NW | X86_CR0_PG)
 #define X86_CR4_TLBFLUSH_BITS (X86_CR4_PGE | X86_CR4_PCIDE | X86_CR4_PAE | X86_CR4_SMEP)
arch/x86/kvm/x86.c +0 -1
index e10ac6b280f6..f264bc9c35f9 100644
@@ -5552,11 +5552,17 @@ static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
 }
 
-static u64 mk_cr_64(u64 curr_cr, u32 new_val)

arch/x86/kvm/x86.c static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, · line 5564

Quoted 10 lines
arch/x86/kvm/x86.c +6 -0
+static u64 mk_cr0_64(u64 curr_cr, u32 new_val)
 {
 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
 }
 
+static u64 mk_cr4_64(struct kvm_vcpu *vcpu, u64 curr_cr, u64 new_val)
+{
+	u32 shift = guest_cpu_cap_has(vcpu, X86_FEATURE_FRED) ? 33 : 32;
+	return (curr_cr & ~((1ULL << shift) - 1)) | new_val;
+}

It's a bit weird to do it based on specific features.

Also, I am not sure this is needed to do the special handling to preserve the higher bits.
emulator has zero extended the higher bits in fetch_register_operand() if in non-64bit mode. I think we can just take the full 64-bit new value? Did I miss anything?

And also for CR0, is the special handling needed?

Quoted 22 lines
arch/x86/kvm/x86.c +3 -2
+
 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
 {
 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
@@ -5593,7 +5599,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
 
 	switch (cr) {
 	case 0:
-		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
+		res = kvm_set_cr0(vcpu, mk_cr0_64(kvm_read_cr0(vcpu), val));
 		break;
 	case 2:
 		vcpu->arch.cr2 = val;
@@ -5602,7 +5608,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
 		res = kvm_set_cr3(vcpu, val);
 		break;
 	case 4:
-		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
+		res = kvm_set_cr4(vcpu, mk_cr4_64(vcpu, kvm_read_cr4(vcpu), val));
 		break;
 	case 8:
 		res = kvm_set_cr8(vcpu, val);
#58 lore raw

Re: [PATCH v10 15/28] KVM: x86: Include CR4.FRED in the emulator CR4 write mask

Quoted 20 lines · Binbin Wu
Quoted 19 lines · Sohil Mehta

From: Xin Li <[email protected]>

Add CR4.FRED to the emulator's CR4 write mask. Historically, CR4 was restricted to its lower 32 bits in the x86 architecture. With the introduction of FRED, CR4 is expanded to use its higher 32 bits to accommodate the FRED enablement bit at position 32. Update the mask to ensure the emulator correctly handles FRED initialization and prevents the inadvertent truncation of high-order bits.

---
v10:
- New patch

---
 arch/x86/kvm/regs.h |  2 +-
 arch/x86/kvm/x86.c  | 12 +++++++++---
 2 files changed, 10 insertions(+), 4 deletions(-)
Quoted 11 lines

arch/x86/kvm/regs.h line 12

Quoted 11 lines
arch/x86/kvm/regs.h +1 -1
index 4e641a6c20f9..ef46918daf43 100644
@@ -8,7 +8,7 @@
 #define KVM_POSSIBLE_CR4_GUEST_BITS				  \
 	(X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR  \
 	 | X86_CR4_OSXMMEXCPT | X86_CR4_PGE | X86_CR4_TSD | X86_CR4_FSGSBASE \
-	 | X86_CR4_CET)
+	 | X86_CR4_CET | X86_CR4_FRED)
 

Looking at this again. I am not sure if this is accurate. Sean's comment in v9 was that KVM should always intercept and emulate CR4.FRED writes. IIUC, by default the bit is KVM owned. So, adding FRED to this guest list seems opposite to that preference.

Quoted 24 lines
Quoted 11 lines
arch/x86/kvm/regs.h +0 -0
 #define X86_CR0_PDPTR_BITS    (X86_CR0_CD | X86_CR0_NW | X86_CR0_PG)
 #define X86_CR4_TLBFLUSH_BITS (X86_CR4_PGE | X86_CR4_PCIDE | X86_CR4_PAE | X86_CR4_SMEP)
arch/x86/kvm/x86.c +0 -1
index e10ac6b280f6..f264bc9c35f9 100644
@@ -5552,11 +5552,17 @@ static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr,
 	return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
 }
 
-static u64 mk_cr_64(u64 curr_cr, u32 new_val)

arch/x86/kvm/x86.c static int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, · line 5564

Quoted 10 lines
arch/x86/kvm/x86.c +6 -0
+static u64 mk_cr0_64(u64 curr_cr, u32 new_val)
 {
 	return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
 }
 
+static u64 mk_cr4_64(struct kvm_vcpu *vcpu, u64 curr_cr, u64 new_val)
+{
+	u32 shift = guest_cpu_cap_has(vcpu, X86_FEATURE_FRED) ? 33 : 32;
+	return (curr_cr & ~((1ULL << shift) - 1)) | new_val;
+}

It's a bit weird to do it based on specific features.

Quoted 6 lines

Also, I am not sure this is needed to do the special handling to preserve the higher bits.
emulator has zero extended the higher bits in fetch_register_operand() if in non-64bit mode. I think we can just take the full 64-bit new value? Did I miss anything?

You are right. The value is already the full operand in 64-bit mode and zero extended otherwise.

Quoted 2 lines

And also for CR0, is the special handling needed?

Yeah, this whole thing is unnecessarily complex. I think we can get rid of mk_cr_64() and drop this patch entirely. How about something like below (based on kvm-x86-next-2026.10.13)?

Quoted 6 lines
Quoted 6 lines
arch/x86/kvm/x86.c +1 -0
+
 static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
 {
 	struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
@@ -5593,7 +5599,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
 
Quoted 17 lines
Quoted 8 lines
arch/x86/kvm/x86.c +1 -1
 	switch (cr) {
 	case 0:
-		res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
+		res = kvm_set_cr0(vcpu, mk_cr0_64(kvm_read_cr0(vcpu), val));
 		break;
 	case 2:
 		vcpu->arch.cr2 = val;

arch/x86/kvm/x86.c static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val) · line 5614

Quoted 8 lines
arch/x86/kvm/x86.c +1 -1
@@ -5602,7 +5608,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
 		res = kvm_set_cr3(vcpu, val);
 		break;
 	case 4:
-		res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
+		res = kvm_set_cr4(vcpu, mk_cr4_64(vcpu, kvm_read_cr4(vcpu), val));
 		break;
 	case 8:
 		res = kvm_set_cr8(vcpu, val);

KVM: x86: Stop truncating CR0/CR4 writes from the emulator

Pass the new value directly to kvm_set_cr0() and kvm_set_cr4() when emulating MOV to CR, instead of taking the low 32 bits of the new value and the upper 32 bits of the current value. Preserving the upper half is not needed, as KVM never allows a bit above bit 31 to be set in CR0 or CR4. In practice, mk_cr_64() only truncates the new value, which allows an emulated write that sets a reserved bit in CR[63:32] to succeed instead of generating #GP.

Truncating the value is unnecessary to begin with. MOV to CR is emulated with Op3264, i.e. the emulator provides the architectural value: the full operand in 64-bit mode, and a zero-extended 32-bit operand otherwise. Note, only the emulator is special in this regard, VMX and SVM pass the guest's value through as-is when handling CR access exits.

Dropping the truncation also readies the emulator for FRED. CR4.FRED (bit 32) is the first CR4 bit defined in the upper half. It now needs no special handling as the full value is passed through.

---

arch/x86/kvm/x86.c +0 -0
index 32563a91fba9..a6f94595ac75 100644
@@ -5541,11 +5541,6 @@ static int emulator_set_dr(struct

x86_emulate_ctxt *ctxt, int dr,
return kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
}

-static u64 mk_cr_64(u64 curr_cr, u32 new_val)
-{
- return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
-}
-
static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr) {
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
@@ -5582,7 +5577,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)

switch (cr) {
case 0:
- res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
+ res = kvm_set_cr0(vcpu, val);
break;
case 2:
vcpu->arch.cr2 = val;
@@ -5591,7 +5586,7 @@ static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
res = kvm_set_cr3(vcpu, val);
break;
case 4:
- res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
+ res = kvm_set_cr4(vcpu, val);
break;
case 8:
res = kvm_set_cr8(vcpu, val);

#59 lore raw

PATCH v10 16/28 KVM: x86: Mark CR4.FRED as not reserved

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

The CR4.FRED bit, i.e., CR4[32], is no longer a reserved bit when guest cpu cap has FRED, i.e.,
1) All of FRED KVM support is in place.
2) Guest enumerates FRED.

Otherwise it is still a reserved bit.

---
v10:
- Check CR4.FRED against IA-32e mode in kvm_set_cr4() instead of __kvm_is_valid_cr4(), so that KVM_SET_SREGS no longer rejects a CR4 and EFER pair that are loaded together (e.g., when restoring a FRED guest)

---
 arch/x86/kvm/regs.c | 7 +++++++
 arch/x86/kvm/regs.h | 4 +++-
 2 files changed, 10 insertions(+), 1 deletion(-)
arch/x86/kvm/regs.c +7 -0
index 8f66438989e4..ba6c8856b4ff 100644
@@ -429,6 +429,13 @@ int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 			return 1;
 	}
 
+	/*
+	 * FRED can not be enabled when EFER.LMA=0.  Note, MOV to CR4 outside
+	 * 64-bit mode clears CR4[63:32] so only emulation can get here.
+	 */
+	if ((cr4 & X86_CR4_FRED) && !is_long_mode(vcpu))
+		return 1;
+
 	if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
 		return 1;
 
arch/x86/kvm/regs.h +3 -1
index ef46918daf43..5db01693ad07 100644
@@ -28,7 +28,7 @@ static_assert(!(KVM_POSSIBLE_CR0_GUEST_BITS & X86_CR0_PDPTR_BITS));
 			  | 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_CET))
+			  | X86_CR4_LAM_SUP | X86_CR4_CET | X86_CR4_FRED))
 
 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
 
@@ -423,6 +423,8 @@ static inline bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 	if (!__cpu_has(__c, X86_FEATURE_SHSTK) &&       \
 	    !__cpu_has(__c, X86_FEATURE_IBT))           \
 		__reserved_bits |= X86_CR4_CET;         \
+	if (!__cpu_has(__c, X86_FEATURE_FRED))          \
+		__reserved_bits |= X86_CR4_FRED;        \
 	__reserved_bits;                                \
 })
 
Signature · 1 line
2.43.0
#60 lore raw

Re: [PATCH v10 16/28] KVM: x86: Mark CR4.FRED as not reserved

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Missing architectural check for CR4.FRED when clearing CR0.PG leads to VM-entry failure and VM…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Missing architectural check for CR4.FRED when clearing CR0.PG leads to VM-entry failure and VM crash. --

commit 8a690b67e3843377a671848b2a774dffef3545bc
Author: Xin Li (Intel) <[email protected]>

KVM: x86: Mark CR4.FRED as not reserved

The CR4.FRED bit, i.e., CR4[32], is no longer a reserved bit when guest cpu cap has FRED. Otherwise it is still a reserved bit.

Quoted 5 lines
arch/x86/kvm/regs.c +0 -0
index 8f66438989e47..ba6c8856b4ffa 100644

arch/x86/kvm/regs.c int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) · line 438

Quoted 10 lines
arch/x86/kvm/regs.c +7 -0
@@ -429,6 +429,13 @@ int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 			return 1;
 	}
 
+	/*
+	 * FRED can not be enabled when EFER.LMA=0.  Note, MOV to CR4 outside
+	 * 64-bit mode clears CR4[63:32] so only emulation can get here.
+	 */
+	if ((cr4 & X86_CR4_FRED) && !is_long_mode(vcpu))
+		return 1;
+

[Severity: High]
Does unreserving CR4.FRED also require an update to kvm_set_cr0() when clearing CR0.PG?

If a guest operating in compatibility mode (CS.L=0) with CR4.FRED=1 executes MOV CR0 to clear the CR0.PG bit, kvm_set_cr0() will allow the operation because it only checks for is_64_bit_mode() and X86_CR4_PCIDE:

arch/x86/kvm/regs.c:kvm_set_cr0() {
	...
	if (!(cr0 & X86_CR0_PG) &&
	    (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
		return 1;
	...
}

Because kvm_set_cr0() fails to check for X86_CR4_FRED, KVM allows the operation, clears CR0.PG, and subsequently clears EFER.LMA and the VM_ENTRY_IA32E_MODE control.

This results in a hardware VM-entry failure ("invalid guest state") because the hardware checks require CR4.FRED to be 0 if the IA-32e mode guest control is 0. This hardware failure leads to KVM_EXIT_FAIL_ENTRY and crashes the hypervisor process hosting the VM, whereas KVM should have injected a #GP.

Quoted 3 lines
arch/x86/kvm/regs.c +0 -0
 	if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
 		return 1;
 
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#61 lore raw

Re: [PATCH v10 16/28] KVM: x86: Mark CR4.FRED as not reserved

In reply to Sohil Mehta
Quoted 27 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

The CR4.FRED bit, i.e., CR4[32], is no longer a reserved bit when guest cpu cap has FRED, i.e.,
1) All of FRED KVM support is in place.
2) Guest enumerates FRED.

Otherwise it is still a reserved bit.

---
v10:
- Check CR4.FRED against IA-32e mode in kvm_set_cr4() instead of __kvm_is_valid_cr4(), so that KVM_SET_SREGS no longer rejects a CR4 and EFER pair that are loaded together (e.g., when restoring a FRED guest)

---
 arch/x86/kvm/regs.c | 7 +++++++
 arch/x86/kvm/regs.h | 4 +++-
 2 files changed, 10 insertions(+), 1 deletion(-)
arch/x86/kvm/regs.c +0 -0
index 8f66438989e4..ba6c8856b4ff 100644

arch/x86/kvm/regs.c int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) · line 435

Quoted 7 lines
arch/x86/kvm/regs.c +4 -0
@@ -429,6 +429,13 @@ int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 			return 1;
 	}
 
+	/*
+	 * FRED can not be enabled when EFER.LMA=0.  Note, MOV to CR4 outside
+	 * 64-bit mode clears CR4[63:32] so only emulation can get here.
+	 */

Could you elaborate what "emulation" means here?

Quoted 28 lines
arch/x86/kvm/regs.c +3 -0
+	if ((cr4 & X86_CR4_FRED) && !is_long_mode(vcpu))
+		return 1;
+
 	if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
 		return 1;
 
arch/x86/kvm/regs.h +3 -1
index ef46918daf43..5db01693ad07 100644
@@ -28,7 +28,7 @@ static_assert(!(KVM_POSSIBLE_CR0_GUEST_BITS & X86_CR0_PDPTR_BITS));
 			  | 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_CET))
+			  | X86_CR4_LAM_SUP | X86_CR4_CET | X86_CR4_FRED))
 
 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
 
@@ -423,6 +423,8 @@ static inline bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 	if (!__cpu_has(__c, X86_FEATURE_SHSTK) &&       \
 	    !__cpu_has(__c, X86_FEATURE_IBT))           \
 		__reserved_bits |= X86_CR4_CET;         \
+	if (!__cpu_has(__c, X86_FEATURE_FRED))          \
+		__reserved_bits |= X86_CR4_FRED;        \
 	__reserved_bits;                                \
 })
 
#62 lore raw

Re: [PATCH v10 16/28] KVM: x86: Mark CR4.FRED as not reserved

Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/regs.c +0 -0
index 8f66438989e4..ba6c8856b4ff 100644
@@ -429,6 +429,13 @@ int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 			return 1;
 	}
 
Quoted 7 lines

arch/x86/kvm/regs.c int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) · line 435

Quoted 4 lines
arch/x86/kvm/regs.c +4 -0
+	/*
+	 * FRED can not be enabled when EFER.LMA=0.  Note, MOV to CR4 outside
+	 * 64-bit mode clears CR4[63:32] so only emulation can get here.
+	 */

Could you elaborate what "emulation" means here?

I think the only emulation component that can currently get here is RSM. As we discussed in patch 15, an emulated MOV to CR4 is Op3264 which is automatically zero extended.

FRED spec Chapter 12 describes the RSM implication for FRED (see next patch). In a nutshell, with KVM's RSM emulation it may be possible to call kvm_set_cr4() with CR4.FRED=1 but EFER.LMA=0.

This check mainly handles that situation and makes RSM shut down. Though, I am not sure how important it is to correctly emulate RSM. The checks were simple enough so I added them.

Quoted 29 lines
Quoted 28 lines
arch/x86/kvm/regs.c +3 -0
+	if ((cr4 & X86_CR4_FRED) && !is_long_mode(vcpu))
+		return 1;
+
 	if ((cr4 & X86_CR4_CET) && !kvm_is_cr0_bit_set(vcpu, X86_CR0_WP))
 		return 1;
 
arch/x86/kvm/regs.h +3 -1
index ef46918daf43..5db01693ad07 100644
@@ -28,7 +28,7 @@ static_assert(!(KVM_POSSIBLE_CR0_GUEST_BITS & X86_CR0_PDPTR_BITS));
 			  | 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_CET))
+			  | X86_CR4_LAM_SUP | X86_CR4_CET | X86_CR4_FRED))
 
 #define CR8_RESERVED_BITS (~(unsigned long)X86_CR8_TPR)
 
@@ -423,6 +423,8 @@ static inline bool __kvm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
 	if (!__cpu_has(__c, X86_FEATURE_SHSTK) &&       \
 	    !__cpu_has(__c, X86_FEATURE_IBT))           \
 		__reserved_bits |= X86_CR4_CET;         \
+	if (!__cpu_has(__c, X86_FEATURE_FRED))          \
+		__reserved_bits |= X86_CR4_FRED;        \
 	__reserved_bits;                                \
 })
 
#63 lore raw

PATCH v10 17/28 KVM: x86: Handle CR4.FRED when emulating RSM

In reply to Sohil Mehta

Clear CR4.FRED before CR0.PG when leaving long mode on RSM, and restore it only after CR0.PG has been set, the same way CR4.PCIDE is already handled in both directions.

SMI delivery saves all 64 bits of CR4 and RSM restores them so CR4.FRED survives SMM. But KVM emulates RSM as a series of individual register writes, and so drives the vCPU through an intermediate state with CR4.FRED set and EFER.LMA clear. kvm_set_cr4() rejects that combination, so RSM of a 64-bit FRED guest fails with X86EMUL_UNHANDLEABLE.

Note, SMI delivery needs no such handling, as enter_smm() clears CR4 in full via the vendor callback rather than kvm_set_cr4().

---
v10:
- New patch

---
 arch/x86/kvm/smm.c | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)
arch/x86/kvm/smm.c +11 -7
index 656a38dad7e7..a504e93fc5f5 100644
@@ -435,10 +435,10 @@ static int rsm_enter_protected_mode(struct kvm_vcpu *vcpu,
 
 	/*
 	 * First enable PAE, long mode needs it before CR0.PG = 1 is set.
-	 * Then enable protected mode.	However, PCID cannot be enabled
-	 * if EFER.LMA=0, so set it separately.
+	 * Then enable protected mode. However, PCID and FRED cannot be
+	 * enabled if EFER.LMA=0, so set them separately.
 	 */
-	bad = kvm_set_cr4(vcpu, cr4 & ~X86_CR4_PCIDE);
+	bad = kvm_set_cr4(vcpu, cr4 & ~(X86_CR4_PCIDE | X86_CR4_FRED));
 	if (bad)
 		return X86EMUL_UNHANDLEABLE;
 
@@ -446,7 +446,7 @@ static int rsm_enter_protected_mode(struct kvm_vcpu *vcpu,
 	if (bad)
 		return X86EMUL_UNHANDLEABLE;
 
-	if (cr4 & X86_CR4_PCIDE) {
+	if (cr4 & (X86_CR4_PCIDE | X86_CR4_FRED)) {
 		bad = kvm_set_cr4(vcpu, cr4);
 		if (bad)
 			return X86EMUL_UNHANDLEABLE;
@@ -599,10 +599,14 @@ int emulator_leave_smm(struct x86_emulate_ctxt *ctxt)
 		struct kvm_segment cs_desc;
 		unsigned long cr4;
 
-		/* Zero CR4.PCIDE before CR0.PG.  */
+		/*
+		 * Zero CR4.PCIDE and CR4.FRED before CR0.PG, as neither can
+		 * be set while EFER.LMA is 0, and clearing CR0.PG clears
+		 * EFER.LMA.
+		 */
 		cr4 = kvm_read_cr4(vcpu);
-		if (cr4 & X86_CR4_PCIDE)
-			kvm_set_cr4(vcpu, cr4 & ~X86_CR4_PCIDE);
+		if (cr4 & (X86_CR4_PCIDE | X86_CR4_FRED))
+			kvm_set_cr4(vcpu, cr4 & ~(X86_CR4_PCIDE | X86_CR4_FRED));
 
 		/* A 32-bit code segment is required to clear EFER.LMA.  */
 		memset(&cs_desc, 0, sizeof(cs_desc));
Signature · 1 line
2.43.0
#64 lore raw

Re: [PATCH v10 17/28] KVM: x86: Handle CR4.FRED when emulating RSM

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

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

New issues:
- [High] kvm_set_cr0() does not reject clearing CR0.PG when CR4.FRED is set, leading to an architecturally invalid vCPU state and guest-triggered VM-Entry failures.

Pre-existing issues:
- [High] RSM emulation fails for guests with CR4.CET enabled if the SMM handler temporarily clears CR0.WP. --

commit 14cda06623e4685b7e725f05b0e66de0ac8e2fb9
Author: Sohil Mehta <[email protected]>

KVM: x86: Handle CR4.FRED when emulating RSM

Clear CR4.FRED before CR0.PG when leaving long mode on RSM, and restore it only after CR0.PG has been set, the same way CR4.PCIDE is already handled in both directions.

Quoted 7 lines
arch/x86/kvm/smm.c +0 -0
index 656a38dad7e7a..a504e93fc5f5f 100644
@@ -435,10 +435,10 @@ static int rsm_enter_protected_mode(struct kvm_vcpu *vcpu,
 
 	/*

arch/x86/kvm/smm.c static int rsm_enter_protected_mode(struct kvm_vcpu *vcpu, · line 443

Quoted 10 lines
arch/x86/kvm/smm.c +3 -3
 	 * First enable PAE, long mode needs it before CR0.PG = 1 is set.
-	 * Then enable protected mode.	However, PCID cannot be enabled
-	 * if EFER.LMA=0, so set it separately.
+	 * Then enable protected mode. However, PCID and FRED cannot be
+	 * enabled if EFER.LMA=0, so set them separately.
 	 */
-	bad = kvm_set_cr4(vcpu, cr4 & ~X86_CR4_PCIDE);
+	bad = kvm_set_cr4(vcpu, cr4 & ~(X86_CR4_PCIDE | X86_CR4_FRED));
 	if (bad)
 		return X86EMUL_UNHANDLEABLE;

[Severity: High]
This isn't a bug introduced by this patch, but does RSM emulation fail for guests with CR4.CET enabled if the SMM handler temporarily clears CR0.WP?

If a guest enables CR4.CET and CR0.WP, and an SMI occurs where the SMM handler clears CR0.WP (e.g., to modify read-only firmware data) and executes RSM without restoring CR0.WP, rsm_enter_protected_mode() attempts to restore the pre-SMM CR4 (which has CET=1) before restoring the pre-SMM CR0.

The kvm_set_cr4() call fails because the current vCPU CR0 still has WP=0. This forces the VM to shut down due to an unhandleable emulation failure (X86EMUL_UNHANDLEABLE).

Does X86_CR4_CET also need to be masked out here and deferred until after kvm_set_cr0(), exactly like PCIDE and FRED?

[ ... ]

[Severity: High]
Does this missing update to kvm_set_cr0() cause a regression where a guest can clear CR0.PG when CR4.FRED is set?

Looking at kvm_set_cr0() in arch/x86/kvm/regs.c:

	if (!(cr0 & X86_CR0_PG) &&
	    (is_64_bit_mode(vcpu) || kvm_is_cr4_bit_set(vcpu, X86_CR4_PCIDE)))
		return 1;

If a guest in 32-bit compatibility mode (CS.L=0, EFER.LMA=1) with CR4.FRED=1 executes a MOV to CR0 to clear CR0.PG, kvm_set_cr0() incorrectly allows the operation because it only checks for is_64_bit_mode() or CR4.PCIDE=1.

KVM then clears EFER.LMA, leaving the vCPU with CR4.FRED=1 and EFER.LMA=0, which is an architecturally invalid state.

Can this allow a guest kernel (CPL=0) to force a host-level VM-entry abort and cause a Denial of Service by terminating its own VM?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
#65 lore raw

PATCH v10 18/28 KVM: VMX: Dump FRED context in dump_vmcs()

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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

---
v10:
- Test the secondary VM-exit controls in the dump_vmcs()

---
 arch/x86/kvm/vmx/vmx.c | 43 +++++++++++++++++++++++++++++++++++-------
 1 file changed, 36 insertions(+), 7 deletions(-)
arch/x86/kvm/vmx/vmx.c +36 -7
index cd041381b322..3a3315a7fc11 100644
@@ -1501,6 +1501,9 @@ static void vmx_write_guest_fred_rsp0(struct vcpu_vmx *vmx, u64 data)
 	vmx_write_guest_host_msr(vmx, MSR_IA32_FRED_RSP0, data,
 				 &vmx->msr_guest_fred_rsp0);
 }
+#else
+/* Make sure it builds on 32-bit */
+static u64 vmx_read_guest_fred_rsp0(struct vcpu_vmx *vmx) { return 0; }
 #endif
 
 static void grow_ple_window(struct kvm_vcpu *vcpu)
@@ -6727,7 +6730,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;
 
@@ -6738,6 +6741,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);
@@ -6784,6 +6789,16 @@ 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);
+	if (vmentry_ctl & VM_ENTRY_LOAD_IA32_FRED)
+		pr_err("FRED guest: config=0x%016llx, stack_levels=0x%016llx\n"
+		       "RSP0=0x%016llx, RSP1=0x%016llx\n"
+		       "RSP2=0x%016llx, RSP3=0x%016llx\n",
+		       vmcs_read64(GUEST_IA32_FRED_CONFIG),
+		       vmcs_read64(GUEST_IA32_FRED_STKLVLS),
+		       vmx_read_guest_fred_rsp0(vmx),
+		       vmcs_read64(GUEST_IA32_FRED_RSP1),
+		       vmcs_read64(GUEST_IA32_FRED_RSP2),
+		       vmcs_read64(GUEST_IA32_FRED_RSP3));
 	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));
@@ -6835,6 +6850,16 @@ 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));
+	if (secondary_vmexit_ctl & SECONDARY_VM_EXIT_LOAD_IA32_FRED)
+		pr_err("FRED host: config=0x%016llx, stack_levels=0x%016llx\n"
+		       "RSP0=0x%016lx, RSP1=0x%016llx\n"
+		       "RSP2=0x%016llx, RSP3=0x%016llx\n",
+		       vmcs_read64(HOST_IA32_FRED_CONFIG),
+		       vmcs_read64(HOST_IA32_FRED_STKLVLS),
+		       (unsigned long)task_stack_page(current) + THREAD_SIZE,
+		       vmcs_read64(HOST_IA32_FRED_RSP1),
+		       vmcs_read64(HOST_IA32_FRED_RSP2),
+		       vmcs_read64(HOST_IA32_FRED_RSP3));
 	pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
 	       vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
 	       vmcs_readl(HOST_CR4));
@@ -6860,25 +6885,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
#66 lore raw

Re: [PATCH v10 18/28] KVM: VMX: Dump FRED context in dump_vmcs()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The FRED context dump in dump_vmcs() omits the FRED Shadow Stack Pointer (SSP) VMCS fields for both…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The FRED context dump in dump_vmcs() omits the FRED Shadow Stack Pointer (SSP) VMCS fields for both guest and host states. --

commit 823b37b6644ed01e20ab9d85f3f985b6c7d1c23f
Author: Xin Li (Intel) <[email protected]>

KVM: VMX: Dump FRED context in dump_vmcs()

This commit adds FRED related VMCS fields to dump_vmcs() to dump FRED context for both guest and host states.

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +0 -0
index cd041381b322c..3a3315a7fc112 100644

[ ... ]

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -6784,6 +6789,16 @@ 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);

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

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	if (vmentry_ctl & VM_ENTRY_LOAD_IA32_FRED)
+		pr_err("FRED guest: config=0x%016llx, stack_levels=0x%016llx\n"
+		       "RSP0=0x%016llx, RSP1=0x%016llx\n"
+		       "RSP2=0x%016llx, RSP3=0x%016llx\n",
+		       vmcs_read64(GUEST_IA32_FRED_CONFIG),
+		       vmcs_read64(GUEST_IA32_FRED_STKLVLS),
+		       vmx_read_guest_fred_rsp0(vmx),
+		       vmcs_read64(GUEST_IA32_FRED_RSP1),
+		       vmcs_read64(GUEST_IA32_FRED_RSP2),
+		       vmcs_read64(GUEST_IA32_FRED_RSP3));

[Severity: Low]
Does this guest context dump in dump_vmcs() miss the FRED Shadow Stack Pointer fields?

It looks like GUEST_IA32_FRED_SSP1, GUEST_IA32_FRED_SSP2, and GUEST_IA32_FRED_SSP3 are omitted from the diagnostic output. Since this is dumping the FRED state when kvm_intel.dump_invalid_vmcs=1 is set, should the SSP fields be included to ensure the diagnostic information is complete?

[ ... ]

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +0 -0
@@ -6835,6 +6850,16 @@ 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));

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

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+	if (secondary_vmexit_ctl & SECONDARY_VM_EXIT_LOAD_IA32_FRED)
+		pr_err("FRED host: config=0x%016llx, stack_levels=0x%016llx\n"
+		       "RSP0=0x%016lx, RSP1=0x%016llx\n"
+		       "RSP2=0x%016llx, RSP3=0x%016llx\n",
+		       vmcs_read64(HOST_IA32_FRED_CONFIG),
+		       vmcs_read64(HOST_IA32_FRED_STKLVLS),
+		       (unsigned long)task_stack_page(current) + THREAD_SIZE,
+		       vmcs_read64(HOST_IA32_FRED_RSP1),
+		       vmcs_read64(HOST_IA32_FRED_RSP2),
+		       vmcs_read64(HOST_IA32_FRED_RSP3));

[Severity: Low]
Similarly, does the host context dump also miss the equivalent HOST_IA32_FRED_SSP1, HOST_IA32_FRED_SSP2, and HOST_IA32_FRED_SSP3 fields?

While this omission doesn't affect runtime correctness, including them alongside the RSP fields might be helpful for full diagnostic visibility.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
#67 lore raw

PATCH v10 19/28 KVM: x86: Advertise support for FRED

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Advertise support for FRED to userspace after changes required to enable FRED in a KVM guest are in place.

---
v10:
- kvm_cpu_cap_clear(X86_FEATURE_FRED) in svm_set_cpu_caps() (Chao).

---
 arch/x86/kvm/cpuid.c   | 1 +
 arch/x86/kvm/svm/svm.c | 3 +++
 2 files changed, 4 insertions(+)
arch/x86/kvm/cpuid.c +1 -0
index ddb022cb203a..5682bacdfd32 100644
@@ -1034,6 +1034,7 @@ void kvm_initialize_cpu_caps(void)
 		F(FSRS),
 		F(FSRC),
 		F(WRMSRNS),
+		X86_64_F(FRED),
 		X86_64_F(LKGS),
 		F(AMX_FP16),
 		F(AVX_IFMA),
arch/x86/kvm/svm/svm.c +3 -0
index f254a5ff570d..dd19c7b4e904 100644
@@ -5518,6 +5518,9 @@ static __init void svm_set_cpu_caps(void)
 
 	kvm_cpu_cap_clear(X86_FEATURE_IBT);
 
+	/* SVM FRED virtualization not implemented yet */
+	kvm_cpu_cap_clear(X86_FEATURE_FRED);
+
 	/* CPUID 0x80000001 and 0x8000000A (SVM features) */
 	if (nested) {
 		kvm_cpu_cap_set(X86_FEATURE_SVM);
Signature · 1 line
2.43.0
#68 lore raw

Re: [PATCH v10 19/28] KVM: x86: Advertise support for FRED

Quoted 8 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Advertise support for FRED to userspace after changes required to enable FRED in a KVM guest are in place.

The code change itself looks good to me.
But this patch should be moved after patch 25.

X86_CR4_FRED is added to nested.msrs.cr4_fixed1 in patch 25, before that if the L1 guest enables FRED, it will break the nested case when do VMXON, which checks nested_host_cr4_valid() and it will fail during the bisect window before patch 25.

Quoted 34 lines

---
v10:
- kvm_cpu_cap_clear(X86_FEATURE_FRED) in svm_set_cpu_caps() (Chao).

---
 arch/x86/kvm/cpuid.c   | 1 +
 arch/x86/kvm/svm/svm.c | 3 +++
 2 files changed, 4 insertions(+)
arch/x86/kvm/cpuid.c +1 -0
index ddb022cb203a..5682bacdfd32 100644
@@ -1034,6 +1034,7 @@ void kvm_initialize_cpu_caps(void)
 		F(FSRS),
 		F(FSRC),
 		F(WRMSRNS),
+		X86_64_F(FRED),
 		X86_64_F(LKGS),
 		F(AMX_FP16),
 		F(AVX_IFMA),
arch/x86/kvm/svm/svm.c +3 -0
index f254a5ff570d..dd19c7b4e904 100644
@@ -5518,6 +5518,9 @@ static __init void svm_set_cpu_caps(void)
 
 	kvm_cpu_cap_clear(X86_FEATURE_IBT);
 
+	/* SVM FRED virtualization not implemented yet */
+	kvm_cpu_cap_clear(X86_FEATURE_FRED);
+
 	/* CPUID 0x80000001 and 0x8000000A (SVM features) */
 	if (nested) {
 		kvm_cpu_cap_set(X86_FEATURE_SVM);
#69 lore raw

Re: [PATCH v10 19/28] KVM: x86: Advertise support for FRED

Quoted 10 lines · Binbin Wu
Quoted 8 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Advertise support for FRED to userspace after changes required to enable FRED in a KVM guest are in place.

Quoted 8 lines

The code change itself looks good to me.
But this patch should be moved after patch 25.

X86_CR4_FRED is added to nested.msrs.cr4_fixed1 in patch 25, before that if the L1 guest enables FRED, it will break the nested case when do VMXON, which checks nested_host_cr4_valid() and it will fail during the bisect window before patch 25.

Good catch. Instead of moving this patch after the nested VMX support, I am wondering if we could reorganize the patches slightly differently so that the nested support can be split up from the L1 guest support.

The series is getting a bit bulky. I am trying to split this series into smaller parts to make it easier to review. Planning to reply to Chang email soon where he also suggested this.

#70 lore raw

PATCH v10 20/28 KVM: nVMX: Enable support for secondary VM exit controls

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Add support for secondary VM exit controls in nested VMX to facilitate future FRED integration.

---
v10:
- Add MSR_IA32_VMX_EXIT_CTLS2 to emulated_msrs_all[] for live migration. (Chao Gao)
- Reject vmcs12's secondary VM exit controls that KVM doesn't advertise to L1 in MSR_IA32_VMX_EXIT_CTLS2.

---
 arch/x86/kvm/msrs.c             |  1 +
 arch/x86/kvm/msrs.h             |  2 +-
 arch/x86/kvm/vmx/capabilities.h |  1 +
 arch/x86/kvm/vmx/nested.c       | 29 ++++++++++++++++++++++++++++-
 arch/x86/kvm/vmx/nested.h       |  5 +++++
 arch/x86/kvm/vmx/vmcs12.c       |  1 +
 arch/x86/kvm/vmx/vmcs12.h       |  3 ++-
 7 files changed, 39 insertions(+), 3 deletions(-)
arch/x86/kvm/msrs.c +1 -0
index 9eabb7b02cb5..3260bddb5f52 100644
@@ -317,6 +317,7 @@ static const u32 emulated_msrs_all[] = {
 	MSR_IA32_VMX_PROCBASED_CTLS2,
 	MSR_IA32_VMX_EPT_VPID_CAP,
 	MSR_IA32_VMX_VMFUNC,
+	MSR_IA32_VMX_EXIT_CTLS2,
 
 	MSR_K7_HWCR,
 	MSR_KVM_POLL_CONTROL,
arch/x86/kvm/msrs.h +1 -1
index 7cc182a15b3b..845d2cbe80e5 100644
@@ -31,7 +31,7 @@ static inline void kvm_pr_unimpl_rdmsr(struct kvm_vcpu *vcpu, u32 msr)
  * 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
 
 /*
  * KVM's internal, non-ABI indices for synthetic MSRs. The values themselves
arch/x86/kvm/vmx/capabilities.h +1 -0
index 95d22a54f856..9cca65b226fd 100644
@@ -36,6 +36,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 +28 -1
index 151873407abd..6576935b9d43 100644
@@ -1596,6 +1596,11 @@ int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
 			return -EINVAL;
 		vmx->nested.msrs.vmfunc_controls = data;
 		return 0;
+	case MSR_IA32_VMX_EXIT_CTLS2:
+		if (data & ~vmcs_config.nested.secondary_exit_ctls)
+			return -EINVAL;
+		vmx->nested.msrs.secondary_exit_ctls = data;
+		return 0;
 	default:
 		/*
 		 * The rest of the VMX capability MSRs do not support restore.
@@ -1635,6 +1640,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(
@@ -2576,6 +2584,9 @@ 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)
+		secondary_vm_exit_controls_set(vmx, __secondary_vm_exit_controls_get(vmcs01));
+
 	/*
 	 * Interrupt/Exception Fields
 	 */
@@ -3040,6 +3051,11 @@ static int nested_check_vm_exit_controls(struct kvm_vcpu *vcpu,
 	    CC(nested_vmx_check_exit_msr_switch_controls(vcpu, vmcs12)))
 		return -EINVAL;
 
+	if (nested_cpu_has_secondary_vm_exit_controls(vmcs12) &&
+	    CC(vmcs12->secondary_vm_exit_controls &
+	       ~vmx->nested.msrs.secondary_exit_ctls))
+		return -EINVAL;
+
 	return 0;
 }
 
@@ -7152,7 +7168,8 @@ 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_LOAD_CET_STATE;
+		VM_EXIT_CLEAR_BNDCFGS | VM_EXIT_LOAD_CET_STATE |
+		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 |
@@ -7165,6 +7182,16 @@ static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
 
 	/* We support free control of debug control saving. */
 	msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
+
+	if (msrs->exit_ctls_high & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) {
+		msrs->secondary_exit_ctls = vmcs_conf->vmexit_2nd_ctrl;
+		/*
+		 * As the secondary VM exit control is always loaded, do not
+		 * advertise any feature in it to nVMX until its nVMX support
+		 * is ready.
+		 */
+		msrs->secondary_exit_ctls &= 0;
+	}
 }
 
 static void nested_vmx_setup_entry_ctls(struct vmcs_config *vmcs_conf,
arch/x86/kvm/vmx/nested.h +5 -0
index c6de848bd9ce..371fc3498b12 100644
@@ -247,6 +247,11 @@ static inline bool nested_cpu_has_save_preemption_timer(struct vmcs12 *vmcs12)
 	    VM_EXIT_SAVE_VMX_PREEMPTION_TIMER;
 }
 
+static inline bool nested_cpu_has_secondary_vm_exit_controls(struct vmcs12 *vmcs12)
+{
+	return vmcs12->vm_exit_controls & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS;
+}
+
 static inline bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
 {
 	return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
arch/x86/kvm/vmx/vmcs12.c +1 -0
index 1ebe67c384ad..9d64a89aff00 100644
@@ -66,6 +66,7 @@ static const u16 kvm_supported_vmcs12_field_offsets[] __initconst = {
 	FIELD64(HOST_IA32_PAT, host_ia32_pat),
 	FIELD64(HOST_IA32_EFER, host_ia32_efer),
 	FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
+	FIELD64(SECONDARY_VM_EXIT_CONTROLS, secondary_vm_exit_controls),
 	FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
 	FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
 	FIELD(EXCEPTION_BITMAP, exception_bitmap),
arch/x86/kvm/vmx/vmcs12.h +2 -1
index 21cd1b75e4fd..bb2f406be63d 100644
@@ -71,7 +71,7 @@ struct __packed vmcs12 {
 	u64 pml_address;
 	u64 encls_exiting_bitmap;
 	u64 tsc_multiplier;
-	u64 padding64[1]; /* room for future expansion */
+	u64 secondary_vm_exit_controls;
 	/*
 	 * To allow migration of L1 (complete with its L2 guests) between
 	 * machines of different natural widths (32 or 64 bit), we cannot have
@@ -261,6 +261,7 @@ static inline void vmx_check_vmcs12_offsets(void)
 	CHECK_OFFSET(pml_address, 312);
 	CHECK_OFFSET(encls_exiting_bitmap, 320);
 	CHECK_OFFSET(tsc_multiplier, 328);
+	CHECK_OFFSET(secondary_vm_exit_controls, 336);
 	CHECK_OFFSET(cr0_guest_host_mask, 344);
 	CHECK_OFFSET(cr4_guest_host_mask, 352);
 	CHECK_OFFSET(cr0_read_shadow, 360);
Signature · 1 line
2.43.0
#72 lore raw

PATCH v10 21/28 KVM: nVMX: Handle FRED VMCS fields in nested VMX context

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Extend nested VMX context management to include FRED-related VMCS fields, enabling proper handling of FRED state during nested virtualization.

Because KVM always sets SECONDARY_VM_EXIT_SAVE_IA32_FRED, FRED MSRs are always saved to vmcs02. However an L1 VMM may choose to clear this bit, i.e., not to save FRED MSRs to vmcs12. This is not a problem when the L1 VMM sets SECONDARY_VM_EXIT_LOAD_IA32_FRED, as KVM then immediately loads host FRED MSRs of vmcs12 to guest FRED MSRs of vmcs01. However if the L1 VMM clears SECONDARY_VM_EXIT_LOAD_IA32_FRED, KVM should retain FRED MSRs to run the L1 VMM.

To propagate guest FRED MSRs from vmcs02 to vmcs01, save them in sync_vmcs02_to_vmcs12() regardless of whether SECONDARY_VM_EXIT_SAVE_IA32_FRED is set in vmcs12. Then, use the saved values to set guest FRED MSRs in vmcs01 within load_vmcs12_host_state() when !nested_cpu_load_host_fred_state().

---
v10:
- Simplify nested FRED MSRs update with read/write helpers (Chao).
- Add other FRED MSRS to MSR bitmap nested filtering (Chao).
- Add {ORIGINAL,INJECTED}_EVENT_DATA to shadow fields in a separate patch (Sean).
- Add a new parameter to load_vmcs12_host_state() to indicate the call is from a failed VM entry.
- Update exception status member variable nested to is_nested (Sean).

v9:
- Rebase to kvm-x86/next.
- Guard FRED state save/restore with guest_cpu_cap_has(vcpu, X86_FEATURE_FRED) (syzbot & Chao).

---
 arch/x86/kvm/vmx/capabilities.h |   5 ++
 arch/x86/kvm/vmx/nested.c       | 107 ++++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/nested.h       |  17 +++++
 arch/x86/kvm/vmx/vmcs.h         |  11 ++++
 arch/x86/kvm/vmx/vmcs12.c       |  18 ++++++
 arch/x86/kvm/vmx/vmcs12.h       |  39 ++++++++++++
 arch/x86/kvm/vmx/vmx.h          |  23 +++++++
 7 files changed, 214 insertions(+), 6 deletions(-)
arch/x86/kvm/vmx/capabilities.h +5 -0
index 9cca65b226fd..74456f4533e9 100644
@@ -82,6 +82,11 @@ static inline bool cpu_has_vmx_basic_no_hw_errcode_cc(void)
 	return	vmcs_config.basic & VMX_BASIC_NO_HW_ERROR_CODE_CC;
 }
 
+static inline bool cpu_has_vmx_nested_exception(void)
+{
+	return vmcs_config.basic & VMX_BASIC_NESTED_EXCEPTION;
+}
+
 static inline bool cpu_has_virtual_nmis(void)
 {
 	return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS &&
arch/x86/kvm/vmx/nested.c +101 -6

211 lines not on this page · raw message

arch/x86/kvm/vmx/nested.h +17 -0
index 371fc3498b12..dc5a1e9cb4e9 100644
@@ -272,6 +272,23 @@ static inline bool nested_cpu_has_encls_exit(struct vmcs12 *vmcs12)
 	return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENCLS_EXITING);
 }
 
+static inline bool nested_cpu_load_guest_fred_state(struct vmcs12 *vmcs12)
+{
+	return vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_FRED;
+}
+
+static inline bool nested_cpu_save_guest_fred_state(struct vmcs12 *vmcs12)
+{
+	return nested_cpu_has_secondary_vm_exit_controls(vmcs12) &&
+	       vmcs12->secondary_vm_exit_controls & SECONDARY_VM_EXIT_SAVE_IA32_FRED;
+}
+
+static inline bool nested_cpu_load_host_fred_state(struct vmcs12 *vmcs12)
+{
+	return nested_cpu_has_secondary_vm_exit_controls(vmcs12) &&
+	       vmcs12->secondary_vm_exit_controls & SECONDARY_VM_EXIT_LOAD_IA32_FRED;
+}
+
 /*
  * if fixed0[i] == 1: val[i] must be 1
  * if fixed1[i] == 0: val[i] must be 0
arch/x86/kvm/vmx/vmcs.h +11 -0
index ca341c59bab1..58af10f73789 100644
@@ -52,6 +52,17 @@ struct vmcs_controls_shadow {
 	u64 tertiary_exec;
 };
 
+struct vmcs_fred_msrs {
+	u64 fred_config;
+	u64 fred_rsp1;
+	u64 fred_rsp2;
+	u64 fred_rsp3;
+	u64 fred_stklvls;
+	u64 fred_ssp1;
+	u64 fred_ssp2;
+	u64 fred_ssp3;
+};
+
 /*
  * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
  * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
arch/x86/kvm/vmx/vmcs12.c +18 -0
index 9d64a89aff00..837cb3d568c3 100644
@@ -67,6 +67,24 @@ static const u16 kvm_supported_vmcs12_field_offsets[] __initconst = {
 	FIELD64(HOST_IA32_EFER, host_ia32_efer),
 	FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
 	FIELD64(SECONDARY_VM_EXIT_CONTROLS, secondary_vm_exit_controls),
+	FIELD64(INJECTED_EVENT_DATA, injected_event_data),
+	FIELD64(ORIGINAL_EVENT_DATA, original_event_data),
+	FIELD64(GUEST_IA32_FRED_CONFIG, guest_ia32_fred_config),
+	FIELD64(GUEST_IA32_FRED_RSP1, guest_ia32_fred_rsp1),
+	FIELD64(GUEST_IA32_FRED_RSP2, guest_ia32_fred_rsp2),
+	FIELD64(GUEST_IA32_FRED_RSP3, guest_ia32_fred_rsp3),
+	FIELD64(GUEST_IA32_FRED_STKLVLS, guest_ia32_fred_stklvls),
+	FIELD64(GUEST_IA32_FRED_SSP1, guest_ia32_fred_ssp1),
+	FIELD64(GUEST_IA32_FRED_SSP2, guest_ia32_fred_ssp2),
+	FIELD64(GUEST_IA32_FRED_SSP3, guest_ia32_fred_ssp3),
+	FIELD64(HOST_IA32_FRED_CONFIG, host_ia32_fred_config),
+	FIELD64(HOST_IA32_FRED_RSP1, host_ia32_fred_rsp1),
+	FIELD64(HOST_IA32_FRED_RSP2, host_ia32_fred_rsp2),
+	FIELD64(HOST_IA32_FRED_RSP3, host_ia32_fred_rsp3),
+	FIELD64(HOST_IA32_FRED_STKLVLS, host_ia32_fred_stklvls),
+	FIELD64(HOST_IA32_FRED_SSP1, host_ia32_fred_ssp1),
+	FIELD64(HOST_IA32_FRED_SSP2, host_ia32_fred_ssp2),
+	FIELD64(HOST_IA32_FRED_SSP3, host_ia32_fred_ssp3),
 	FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
 	FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
 	FIELD(EXCEPTION_BITMAP, exception_bitmap),
arch/x86/kvm/vmx/vmcs12.h +39 -0
index bb2f406be63d..c4c5cd3722a5 100644
@@ -191,6 +191,27 @@ struct __packed vmcs12 {
 	u16 host_gs_selector;
 	u16 host_tr_selector;
 	u16 guest_pml_index;
+	u16 padding16[1]; /* align to 64-bit boundary */
+	struct vmcs_fred_msrs guest_fred_msrs;
+#define guest_ia32_fred_config	guest_fred_msrs.fred_config
+#define guest_ia32_fred_rsp1	guest_fred_msrs.fred_rsp1
+#define guest_ia32_fred_rsp2	guest_fred_msrs.fred_rsp2
+#define guest_ia32_fred_rsp3	guest_fred_msrs.fred_rsp3
+#define guest_ia32_fred_stklvls	guest_fred_msrs.fred_stklvls
+#define guest_ia32_fred_ssp1	guest_fred_msrs.fred_ssp1
+#define guest_ia32_fred_ssp2	guest_fred_msrs.fred_ssp2
+#define guest_ia32_fred_ssp3	guest_fred_msrs.fred_ssp3
+	struct vmcs_fred_msrs host_fred_msrs;
+#define host_ia32_fred_config	host_fred_msrs.fred_config
+#define host_ia32_fred_rsp1	host_fred_msrs.fred_rsp1
+#define host_ia32_fred_rsp2	host_fred_msrs.fred_rsp2
+#define host_ia32_fred_rsp3	host_fred_msrs.fred_rsp3
+#define host_ia32_fred_stklvls	host_fred_msrs.fred_stklvls
+#define host_ia32_fred_ssp1	host_fred_msrs.fred_ssp1
+#define host_ia32_fred_ssp2	host_fred_msrs.fred_ssp2
+#define host_ia32_fred_ssp3	host_fred_msrs.fred_ssp3
+	u64 injected_event_data;
+	u64 original_event_data;
 };
 
 /*
@@ -373,6 +394,24 @@ 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(guest_ia32_fred_config, 1000);
+	CHECK_OFFSET(guest_ia32_fred_rsp1, 1008);
+	CHECK_OFFSET(guest_ia32_fred_rsp2, 1016);
+	CHECK_OFFSET(guest_ia32_fred_rsp3, 1024);
+	CHECK_OFFSET(guest_ia32_fred_stklvls, 1032);
+	CHECK_OFFSET(guest_ia32_fred_ssp1, 1040);
+	CHECK_OFFSET(guest_ia32_fred_ssp2, 1048);
+	CHECK_OFFSET(guest_ia32_fred_ssp3, 1056);
+	CHECK_OFFSET(host_ia32_fred_config, 1064);
+	CHECK_OFFSET(host_ia32_fred_rsp1, 1072);
+	CHECK_OFFSET(host_ia32_fred_rsp2, 1080);
+	CHECK_OFFSET(host_ia32_fred_rsp3, 1088);
+	CHECK_OFFSET(host_ia32_fred_stklvls, 1096);
+	CHECK_OFFSET(host_ia32_fred_ssp1, 1104);
+	CHECK_OFFSET(host_ia32_fred_ssp2, 1112);
+	CHECK_OFFSET(host_ia32_fred_ssp3, 1120);
+	CHECK_OFFSET(injected_event_data, 1128);
+	CHECK_OFFSET(original_event_data, 1136);
 }
 
 extern u16 vmcs12_field_offsets[] __ro_after_init;
arch/x86/kvm/vmx/vmx.h +23 -0
index 14fd3f57d5c1..cc1e4038cd44 100644
@@ -182,6 +182,29 @@ struct nested_vmx {
 	u64 pre_vmenter_ssp;
 	u64 pre_vmenter_ssp_tbl;
 
+	/*
+	 * Used to snapshot FRED MSRs that may NOT be saved to vmcs12 as specified
+	 * in the VM-Exit controls of vmcs12 configured by L1 VMM.
+	 *
+	 * FRED MSRs are *always* saved into vmcs02 because KVM always sets
+	 * SECONDARY_VM_EXIT_SAVE_IA32_FRED.  However an L1 VMM may choose to clear
+	 * this bit, resulting in FRED MSRs not being propagated to vmcs12 from
+	 * vmcs02.  When the L1 VMM sets SECONDARY_VM_EXIT_LOAD_IA32_FRED, this is
+	 * not a problem, since KVM then immediately loads the host FRED MSRs of
+	 * vmcs12 to the guest FRED MSRs of vmcs01.
+	 *
+	 * But if the L1 VMM clears SECONDARY_VM_EXIT_LOAD_IA32_FRED, KVM should
+	 * retain the FRED MSRs, i.e., propagate the guest FRED MSRs of vmcs02 to
+	 * the guest FRED MSRs of vmcs01.
+	 *
+	 * This structure stores guest FRED MSRs that an L1 VMM opts not to save
+	 * during VM-Exits from L2 to L1.  These MSRs may still be retained for
+	 * running the L1 VMM if SECONDARY_VM_EXIT_LOAD_IA32_FRED is cleared in
+	 * vmcs12.
+	 */
+	struct vmcs_fred_msrs pre_vmenter_fred_msrs;
+	struct vmcs_fred_msrs at_vmexit_fred_msrs;
+
 	u16 vpid02;
 	u16 last_vpid;
 
Signature · 1 line
2.43.0
#73 lore raw

Re: [PATCH v10 21/28] KVM: nVMX: Handle FRED VMCS fields in nested VMX context

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] L2 guest state corruption: FRED MSRs leak across VMRESUME when L1 configures LOAD_IA32_FRED=1 and…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] L2 guest state corruption: FRED MSRs leak across VMRESUME when L1 configures LOAD_IA32_FRED=1 and SAVE_IA32_FRED=0.
- [Medium] Missing VM-entry consistency checks allow L1 to bypass guest FRED MSR validation and trigger hardware VM-entry failures. --

commit 057f971773a8afea0241cab2d4cb47bca7dc2643
Author: Xin Li (Intel) <[email protected]>
Subject: KVM: nVMX: Handle FRED VMCS fields in nested VMX context

Extend nested VMX context management to include FRED-related VMCS fields, enabling proper handling of FRED state during nested virtualization.

Quoted 4 lines
arch/x86/kvm/vmx/nested.c +0 -0
index 6576935b9d43f..83e846fb3fc8c 100644

[ ... ]

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

Quoted 9 lines
arch/x86/kvm/vmx/nested.c +4 -0
@@ -2755,6 +2792,10 @@ static void prepare_vmcs02_rare(struct vcpu_vmx *vmx, struct vmcs12 *vmcs12)
 				     vmcs12->guest_ssp, vmcs12->guest_ssp_tbl);
 
 	set_cr4_guest_host_mask(vmx);
+
+	if (guest_cpu_cap_has(&vmx->vcpu, X86_FEATURE_FRED) &&
+	    nested_cpu_load_guest_fred_state(vmcs12))
+		vmcs_write_fred_msrs(&vmcs12->guest_fred_msrs);
 }

[Severity: High]
Can this lead to L2 guest state corruption?

When L1 sets VM_ENTRY_LOAD_IA32_FRED=1 but VM_EXIT_SAVE_IA32_FRED=0, it expects L2's FRED MSRs to be reset to the values in vmcs12 on every VM-entry.

Because the vmcs02 update is placed here inside prepare_vmcs02_rare(), it is skipped on a clean VMRESUME operation. Since FRED MSRs are passed through to L2 (via the MSR bitmap), L2 can modify them directly without triggering a VM-exit.

Hardware saves these modified values to vmcs02 on VM-exit, but KVM does not sync them back to vmcs12 (because SAVE_IA32_FRED=0). On the next VMRESUME, prepare_vmcs02_rare() is bypassed, leaving the stale, modified L2 values in vmcs02. L2 will therefore inherit its previous modified state instead of the clean baseline values configured by L1 in vmcs12.

[ ... ]

[Severity: Medium]
Could KVM miss a VM-entry consistency check during FRED MSR validation?

Looking at nested_vmx_check_guest_state() in arch/x86/kvm/vmx/nested.c, the FRED MSR validation is nested under the ia32e condition:

	if (ia32e) {
		if (nested_cpu_load_guest_fred_state(vmcs12)) {
			if (CC(vmcs12->guest_ia32_fred_config & FRED_CONFIG_RESERVED) ||

If an L1 hypervisor sets VM_ENTRY_LOAD_IA32_FRED=1 but clears VM_ENTRY_IA32E_MODE=0, these checks bypass the validation of guest_ia32_fred_config and other FRED MSRs.

Additionally, KVM appears to lack the cross-control verification required by the SDM where LOAD_IA32_FRED=1 requires IA32E_MODE=1. As a result, KVM might attempt to VMLAUNCH vmcs02 with invalid state, which hardware rejects with a VM-instruction error and triggers the warn_on_missed_cc path.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
#74 lore raw

Re: [PATCH v10 21/28] KVM: nVMX: Handle FRED VMCS fields in nested VMX context

In reply to Sohil Mehta
Quoted 4 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Extend nested VMX context management to include FRED-related VMCS fields, enabling proper handling of FRED state during nested virtualization.

No strong preference, but for me this is a bit too thin to describe the overall change of this patch.

Quoted 32 lines

Because KVM always sets SECONDARY_VM_EXIT_SAVE_IA32_FRED, FRED MSRs are always saved to vmcs02. However an L1 VMM may choose to clear this bit, i.e., not to save FRED MSRs to vmcs12. This is not a problem when the L1 VMM sets SECONDARY_VM_EXIT_LOAD_IA32_FRED, as KVM then immediately loads host FRED MSRs of vmcs12 to guest FRED MSRs of vmcs01. However if the L1 VMM clears SECONDARY_VM_EXIT_LOAD_IA32_FRED, KVM should retain FRED MSRs to run the L1 VMM.

To propagate guest FRED MSRs from vmcs02 to vmcs01, save them in sync_vmcs02_to_vmcs12() regardless of whether SECONDARY_VM_EXIT_SAVE_IA32_FRED is set in vmcs12. Then, use the saved values to set guest FRED MSRs in vmcs01 within load_vmcs12_host_state() when !nested_cpu_load_host_fred_state().

---
v10:
- Simplify nested FRED MSRs update with read/write helpers (Chao).
- Add other FRED MSRS to MSR bitmap nested filtering (Chao).
- Add {ORIGINAL,INJECTED}_EVENT_DATA to shadow fields in a separate patch (Sean).
- Add a new parameter to load_vmcs12_host_state() to indicate the call is from a failed VM entry.
- Update exception status member variable nested to is_nested (Sean).

v9:
- Rebase to kvm-x86/next.
- Guard FRED state save/restore with guest_cpu_cap_has(vcpu, X86_FEATURE_FRED) (syzbot & Chao).
---

[...]

Quoted 19 lines
arch/x86/kvm/vmx/vmx.h +11 -0
index 14fd3f57d5c1..cc1e4038cd44 100644
@@ -182,6 +182,29 @@ struct nested_vmx {
 	u64 pre_vmenter_ssp;
 	u64 pre_vmenter_ssp_tbl;
 
+	/*
+	 * Used to snapshot FRED MSRs that may NOT be saved to vmcs12 as specified
+	 * in the VM-Exit controls of vmcs12 configured by L1 VMM.
+	 *
+	 * FRED MSRs are *always* saved into vmcs02 because KVM always sets
+	 * SECONDARY_VM_EXIT_SAVE_IA32_FRED.  However an L1 VMM may choose to clear
+	 * this bit, resulting in FRED MSRs not being propagated to vmcs12 from
+	 * vmcs02.  When the L1 VMM sets SECONDARY_VM_EXIT_LOAD_IA32_FRED, this is
+	 * not a problem, since KVM then immediately loads the host FRED MSRs of
+	 * vmcs12 to the guest FRED MSRs of vmcs01.
+	 *

arch/x86/kvm/vmx/vmx.h struct nested_vmx { · line 205

Quoted 10 lines
arch/x86/kvm/vmx/vmx.h +10 -0
+	 * But if the L1 VMM clears SECONDARY_VM_EXIT_LOAD_IA32_FRED, KVM should
+	 * retain the FRED MSRs, i.e., propagate the guest FRED MSRs of vmcs02 to
+	 * the guest FRED MSRs of vmcs01.
+	 *
+	 * This structure stores guest FRED MSRs that an L1 VMM opts not to save
+	 * during VM-Exits from L2 to L1.  These MSRs may still be retained for
+	 * running the L1 VMM if SECONDARY_VM_EXIT_LOAD_IA32_FRED is cleared in
+	 * vmcs12.
+	 */
+	struct vmcs_fred_msrs pre_vmenter_fred_msrs;> +	struct vmcs_fred_msrs at_vmexit_fred_msrs;

I understand that the two fields are both belong to FRED, but the comment blocks are for at_vmexit_fred_msrs, not for pre_vmenter_fred_msrs.

Should pre_vmenter_fred_msrs be put together with the other pre_vmenter_xxx, since the comments above the pre_vmenter_xxx explains why these fields are needed.

Quoted 4 lines
arch/x86/kvm/vmx/vmx.h +1 -0
+
 	u16 vpid02;
 	u16 last_vpid;
 
#75 lore raw

Re: [PATCH v10 21/28] KVM: nVMX: Handle FRED VMCS fields in nested VMX context

Quoted 25 lines · Binbin Wu
Quoted 11 lines
arch/x86/kvm/vmx/vmx.h +11 -0
+	/*
+	 * Used to snapshot FRED MSRs that may NOT be saved to vmcs12 as specified
+	 * in the VM-Exit controls of vmcs12 configured by L1 VMM.
+	 *
+	 * FRED MSRs are *always* saved into vmcs02 because KVM always sets
+	 * SECONDARY_VM_EXIT_SAVE_IA32_FRED.  However an L1 VMM may choose to clear
+	 * this bit, resulting in FRED MSRs not being propagated to vmcs12 from
+	 * vmcs02.  When the L1 VMM sets SECONDARY_VM_EXIT_LOAD_IA32_FRED, this is
+	 * not a problem, since KVM then immediately loads the host FRED MSRs of
+	 * vmcs12 to the guest FRED MSRs of vmcs01.
+	 *

arch/x86/kvm/vmx/vmx.h struct nested_vmx {

Quoted 10 lines
arch/x86/kvm/vmx/vmx.h +10 -0
+	 * But if the L1 VMM clears SECONDARY_VM_EXIT_LOAD_IA32_FRED, KVM should
+	 * retain the FRED MSRs, i.e., propagate the guest FRED MSRs of vmcs02 to
+	 * the guest FRED MSRs of vmcs01.
+	 *
+	 * This structure stores guest FRED MSRs that an L1 VMM opts not to save
+	 * during VM-Exits from L2 to L1.  These MSRs may still be retained for
+	 * running the L1 VMM if SECONDARY_VM_EXIT_LOAD_IA32_FRED is cleared in
+	 * vmcs12.
+	 */
+	struct vmcs_fred_msrs pre_vmenter_fred_msrs;> +	struct vmcs_fred_msrs at_vmexit_fred_msrs;

I understand that the two fields are both belong to FRED, but the comment blocks are for at_vmexit_fred_msrs, not for pre_vmenter_fred_msrs.

Quoted 3 lines

Should pre_vmenter_fred_msrs be put together with the other pre_vmenter_xxx, since the comments above the pre_vmenter_xxx explains why these fields are needed.

Sure, I'll do that in the next version.

#76 lore raw

PATCH v10 22/28 KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts

In reply to Sohil Mehta

From: Xin Li <[email protected]>

Prevent L1 from accessing the ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA VMCS fields via VMREAD or VMWRITE when FRED support is disabled or not present in KVM.

---
v10:
- Split out of "KVM: nVMX: Guard SHADOW_FIELD_R[OW] macros with VMX feature checks" and renamed (Sean).

---
 arch/x86/kvm/vmx/vmcs12.c | 3 +++
 1 file changed, 3 insertions(+)
arch/x86/kvm/vmx/vmcs12.c +3 -0
index 837cb3d568c3..67c730e31465 100644
@@ -222,6 +222,9 @@ static __init bool cpu_has_vmcs12_field(unsigned int idx)
 	case HOST_SSP:
 	case HOST_INTR_SSP_TABLE:
 		return cpu_has_load_cet_ctrl();
+	VMCS12_CASE64(ORIGINAL_EVENT_DATA):
+	VMCS12_CASE64(INJECTED_EVENT_DATA):
+		return cpu_has_vmx_fred();
 
 	/* KVM always emulates PML and the VMX preemption timer in software. */
 	case GUEST_PML_INDEX:
Signature · 1 line
2.43.0
#77 lore raw

Re: [PATCH v10 22/28] KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Incomplete restrictions for new VMCS fields exposing unsupported fields to L1 guests. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Incomplete restrictions for new VMCS fields exposing unsupported fields to L1 guests. --

commit 54389ae57bfff5e56dff4d41b4c42f872fb1693f
Author: Xin Li <[email protected]>

KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts

This commit restricts L1 guest access to the ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA VMCS fields via VMREAD or VMWRITE when FRED support is disabled. It updates cpu_has_vmcs12_field in arch/x86/kvm/vmx/vmcs12.c to check cpu_has_vmx_fred for these specific fields.

Quoted 3 lines
arch/x86/kvm/vmx/vmcs12.c +0 -0

[ ... ]

arch/x86/kvm/vmx/vmcs12.c

Quoted 13 lines
arch/x86/kvm/vmx/vmcs12.c +3 -0
@@ -222,6 +222,9 @@ static __init bool cpu_has_vmcs12_field(unsigned int idx)
 	case HOST_SSP:
 	case HOST_INTR_SSP_TABLE:
 		return cpu_has_load_cet_ctrl();
+	VMCS12_CASE64(ORIGINAL_EVENT_DATA):
+	VMCS12_CASE64(INJECTED_EVENT_DATA):
+		return cpu_has_vmx_fred();
 
 	/* KVM always emulates PML and the VMX preemption timer in software. */
 	case GUEST_PML_INDEX:
arch/x86/kvm/vmx/vmcs12.c +0 -0
 	case VMX_PREEMPTION_TIMER_VALUE:
 	default:
 		return true;

[Severity: Medium]
Does this code leave other FRED-related fields exposed to L1?

While this restricts ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA, it appears to omit all GUEST_IA32_FRED_*, HOST_IA32_FRED_*, and SECONDARY_VM_EXIT_CONTROLS fields.

Because cpu_has_vmcs12_field falls through to the default case and returns true for unhandled fields, wouldn't these remaining FRED MSR fields and SECONDARY_VM_EXIT_CONTROLS be unconditionally exposed to an L1 guest?

If a nested hypervisor (L1) executes VMREAD or VMWRITE on these specific fields (for example, GUEST_IA32_FRED_CONFIG) on a host without FRED or secondary VM-exit controls, KVM intercepts the instruction and calls vmcs12_read_any or vmcs12_write_any.

Because they are incorrectly populated in the vmcs12_field_offsets array by default, it seems they would be allowed instead of properly generating a VMfail (VMXERR_UNSUPPORTED_VMCS_COMPONENT), violating the CPUID-based capability masking.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
#78 lore raw

Re: [PATCH v10 22/28] KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts

In reply to Sohil Mehta
Quoted 5 lines · Sohil Mehta

From: Xin Li <[email protected]>

Prevent L1 from accessing the ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA VMCS fields via VMREAD or VMWRITE when FRED support is disabled or not present in KVM.

I think the change log should tell why the patch only restricts event data fields.

Quoted 25 lines

---
v10:
- Split out of "KVM: nVMX: Guard SHADOW_FIELD_R[OW] macros with VMX feature checks" and renamed (Sean).

---
 arch/x86/kvm/vmx/vmcs12.c | 3 +++
 1 file changed, 3 insertions(+)
arch/x86/kvm/vmx/vmcs12.c +3 -0
index 837cb3d568c3..67c730e31465 100644
@@ -222,6 +222,9 @@ static __init bool cpu_has_vmcs12_field(unsigned int idx)
 	case HOST_SSP:
 	case HOST_INTR_SSP_TABLE:
 		return cpu_has_load_cet_ctrl();
+	VMCS12_CASE64(ORIGINAL_EVENT_DATA):
+	VMCS12_CASE64(INJECTED_EVENT_DATA):
+		return cpu_has_vmx_fred();
 
 	/* KVM always emulates PML and the VMX preemption timer in software. */
 	case GUEST_PML_INDEX:
#79 lore raw

Re: [PATCH v10 22/28] KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts

Quoted 9 lines · Binbin Wu
Quoted 5 lines · Sohil Mehta

From: Xin Li <[email protected]>

Prevent L1 from accessing the ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA VMCS fields via VMREAD or VMWRITE when FRED support is disabled or not present in KVM.

I think the change log should tell why the patch only restricts event data fields.

Sean preferred an "unconditional" rule for cpu_has_vmcs12_field() [1], i.e., new fields are added there whether or not they are shadowed. Following that rule, this patch should cover all FRED VMCS fields.

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

Quoted 27 lines
Quoted 26 lines

---
v10:
- Split out of "KVM: nVMX: Guard SHADOW_FIELD_R[OW] macros with VMX feature checks" and renamed (Sean).

---
 arch/x86/kvm/vmx/vmcs12.c | 3 +++
 1 file changed, 3 insertions(+)
arch/x86/kvm/vmx/vmcs12.c +3 -0
index 837cb3d568c3..67c730e31465 100644
@@ -222,6 +222,9 @@ static __init bool cpu_has_vmcs12_field(unsigned int idx)
 	case HOST_SSP:
 	case HOST_INTR_SSP_TABLE:
 		return cpu_has_load_cet_ctrl();
+	VMCS12_CASE64(ORIGINAL_EVENT_DATA):
+	VMCS12_CASE64(INJECTED_EVENT_DATA):
+		return cpu_has_vmx_fred();
 
 	/* KVM always emulates PML and the VMX preemption timer in software. */
 	case GUEST_PML_INDEX:
#80 lore raw

Re: [PATCH v10 22/28] KVM: nVMX: Restrict event data VMCS fields to FRED-supported hosts

Quoted 8 lines · Chao Gao
Quoted 7 lines · Binbin Wu
Quoted 5 lines · Sohil Mehta

From: Xin Li <[email protected]>

Prevent L1 from accessing the ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA VMCS fields via VMREAD or VMWRITE when FRED support is disabled or not present in KVM.

Quoted 7 lines
Quoted 2 lines

I think the change log should tell why the patch only restricts event data fields.

Sean preferred an "unconditional" rule for cpu_has_vmcs12_field() [1], i.e., new fields are added there whether or not they are shadowed. Following that rule, this patch should cover all FRED VMCS fields.

Sure, will add all the FRED fields.

I think we should also include the secondary VM exit controls case in the nVMX patch that adds it:

	VMCS12_CASE64(SECONDARY_VM_EXIT_CONTROLS):
		return cpu_has_secondary_vmexit_ctrls();
#81 lore raw

PATCH v10 23/28 KVM: nVMX: Shadow ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA fields

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Add ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA to the list of shadowed VMCS fields.

Shadowing these fields allows the L1 hypervisor to access them without triggering a VM-exit to L0, optimizing performance for nested virtualization workloads that frequently query or inject event data.

---
v10:
- Split out of "KVM: nVMX: Guard SHADOW_FIELD_R[OW] macros with VMX feature checks" (Sean).

---
 arch/x86/kvm/vmx/vmcs_shadow_fields.h | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/vmx/vmcs_shadow_fields.h +4 -0
index 67e821c2be6d..bdd56f3ca6c3 100644
@@ -74,6 +74,10 @@ SHADOW_FIELD_RW(HOST_GS_BASE, host_gs_base)
 /* 64-bit */
 SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS, guest_physical_address)
 SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS_HIGH, guest_physical_address)
+SHADOW_FIELD_RO(ORIGINAL_EVENT_DATA, original_event_data)
+SHADOW_FIELD_RO(ORIGINAL_EVENT_DATA_HIGH, original_event_data)
+SHADOW_FIELD_RW(INJECTED_EVENT_DATA, injected_event_data)
+SHADOW_FIELD_RW(INJECTED_EVENT_DATA_HIGH, injected_event_data)
 #endif
 
 #undef SHADOW_FIELD_RO
Signature · 1 line
2.43.0
Reviewed-by on v10 23/28
#82 lore raw

Re: [PATCH v10 23/28] KVM: nVMX: Shadow ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA fields

Quoted 11 lines · Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Add ORIGINAL_EVENT_DATA and INJECTED_EVENT_DATA to the list of shadowed VMCS fields.

Shadowing these fields allows the L1 hypervisor to access them without triggering a VM-exit to L0, optimizing performance for nested virtualization workloads that frequently query or inject event data.

Quoted 23 lines

---
v10:
- Split out of "KVM: nVMX: Guard SHADOW_FIELD_R[OW] macros with VMX feature checks" (Sean).

---
 arch/x86/kvm/vmx/vmcs_shadow_fields.h | 4 ++++
 1 file changed, 4 insertions(+)
arch/x86/kvm/vmx/vmcs_shadow_fields.h +4 -0
index 67e821c2be6d..bdd56f3ca6c3 100644
@@ -74,6 +74,10 @@ SHADOW_FIELD_RW(HOST_GS_BASE, host_gs_base)
 /* 64-bit */
 SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS, guest_physical_address)
 SHADOW_FIELD_RO(GUEST_PHYSICAL_ADDRESS_HIGH, guest_physical_address)
+SHADOW_FIELD_RO(ORIGINAL_EVENT_DATA, original_event_data)
+SHADOW_FIELD_RO(ORIGINAL_EVENT_DATA_HIGH, original_event_data)
+SHADOW_FIELD_RW(INJECTED_EVENT_DATA, injected_event_data)
+SHADOW_FIELD_RW(INJECTED_EVENT_DATA_HIGH, injected_event_data)
 #endif
 
 #undef SHADOW_FIELD_RO
#83 lore raw

PATCH v10 24/28 KVM: nVMX: Validate FRED-related VMCS fields

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Extend nested VMX field validation to include FRED-specific VMCS fields, mirroring hardware behavior.

This enables support for nested FRED by ensuring control and guest/host state fields are properly checked.

---
v10:
- Use has_nested_exception to describe the event being injected rather than the CPU capability, for consistency with has_error_code (Chao).
- Restructure the interruption-information checks into a switch on the interruption type (Chao).
- Add a CC() statement to the reserved interruption type check so a VM-entry failure can be correlated with a specific check (Chao).
- Reject the nested-exception bit (bit 13) for interruption types other than hardware exception, and fold in the nested-exception capability check.
- Bound the "other event" vector explicitly instead of relying on a default arm.
- Reject a zero VM-entry instruction length when injecting SYSCALL or SYSENTER if the vCPU doesn't enumerate zero-length instruction injection.

---
 arch/x86/kvm/vmx/nested.c | 119 +++++++++++++++++++++++++++++++++-----
 arch/x86/kvm/vmx/nested.h |   5 ++
 2 files changed, 111 insertions(+), 13 deletions(-)
arch/x86/kvm/vmx/nested.c +106 -13
index 83e846fb3fc8..3e0a1ed6440d 100644
@@ -3111,6 +3111,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,
@@ -3128,22 +3130,11 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 		u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
 		u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
 		bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
+		bool has_nested_exception = intr_info & INTR_INFO_NESTED_EXCEPTION_MASK;
 		bool urg = nested_cpu_has2(vmcs12,
 					   SECONDARY_EXEC_UNRESTRICTED_GUEST);
 		bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
 
-		/* VM-entry interruption-info field: interruption type */
-		if (CC(intr_type == INTR_TYPE_RESERVED) ||
-		    CC(intr_type == INTR_TYPE_OTHER_EVENT &&
-		       !nested_cpu_supports_monitor_trap_flag(vcpu)))
-			return -EINVAL;
-
-		/* 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))
-			return -EINVAL;
-
 		/*
 		 * Cannot deliver error code in real mode or if the interrupt
 		 * type is not hardware exception. For other cases, do the
@@ -3167,8 +3158,28 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 		if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
 			return -EINVAL;
 
-		/* VM-entry instruction length */
+		if (CC(intr_type == INTR_TYPE_RESERVED))
+			return -EINVAL;
+
+		/*
+		 * Only for hardware exceptions and when the CPU enumerates
+		 * VMX nested-exception support, bit 13 (indicating a nested
+		 * exception) has value 1. Otherwise it is reserved.
+		 */
+		if (CC(has_nested_exception &&
+		       (intr_type != INTR_TYPE_HARD_EXCEPTION ||
+			!nested_cpu_has_nested_exception(vcpu))))
+			return -EINVAL;
+
 		switch (intr_type) {
+		case INTR_TYPE_NMI_INTR:
+			if (CC(vector != NMI_VECTOR))
+				return -EINVAL;
+			break;
+		case INTR_TYPE_HARD_EXCEPTION:
+			if (CC(vector > 31))
+				return -EINVAL;
+			break;
 		case INTR_TYPE_SOFT_EXCEPTION:
 		case INTR_TYPE_SOFT_INTR:
 		case INTR_TYPE_PRIV_SW_EXCEPTION:
@@ -3176,6 +3187,28 @@ 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 (CC(vector > 2))
+				return -EINVAL;
+
+			switch (vector) {
+			case 0:
+				if (CC(!nested_cpu_supports_monitor_trap_flag(vcpu)))
+					return -EINVAL;
+				break;
+			case 1:
+			case 2:
+				if (CC(!fred_enabled))
+					return -EINVAL;
+				if (CC(vmcs12->vm_entry_instruction_len > X86_MAX_INSTRUCTION_LENGTH))
+					return -EINVAL;
+				if (CC(vmcs12->vm_entry_instruction_len == 0 &&
+				       !nested_cpu_has_zero_length_injection(vcpu)))
+					return -EINVAL;
+				break;
+			}
+			break;
 		}
 	}
 
@@ -3262,9 +3295,27 @@ static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
 	if (ia32e) {
 		if (CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
 			return -EINVAL;
+		if (nested_cpu_load_host_fred_state(vmcs12)) {
+			if (CC(vmcs12->host_ia32_fred_config & FRED_CONFIG_RESERVED) ||
+			    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_msr_address(vmcs12->host_ia32_fred_config & PAGE_MASK, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_rsp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_rsp2, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_rsp3, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_ssp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_ssp2, vcpu)) ||
+			    CC(is_noncanonical_msr_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;
 	}
@@ -3447,6 +3498,48 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
 	     CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
 		return -EINVAL;
 
+	if (ia32e) {
+		if (nested_cpu_load_guest_fred_state(vmcs12)) {
+			if (CC(vmcs12->guest_ia32_fred_config & FRED_CONFIG_RESERVED) ||
+			    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_msr_address(vmcs12->guest_ia32_fred_config & PAGE_MASK, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_rsp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_rsp2, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_rsp3, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_ssp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_ssp2, vcpu)) ||
+			    CC(is_noncanonical_msr_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;
+
+			switch (ss_dpl) {
+			case 0:
+				if (CC(!(vmcs12->guest_cs_ar_bytes & VMX_AR_L_MASK)))
+					return -EINVAL;
+				break;
+			case 3:
+				if (CC(vmcs12->guest_rflags & X86_EFLAGS_IOPL))
+					return -EINVAL;
+				if (CC(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_STI))
+					return -EINVAL;
+				break;
+			}
+		}
+	} else {
+		if (CC(vmcs12->guest_cr4 & X86_CR4_FRED))
+			return -EINVAL;
+	}
+
 	if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_CET_STATE) {
 		if (nested_vmx_check_cet_state_common(vcpu, vmcs12->guest_s_cet,
 						      vmcs12->guest_ssp,
arch/x86/kvm/vmx/nested.h +5 -0
index dc5a1e9cb4e9..551121824128 100644
@@ -334,6 +334,11 @@ static inline bool nested_cpu_has_no_hw_errcode_cc(struct kvm_vcpu *vcpu)
 	return to_vmx(vcpu)->nested.msrs.basic & VMX_BASIC_NO_HW_ERROR_CODE_CC;
 }
 
+static inline bool nested_cpu_has_nested_exception(struct kvm_vcpu *vcpu)
+{
+	return to_vmx(vcpu)->nested.msrs.basic & VMX_BASIC_NESTED_EXCEPTION;
+}
+
 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
 #define nested_guest_cr4_valid	nested_cr4_valid
 #define nested_host_cr4_valid	nested_cr4_valid
Signature · 1 line
2.43.0
#84 lore raw

Re: [PATCH v10 24/28] KVM: nVMX: Validate FRED-related VMCS fields

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Missing cross-field consistency checks for FRED VM-entry and VM-exit controls against IA-32e mode…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Missing cross-field consistency checks for FRED VM-entry and VM-exit controls against IA-32e mode, allowing invalid VMCS state to cause hardware VM-entry failures.
- [Low] Redundant nesting of CC() macro causes duplicate tracepoints on failure.
--

commit 20abff7abf2b901c4e2f9f748875173a59380be0
Author: Xin Li (Intel) <[email protected]>

KVM: nVMX: Validate FRED-related VMCS fields

Extend nested VMX field validation to include FRED-specific VMCS fields, mirroring hardware behavior. This enables support for nested FRED by ensuring control and guest/host state fields are properly checked.

Quoted 4 lines
arch/x86/kvm/vmx/nested.c +0 -0
index 83e846fb3fc8c..3e0a1ed6440d4 100644

[ ... ]

Quoted 31 lines
arch/x86/kvm/vmx/nested.c +21 -1
@@ -3167,8 +3158,28 @@ static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu,
 		if (CC(intr_info & INTR_INFO_RESVD_BITS_MASK))
 			return -EINVAL;
 
-		/* VM-entry instruction length */
+		if (CC(intr_type == INTR_TYPE_RESERVED))
+			return -EINVAL;
+
+		/*
+		 * Only for hardware exceptions and when the CPU enumerates
+		 * VMX nested-exception support, bit 13 (indicating a nested
+		 * exception) has value 1. Otherwise it is reserved.
+		 */
+		if (CC(has_nested_exception &&
+		       (intr_type != INTR_TYPE_HARD_EXCEPTION ||
+			!nested_cpu_has_nested_exception(vcpu))))
+			return -EINVAL;
+
 		switch (intr_type) {
+		case INTR_TYPE_NMI_INTR:
+			if (CC(vector != NMI_VECTOR))
+				return -EINVAL;
+			break;
+		case INTR_TYPE_HARD_EXCEPTION:
+			if (CC(vector > 31))
+				return -EINVAL;
+			break;
 		case INTR_TYPE_SOFT_EXCEPTION:
 		case INTR_TYPE_SOFT_INTR:
 		case INTR_TYPE_PRIV_SW_EXCEPTION:

arch/x86/kvm/vmx/nested.c static int nested_check_vm_entry_controls(struct kvm_vcpu *vcpu, · line 3189

Quoted 3 lines
arch/x86/kvm/vmx/nested.c +0 -0
@@ -3176,6 +3187,28 @@ 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;

[Severity: Low]
Does this double CC() macro wrapping cause duplicate tracepoints?

If both conditions evaluate to true for soft exceptions and interrupts, the inner CC() will emit a tracepoint, which then causes the outer CC() to also evaluate to true and emit a second tracepoint. Is this intentional?

[ ... ]

Quoted 17 lines
arch/x86/kvm/vmx/nested.c +13 -0
@@ -3262,9 +3295,27 @@ static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu,
 	if (ia32e) {
 		if (CC(!(vmcs12->host_cr4 & X86_CR4_PAE)))
 			return -EINVAL;
+		if (nested_cpu_load_host_fred_state(vmcs12)) {
+			if (CC(vmcs12->host_ia32_fred_config & FRED_CONFIG_RESERVED) ||
+			    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_msr_address(vmcs12->host_ia32_fred_config & PAGE_MASK, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_rsp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_rsp2, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_rsp3, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_ssp1, vcpu)) ||

arch/x86/kvm/vmx/nested.c static int nested_vmx_check_host_state(struct kvm_vcpu *vcpu, · line 3320

Quoted 10 lines
arch/x86/kvm/vmx/nested.c +5 -0
+			    CC(is_noncanonical_msr_address(vmcs12->host_ia32_fred_ssp2, vcpu)) ||
+			    CC(is_noncanonical_msr_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;

[Severity: High]
Are we missing a check for FRED host state when not in IA-32e mode?

If an L1 guest configures vmcs12 with VM_ENTRY_LOAD_IA32_FRED = 1 but VM_ENTRY_IA32E_MODE = 0 (or equivalent host state), the FRED host state checks are completely bypassed since ia32e is false here.

Would this missing cross-field consistency check allow an invalid vmcs12 state to be accepted, failing to validate that FRED controls must be zero in 32-bit mode?

[ ... ]

Quoted 35 lines
arch/x86/kvm/vmx/nested.c +31 -0
@@ -3447,6 +3498,48 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,
 	     CC((vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD))))
 		return -EINVAL;
 
+	if (ia32e) {
+		if (nested_cpu_load_guest_fred_state(vmcs12)) {
+			if (CC(vmcs12->guest_ia32_fred_config & FRED_CONFIG_RESERVED) ||
+			    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_msr_address(vmcs12->guest_ia32_fred_config & PAGE_MASK, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_rsp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_rsp2, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_rsp3, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_ssp1, vcpu)) ||
+			    CC(is_noncanonical_msr_address(vmcs12->guest_ia32_fred_ssp2, vcpu)) ||
+			    CC(is_noncanonical_msr_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;
+
+			switch (ss_dpl) {
+			case 0:
+				if (CC(!(vmcs12->guest_cs_ar_bytes & VMX_AR_L_MASK)))
+					return -EINVAL;
+				break;
+			case 3:
+				if (CC(vmcs12->guest_rflags & X86_EFLAGS_IOPL))

arch/x86/kvm/vmx/nested.c static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu, · line 3541

Quoted 10 lines
arch/x86/kvm/vmx/nested.c +10 -0
+					return -EINVAL;
+				if (CC(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_STI))
+					return -EINVAL;
+				break;
+			}
+		}
+	} else {
+		if (CC(vmcs12->guest_cr4 & X86_CR4_FRED))
+			return -EINVAL;
+	}

[Severity: High]
Similarly, does this else branch for the guest state miss failing the entry if nested_cpu_load_guest_fred_state(vmcs12) is true?

Without this cross-field check, a malicious L1 hypervisor could provide a vmcs12 with VM_ENTRY_LOAD_IA32_FRED = 1 but VM_ENTRY_IA32E_MODE = 0, causing KVM to accept the invalid configuration and copy the VM_ENTRY_LOAD_IA32_FRED bit directly into vmcs02 during prepare_vmcs02.

This would lead to an L0 hardware VM-entry failure instead of the required software synthesis of an L1 VMFail, causing a host-side denial of service against the VM process.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
#85 lore raw

PATCH v10 25/28 KVM: nVMX: Enable VMX FRED controls

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

Permit use of VMX FRED controls in nested VMX now that support for nested FRED is implemented.

---
v10:
- Remove an obsolete comment (Chao).

---
 arch/x86/kvm/vmx/nested.c | 10 +++-------
 arch/x86/kvm/vmx/vmx.c    |  1 +
 2 files changed, 4 insertions(+), 7 deletions(-)
arch/x86/kvm/vmx/nested.c +3 -7
index 3e0a1ed6440d..4fad9728a2ea 100644
@@ -7371,12 +7371,8 @@ static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
 
 	if (msrs->exit_ctls_high & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) {
 		msrs->secondary_exit_ctls = vmcs_conf->vmexit_2nd_ctrl;
-		/*
-		 * As the secondary VM exit control is always loaded, do not
-		 * advertise any feature in it to nVMX until its nVMX support
-		 * is ready.
-		 */
-		msrs->secondary_exit_ctls &= 0;
+		msrs->secondary_exit_ctls &= SECONDARY_VM_EXIT_SAVE_IA32_FRED |
+					     SECONDARY_VM_EXIT_LOAD_IA32_FRED;
 	}
 }
 
@@ -7392,7 +7388,7 @@ static void nested_vmx_setup_entry_ctls(struct vmcs_config *vmcs_conf,
 		VM_ENTRY_IA32E_MODE |
 #endif
 		VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS |
-		VM_ENTRY_LOAD_CET_STATE;
+		VM_ENTRY_LOAD_CET_STATE | 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);
arch/x86/kvm/vmx/vmx.c +1 -0
index 3a3315a7fc11..f673cd4e8956 100644
@@ -8150,6 +8150,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
#86 lore raw

Re: [PATCH v10 25/28] KVM: nVMX: Enable VMX FRED controls

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] KVM unconditionally advertises nested VMX FRED controls to L1 guests without verifying host or…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] KVM unconditionally advertises nested VMX FRED controls to L1 guests without verifying host or guest FRED CPUID capabilities, leading to silent state drops during nested transitions. --

commit 8c95c51cce41b2dd05048f8b79efa91ac6528519
Author: Xin Li (Intel) <[email protected]>

KVM: nVMX: Enable VMX FRED controls

This patch permits the use of VMX FRED controls in nested VMX by updating the entry and secondary exit controls, allowing FRED-related operations during nested VM exits and entries.

Quoted 5 lines
arch/x86/kvm/vmx/nested.c +0 -0
@@ -7371,12 +7371,8 @@ static void nested_vmx_setup_exit_ctls(struct vmcs_config *vmcs_conf,
 

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

Quoted 10 lines
arch/x86/kvm/vmx/nested.c +2 -6
 	if (msrs->exit_ctls_high & VM_EXIT_ACTIVATE_SECONDARY_CONTROLS) {
 		msrs->secondary_exit_ctls = vmcs_conf->vmexit_2nd_ctrl;
-		/*
-		 * As the secondary VM exit control is always loaded, do not
-		 * advertise any feature in it to nVMX until its nVMX support
-		 * is ready.
-		 */
-		msrs->secondary_exit_ctls &= 0;
+		msrs->secondary_exit_ctls &= SECONDARY_VM_EXIT_SAVE_IA32_FRED |
+					     SECONDARY_VM_EXIT_LOAD_IA32_FRED;

[Severity: High]
Does this unconditionally advertise nested VMX FRED controls to L1 guests without verifying host or guest FRED CPUID capabilities?

If an L1 guest is configured without FRED CPUID capabilities, it is still permitted by these MSRs to set the FRED controls in its vmcs12. KVM directly copies this control bit to the hardware vmcs02 structure.

However, because KVM's nested entry routines explicitly check guest_cpu_cap_has(vcpu, X86_FEATURE_FRED), KVM will skip initializing the vmcs02 FRED MSR fields. When the physical CPU enters L2, it will load uninitialized or stale FRED MSR fields from KVM's vmcs02 memory, which can lead to unpredictable L2 behavior or silent state drops.

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

Quoted 9 lines
arch/x86/kvm/vmx/nested.c +1 -1
 	}
 }
 
@@ -7392,7 +7388,7 @@ static void nested_vmx_setup_entry_ctls(struct vmcs_config *vmcs_conf,
 		VM_ENTRY_IA32E_MODE |
 #endif
 		VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS |
-		VM_ENTRY_LOAD_CET_STATE;
+		VM_ENTRY_LOAD_CET_STATE | VM_ENTRY_LOAD_IA32_FRED;

[Severity: High]
Similar to the exit controls above, does VM_ENTRY_LOAD_IA32_FRED need to be dynamically masked from msrs->entry_ctls_high in nested_vmx_setup_entry_ctls() when FRED is unsupported by KVM or the guest?

Quoted 3 lines
arch/x86/kvm/vmx/nested.c +0 -0
 	msrs->entry_ctls_high |=
 		(VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER |
 		 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
#87 lore raw

PATCH v10 26/28 KVM: selftests: Add FRED MSRs to msrs_test

In reply to Sohil Mehta

From: Xin Li <[email protected]>

Add FRED MSR coverage to msrs_test, including the FRED RSP0-3, SSP0-3, STKLVLS and CONFIG MSRs.

---
v10:
- New patch.

---
 tools/arch/x86/include/asm/msr-index.h        |  2 +
 .../selftests/kvm/include/x86/processor.h     |  1 +
 tools/testing/selftests/kvm/x86/msrs_test.c   | 52 ++++++++++++++++++-
 3 files changed, 53 insertions(+), 2 deletions(-)
tools/arch/x86/include/asm/msr-index.h +2 -0
index 18c4be75e927..14632e29f981 100644
@@ -64,6 +64,8 @@
 #define MSR_IA32_FRED_SSP3	0x1d3			/* Level 3 shadow stack pointer */
 #define MSR_IA32_FRED_CONFIG	0x1d4			/* Entrypoint and interrupt stack level */
 
+#define FRED_CONFIG_RESERVED		(BIT_ULL(2) | GENMASK_ULL(5, 4) | BIT_ULL(11))
+
 /* Intel MSRs. Some also available on other CPUs */
 #define MSR_TEST_CTRL				0x00000033
 #define MSR_TEST_CTRL_SPLIT_LOCK_DETECT_BIT	29
tools/testing/selftests/kvm/include/x86/processor.h +1 -0
index 6e6f70035508..916646cb4d89 100644
@@ -195,6 +195,7 @@ 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_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/msrs_test.c +50 -2

83 lines not on this page · raw message

Signature · 1 line
2.43.0
#88 lore raw

PATCH v10 27/28 KVM: selftests: Add a new VM guest mode to run user level code

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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.

---
v10:
- Treat as new patch (last posted in v2).

---
 tools/testing/selftests/kvm/include/kvm_util.h  |  1 +
 tools/testing/selftests/kvm/lib/kvm_util.c      |  5 ++++-
 tools/testing/selftests/kvm/lib/x86/processor.c | 16 ++++++++++++----
 3 files changed, 17 insertions(+), 5 deletions(-)
tools/testing/selftests/kvm/include/kvm_util.h +1 -0
index 5a7a455b5387..981adfcbd5fa 100644
@@ -191,6 +191,7 @@ enum vm_guest_mode {
 	VM_MODE_P40V48_16K,
 	VM_MODE_P40V48_64K,
 	VM_MODE_PXXVYY_4K,	/* For 48-bit or 57-bit VA, depending on host support */
+	VM_MODE_PXXVYY_4K_USER,	/* For 48bits VA but ANY bits PA with USER bit set */
 	VM_MODE_P47V64_4K,
 	VM_MODE_P44V64_4K,
 	VM_MODE_P36V48_4K,
tools/testing/selftests/kvm/lib/kvm_util.c +4 -1
index 9ddc047d5c27..e79fddedaf39 100644
@@ -210,6 +210,7 @@ const char *vm_guest_mode_string(u32 i)
 		[VM_MODE_P40V48_16K]	= "PA-bits:40,  VA-bits:48, 16K pages",
 		[VM_MODE_P40V48_64K]	= "PA-bits:40,  VA-bits:48, 64K pages",
 		[VM_MODE_PXXVYY_4K]	= "PA-bits:ANY, VA-bits:48 or 57, 4K pages",
+		[VM_MODE_PXXVYY_4K_USER]= "PA-bits:ANY, VA-bits:48,  4K user pages",
 		[VM_MODE_P47V64_4K]	= "PA-bits:47,  VA-bits:64,  4K pages",
 		[VM_MODE_P44V64_4K]	= "PA-bits:44,  VA-bits:64,  4K pages",
 		[VM_MODE_P36V48_4K]	= "PA-bits:36,  VA-bits:48,  4K pages",
@@ -246,6 +247,7 @@ const struct vm_guest_mode_params vm_guest_mode_params[] = {
 	[VM_MODE_P40V48_16K]	= { 40, 48,  0x4000, 14 },
 	[VM_MODE_P40V48_64K]	= { 40, 48, 0x10000, 16 },
 	[VM_MODE_PXXVYY_4K]	= {  0,  0,  0x1000, 12 },
+	[VM_MODE_PXXVYY_4K_USER]= {  0,  0,  0x1000, 12 },
 	[VM_MODE_P47V64_4K]	= { 47, 64,  0x1000, 12 },
 	[VM_MODE_P44V64_4K]	= { 44, 64,  0x1000, 12 },
 	[VM_MODE_P36V48_4K]	= { 36, 48,  0x1000, 12 },
@@ -337,6 +339,7 @@ struct kvm_vm *____vm_create(struct vm_shape shape)
 		vm->mmu.pgtable_levels = 3;
 		break;
 	case VM_MODE_PXXVYY_4K:
+	case VM_MODE_PXXVYY_4K_USER:
 #ifdef __x86_64__
 		kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
 		kvm_init_vm_address_properties(vm);
@@ -355,7 +358,7 @@ struct kvm_vm *____vm_create(struct vm_shape shape)
 			vm->mmu.pgtable_levels = 4;
 		}
 #else
-		TEST_FAIL("VM_MODE_PXXVYY_4K not supported on non-x86 platforms");
+		TEST_FAIL("VM_MODE_PXXVYY_4K(_USER) not supported on non-x86 platforms");
 #endif
 		break;
 	case VM_MODE_P47V64_4K:
tools/testing/selftests/kvm/lib/x86/processor.c +12 -4
index d31fa81ea075..51d713c4c9de 100644
@@ -167,6 +167,9 @@ bool kvm_is_tdp_enabled(void)
 static void virt_mmu_init(struct kvm_vm *vm, struct kvm_mmu *mmu,
 			  struct pte_masks *pte_masks)
 {
+	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K || vm->mode == VM_MODE_PXXVYY_4K_USER,
+		    "Unknown or unsupported guest mode: 0x%x", vm->mode);
+
 	/* If needed, create the top-level page table. */
 	if (!mmu->pgd_created) {
 		mmu->pgd = vm_alloc_page_table(vm);
@@ -181,7 +184,7 @@ static void virt_mmu_init(struct kvm_vm *vm, struct kvm_mmu *mmu,
 
 void virt_arch_pgd_alloc(struct kvm_vm *vm)
 {
-	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K,
+	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K || vm->mode == VM_MODE_PXXVYY_4K_USER,
 		    "Unknown or unsupported guest mode: 0x%x", vm->mode);
 
 	struct pte_masks pte_masks = (struct pte_masks){
@@ -239,6 +242,8 @@ static u64 *virt_create_upper_pte(struct kvm_vm *vm,
 		*pte = PTE_PRESENT_MASK(mmu) | PTE_READABLE_MASK(mmu) |
 		       PTE_WRITABLE_MASK(mmu) | PTE_EXECUTABLE_MASK(mmu) |
 		       PTE_ALWAYS_SET_MASK(mmu);
+		if (vm->mode == VM_MODE_PXXVYY_4K_USER)
+			*pte |= PTE_USER_MASK(mmu);
 		if (current_level == target_level)
 			*pte |= PTE_HUGE_MASK(mmu) | (gpa & PHYSICAL_PAGE_MASK);
 		else
@@ -266,7 +271,7 @@ void __virt_pg_map(struct kvm_vm *vm, struct kvm_mmu *mmu, gva_t gva,
 	u64 *pte = &mmu->pgd;
 	int current_level;
 
-	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K,
+	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K || vm->mode == VM_MODE_PXXVYY_4K_USER,
 		    "Unknown or unsupported guest mode: 0x%x", vm->mode);
 
 	TEST_ASSERT((gva % pg_size) == 0,
@@ -316,6 +321,9 @@ void __virt_pg_map(struct kvm_vm *vm, struct kvm_mmu *mmu, gva_t gva,
 		*pte |= PTE_C_BIT_MASK(mmu);
 	else
 		*pte |= PTE_S_BIT_MASK(mmu);
+
+	if (vm->mode == VM_MODE_PXXVYY_4K_USER)
+		*pte |= PTE_USER_MASK(mmu);
 }
 
 void virt_arch_pg_map(struct kvm_vm *vm, gva_t gva, gpa_t gpa)
@@ -372,7 +380,7 @@ static u64 *__vm_get_page_table_entry(struct kvm_vm *vm,
 	TEST_ASSERT(*level >= PG_LEVEL_NONE && *level <= mmu->pgtable_levels,
 		    "Invalid PG_LEVEL_* '%d'", *level);
 
-	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K,
+	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K || vm->mode == VM_MODE_PXXVYY_4K_USER,
 		    "Unknown or unsupported guest mode: 0x%x", vm->mode);
 	TEST_ASSERT(sparsebit_is_set(vm->vpages_valid, (gva >> vm->page_shift)),
 		    "Invalid virtual address, gva: 0x%lx", gva);
@@ -645,7 +653,7 @@ static void vcpu_init_sregs(struct kvm_vm *vm, struct kvm_vcpu *vcpu)
 {
 	struct kvm_sregs sregs;
 
-	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K,
+	TEST_ASSERT(vm->mode == VM_MODE_PXXVYY_4K || vm->mode == VM_MODE_PXXVYY_4K_USER,
 		    "Unknown or unsupported guest mode: 0x%x", vm->mode);
 
 	/* Set mode specific system register values. */
Signature · 1 line
2.43.0
#89 lore raw

PATCH v10 28/28 KVM: selftests: Add fred exception tests

In reply to Sohil Mehta

From: "Xin Li (Intel)" <[email protected]>

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 based 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.

---
v10:
- Treat as new patch (last posted in v2).

---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../selftests/kvm/include/x86/processor.h     |  33 ++
 tools/testing/selftests/kvm/x86/fred_test.c   | 291 ++++++++++++++++++
 3 files changed, 325 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/fred_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 96bab7002d39..73aed018f4a3 100644
@@ -78,6 +78,7 @@ TEST_GEN_PROGS_x86 += x86/feature_msrs_test
 TEST_GEN_PROGS_x86 += x86/evmcs_smm_controls_test
 TEST_GEN_PROGS_x86 += x86/exit_on_emulation_failure_test
 TEST_GEN_PROGS_x86 += x86/fastops_test
+TEST_GEN_PROGS_x86 += x86/fred_test
 TEST_GEN_PROGS_x86 += x86/fix_hypercall_test
 TEST_GEN_PROGS_x86 += x86/hwcr_msr_test
 TEST_GEN_PROGS_x86 += x86/hyperv_clock
tools/testing/selftests/kvm/include/x86/processor.h +33 -0
index 916646cb4d89..988c45e32689 100644
@@ -79,6 +79,7 @@ const char *ex_str(int vector);
 #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;
@@ -1646,4 +1647,36 @@ u64 *tdp_get_pte(struct kvm_vm *vm, u64 l2_gpa);
 
 bool sys_clocksource_is_based_on_tsc(void);
 
+/*
+ * 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/fred_test.c new file +291 -0

291 lines not on this page · raw message

Signature · 1 line
2.43.0
#90 lore raw

Re: [PATCH v10 28/28] KVM: selftests: Add fred exception tests

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [Critical] MSR_STAR is not initialized, leading to #GP(0) during FRED event delivery to ring 0. - [High]…

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [Critical] MSR_STAR is not initialized, leading to #GP(0) during FRED event delivery to ring 0.
- [High] The test fails to verify KVM's VMX nested-exception injection logic because it uses an unmapped guest virtual address with EPT enabled, which triggers a native guest #PF rather than an EPT violation VM exit.
- [High] The host test loop ignores UCALL_ABORT and unhandled VM exits, leading to an infinite test hang instead of a clear failure.
- [High] Incorrect hardcoded segment selectors and missing Long Mode bit in the FRED event frame's SS field, leading to #GP(0) during ERETS.
- [Medium] The guest stack pointer FRED_VALID_RSP is hardcoded to 0x8000, which risks colliding with guest page tables or framework allocations.
- [Medium] The host test loop silently succeeds on early termination without verifying that all expected test stages were executed.
--

commit 2e068431765f5ca444df8cd9c81ade084609dfcd
Author: Xin Li (Intel) <[email protected]>

KVM: selftests: Add fred exception tests

This commit adds selftests for Flexible Return and Event Delivery (FRED) event data and VMX nested-exception handling. It injects page faults as nested exceptions to test FRED VMX code by running tests with EPT disabled.

Quoted 6 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +0 -0
new file mode 100644
index 0000000000000..c7d08e5253b98
@@ -0,0 +1,291 @@

[ ... ]

tools/testing/selftests/kvm/x86/fred_test.c line 27

Quoted 2 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +2 -0
+/* This address is already mapped in guest page table. */
+#define FRED_VALID_RSP			0x8000

[Severity: Medium]
Is using a hardcoded guest stack pointer of 0x8000 safe here? There might be a risk of memory corruption in the guest if this hardcoded address overlaps with dynamically allocated KVM selftests structures or page tables.

Quoted 5 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +5 -0
+/*
+ * 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.

tools/testing/selftests/kvm/x86/fred_test.c line 43

Quoted 10 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +10 -0
+ *
+ * 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,
+};

[Severity: High]
Does this properly verify KVM VMX nested-exception injection logic? Using an unmapped guest virtual address while EPT is enabled natively delivers the fault to the guest rather than causing an EPT violation VM exit. This could result in bypassing the KVM code it was intended to validate.

[ ... ]

tools/testing/selftests/kvm/x86/fred_test.c line 85

Quoted 11 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +11 -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;
+}

[Severity: High]
Will executing ERETS with these hardcoded segment selectors cause a #GP(0) fault in the guest? The value 0x10 is a data segment in KVM selftests, and the SSX value 0x18 is missing the Long Mode bit. This combination seems to lead to a triple fault and test crash when asm_fred_entrypoint_user executes ERETS using this prepared stack frame.

[ ... ]

tools/testing/selftests/kvm/x86/fred_test.c line 214

Quoted 4 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +4 -0
+static void guest_code(void)
+{
+	wrmsr(MSR_IA32_FRED_CONFIG,
+	      FRED_CONFIG_ENTRYPOINT(asm_fred_entrypoint_user));

[Severity: Critical]
Is MSR_STAR initialization missing from the FRED testing environment setup? When triggering a #UD or #PF in ring 3, FRED delivers the event to ring 0 and reads MSR_STAR[47:32] for the target CS. Since it is uninitialized (0), the CPU could fault on the null CS selector and cause a triple fault during event delivery in guest_code.

[ ... ]

tools/testing/selftests/kvm/x86/fred_test.c line 280

Quoted 11 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +11 -0
+	while (true) {
+		uint64_t r;
+
+		vcpu_run(vcpu);
+
+		r = get_ucall(vcpu, &uc);
+
+		if (r == UCALL_DONE)
+			break;
+
+		if (r == UCALL_SYNC) {

[Severity: High]
What happens if the guest crashes or asserts in main, returning an exit reason like UCALL_ABORT? The loop appears to lack handling for unexpected VM exits, which would cause get_ucall() to return 0 or UCALL_ABORT. This could result in an infinite test hang rather than a clean failure.

tools/testing/selftests/kvm/x86/fred_test.c line 291

Quoted 11 lines
tools/testing/selftests/kvm/x86/fred_test.c new file +11 -0
+			TEST_ASSERT((uc.args[1] == expected_current_stack_level) &&
+				    (uc.args[2] == fred_invalid_rsp[expected_current_stack_level] - 8),
+				    "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;
+}

[Severity: Medium]
Could the test falsely pass if the guest exits early? Receiving UCALL_DONE breaks the loop and exits with 0, but it does not verify that all expected test stages were actually executed.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=28
maintainer
#91 lore raw
In reply to Sohil Mehta
Quoted 7 lines · Sohil Mehta

I mainly rebased the patches to the latest kvm-x86/next branch and fixed a handful of issues reported during internal testing and basic AI reviews. I've avoided making any major code changes or commit message updates as this is the first iteration that I am posting.

Thanks a lot for taking care of the patch series.

Quoted 6 lines

Going forward, based on the feedback, I'll rework the patches as needed. I've listed a few opens below that need additional discussion or clarification. I'm relatively new to the KVM subsystem, so please feel free to provide suggestions on the series structure, code organization as well as commit log clarity to smoothen the review process.

I’ve been thinking about an optimization: because FRED drops most of the old syscall MSRs (IA32_LSTAR/IA32_CSTAR/IA32_SFMASK), we should be able to omit them from KVM's uret MSR tracking entirely as if host enables FRED (no matter whether a guest uses FRED).

Thanks!
Xin

maintainer
#92 lore raw
Quoted 17 lines · Xin Li
Quoted 7 lines · Sohil Mehta

I mainly rebased the patches to the latest kvm-x86/next branch and fixed a handful of issues reported during internal testing and basic AI reviews. I've avoided making any major code changes or commit message updates as this is the first iteration that I am posting.

Thanks a lot for taking care of the patch series.

Quoted 6 lines

Going forward, based on the feedback, I'll rework the patches as needed. I've listed a few opens below that need additional discussion or clarification. I'm relatively new to the KVM subsystem, so please feel free to provide suggestions on the series structure, code organization as well as commit log clarity to smoothen the review process.

Quoted 5 lines

I’ve been thinking about an optimization: because FRED drops most of the old syscall MSRs (IA32_LSTAR/IA32_CSTAR/IA32_SFMASK), we should be able to omit them from KVM's uret MSR tracking entirely as if host enables FRED (no matter whether a guest uses FRED).

Yes, although they will need to be handled properly between VCPU switches, of course.

-hpa

#93 lore raw
Quoted 18 lines · H. Peter Anvin
Quoted 17 lines · Xin Li
Quoted 7 lines · Sohil Mehta

I mainly rebased the patches to the latest kvm-x86/next branch and fixed a handful of issues reported during internal testing and basic AI reviews. I've avoided making any major code changes or commit message updates as this is the first iteration that I am posting.

Thanks a lot for taking care of the patch series.

Quoted 6 lines

Going forward, based on the feedback, I'll rework the patches as needed. I've listed a few opens below that need additional discussion or clarification. I'm relatively new to the KVM subsystem, so please feel free to provide suggestions on the series structure, code organization as well as commit log clarity to smoothen the review process.

Quoted 7 lines
Quoted 5 lines

I’ve been thinking about an optimization: because FRED drops most of the old syscall MSRs (IA32_LSTAR/IA32_CSTAR/IA32_SFMASK), we should be able to omit them from KVM's uret MSR tracking entirely as if host enables FRED (no matter whether a guest uses FRED).

Yes, although they will need to be handled properly between VCPU switches, of course.

And we'd want to keep the optimizations to elide writes when vCPUs are using the same value(s). So, compile tested only...

From: Sean Christopherson <[email protected]>
Date: Mon, 26 Oct 2026 07:37:03 -0700
Subject: [PATCH] KVM: x86: Don't bother loading host values for SYSCALL MSRs
when FRED is in use

Elide the WRMSRs for the SYSCALL MSRs when returning to userspace if FRED is in use, in which case said MSRs are never actually used in Linux.

Note, KVM never saves/restores MSR_CSTAR via the user-return MSR mechanism, as the MSR is unused by Intel/VMX hardware, and SVM unconditionally context switches the MSR via a dedicated VMCB field (along with all other SYSCALL MSRs). Include MSR_CSTAR to provide a contiguous range of values in the case statements, e.g. so that the compiler can optimize the case statements into a simple bounds checks.

---
 arch/x86/kvm/msrs.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
arch/x86/kvm/msrs.c +19 -1
index e91650af44c2..ef3596d8c780 100644
@@ -65,6 +65,23 @@ void kvm_destroy_user_return_msrs(void)
 	kvm_nr_uret_msrs = 0;
 }
 
+static bool kvm_is_msr_used_in_host(u32 msr)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_FRED))
+		return true;
+
+	switch (msr) {
+	case MSR_STAR:
+	case MSR_LSTAR:
+	case MSR_CSTAR:
+	case MSR_SYSCALL_MASK:
+		return false;
+	default:
+		break;
+	}
+	return true;
+}
+
 static void kvm_on_user_return(struct user_return_notifier *urn)
 {
 	unsigned slot;
@@ -77,7 +94,8 @@ static void kvm_on_user_return(struct user_return_notifier *urn)
 
 	for (slot = 0; slot < kvm_nr_uret_msrs; ++slot) {
 		values = &msrs->values[slot];
-		if (values->host != values->curr) {
+		if (kvm_is_msr_used_in_host(kvm_uret_msrs_list[slot]) &&
+		    values->host != values->curr) {
 			wrmsrq(kvm_uret_msrs_list[slot], values->host);
 			values->curr = values->host;
 		}

base-commit: 7e60162b16f9da0d2fa83da5c1723b6853a0ac1d

#94 lore raw
Quoted 3 lines · Sean Christopherson

And we'd want to keep the optimizations to elide writes when vCPUs are using the same value(s). So, compile tested only...

Will test this out on real hardware with the MSR_STAR change below.

arch/x86/kvm/msrs.c void kvm_destroy_user_return_msrs(void) · line 74

Quoted 8 lines
arch/x86/kvm/msrs.c +7 -0
+static bool kvm_is_msr_used_in_host(u32 msr)
+{
+	if (!cpu_feature_enabled(X86_FEATURE_FRED))
+		return true;
+
+	switch (msr) {
+	case MSR_STAR:

AFAIU, MSR_STAR is still used with FRED so it shouldn't be included here. The Spec says in section 4.4:

IA32_STAR:
- Existing use: this MSR is used by the existing operation of SYSCALL and SYSRET.
- FRED use: FRED event delivery loads the CS and SS selectors with values derived from IA32_STAR[47:32] (see Section 5.3). ERETU uses the value of IA32_STAR[63:48] to determine how to load the CS and SS registers (see Section 6.2.1).

It is expected that operating systems will set IA32_STAR[33:32] to 00B and IA32_STAR[49:48] to 11B.

Likewise, the kernel also writes to MSR_STAR during syscall_init() and it has a comment saying: "Except the IA32_STAR MSR, there is NO need to setup SYSCALL and SYSENTER MSRs for FRED, .."

Quoted 10 lines
arch/x86/kvm/msrs.c +10 -0
+	case MSR_LSTAR:
+	case MSR_CSTAR:
+	case MSR_SYSCALL_MASK:
+		return false;
+	default:
+		break;
+	}
+	return true;
+}
+
author Tested-by
#95 lore raw
Quoted 8 lines · Sohil Mehta
Quoted 3 lines · Sean Christopherson

And we'd want to keep the optimizations to elide writes when vCPUs are using the same value(s). So, compile tested only...

Will test this out on real hardware with the MSR_STAR change below.

With MSR_STAR not restored (original patch), the kernel boots fine, but a guest's STAR stays loaded and it triggers a ERETS #GP as expected when CS/SS has a mismatch.

With MSR_STAR dropped from kvm_is_msr_used_in_host(), it works as expected. x86 KVM selftests pass and the systems runs without issues.

A few AI generated scripts and tests confirmed that STAR is restored each time and LSTAR/SYSCALL_MASK is left at the guest's values when FRED is enabled. Also, SYSCALL in each guest still lands on its own LSTAR when two VMs alternate on one pCPU.

#96 lore raw
In reply to Sean Christopherson
Quoted 9 lines

From: Sean Christopherson <[email protected]>
Date: Mon, 26 Oct 2026 07:37:03 -0700
Subject: [PATCH] KVM: x86: Don't bother loading host values for SYSCALL MSRs
when FRED is in use

Elide the WRMSRs for the SYSCALL MSRs when returning to userspace if FRED is in use, in which case said MSRs are never actually used in Linux.

Quoted 7 lines

Note, KVM never saves/restores MSR_CSTAR via the user-return MSR mechanism, as the MSR is unused by Intel/VMX hardware, and SVM unconditionally context switches the MSR via a dedicated VMCB field (along with all other SYSCALL MSRs). Include MSR_CSTAR to provide a contiguous range of values in the case statements, e.g. so that the compiler can optimize the case statements into a simple bounds checks.

Sean, I assume you will post this separately. I don't think it depends on anything in this series. Please let me know if you want me to do anything additional here.

Quoted 1 line

BTW, Xin no longer works at Intel. For any of his *new* contributions to the kernel, he has been using:

Xin Li <[email protected]>

Quoted 6 lines
---
 arch/x86/kvm/msrs.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
#97 lore raw
In reply to Sohil Mehta
Quoted 8 lines · Sohil Mehta

Opens
-----
INT1 event type: David Woodhouse shared a selftest which shows [2] KVM re-injects an intercepted ICEBP (INT1) #DB as a hardware exception, so a FRED guest reads event type 3 instead of 5. IIUC, the issue is not FRED specific but it becomes visible due to FRED. Is that understanding correct? Also, I am unsure of where the fix should reside or if a generic fix is already in the works. Any insights here would be helpful.

That's my understanding too, yes. It doesn't *matter* what type it's re-injected as, until the guest has FRED support and can actually see the difference.

So while the issue is pre-existing, it's only actually a *bug* in KVM once your series lands. So I think you need to plumb the event type through the KVM exception queue as an explicit field.

#98 lore raw
In reply to Sohil Mehta
Quoted 7 lines · Sohil Mehta

Opens
-----

AMD compatibility: The SVM enabling [5] builds on the same common plumbing but I haven't had a chance to look at the series yet. Shivansh, please let me know if there are any incompatibilities. I assume most of the opens apply to SVM as well so resolutions would help both vendors.

Thanks for the series Sohil. I've been able to run SVM side of vFRED with changes rebased on top of this series. So, no incompatibilities in common plumbing as of now. Will let you know if anything comes up.

Cheers,
Shivansh

#99 lore raw
Quoted 4 lines · Shivansh Dhiman
Quoted 2 lines · Sohil Mehta

Opens
-----

Quoted 8 lines
Quoted 4 lines

AMD compatibility: The SVM enabling [5] builds on the same common plumbing but I haven't had a chance to look at the series yet. Shivansh, please let me know if there are any incompatibilities. I assume most of the opens apply to SVM as well so resolutions would help both vendors.

Thanks for the series Sohil. I've been able to run SVM side of vFRED with changes rebased on top of this series. So, no incompatibilities in common plumbing as of now. Will let you know if anything comes up.

Can I remove the "Some AMD CPUs (Venice) incorrectly..." part of the commit message of
https://git.infradead.org/?p=users/dwmw2/linux.git;a=commitdiff;h=fred

#100 lore raw
Quoted 10 lines · David Woodhouse
Quoted 9 lines · Shivansh Dhiman
Quoted 7 lines · Sohil Mehta

Opens
-----

AMD compatibility: The SVM enabling [5] builds on the same common plumbing but I haven't had a chance to look at the series yet. Shivansh, please let me know if there are any incompatibilities. I assume most of the opens apply to SVM as well so resolutions would help both vendors.

Quoted 7 lines
Quoted 3 lines

Thanks for the series Sohil. I've been able to run SVM side of vFRED with changes rebased on top of this series. So, no incompatibilities in common plumbing as of now. Will let you know if anything comes up.

Can I remove the "Some AMD CPUs (Venice) incorrectly..." part of the commit message of
https://git.infradead.org/?p=users/dwmw2/linux.git;a=commitdiff;h=fred

Hi David,

Yes, you may go ahead and drop that sentence. AMD Zen 6 (Venice) supports event type 5 for INT1, and the FRED Virtualization spec [1] has been updated to reflect this.

I also ran your int1_fred_test selftest on top of my SVM FRED series [2], and all three tests pass. Note that the series stops intercepting ICEBP for FRED-enabled guests, which is what lets the guest see event type 5.

$ sudo ./int1_fred_test
Random seed: 0x55d6fcb8
Testing FRED event types with EPT fault on stack
  ICEBP (EVENT_TYPE_PRIV_SWEXC): PASSED
  INT3 (EVENT_TYPE_SWEXC): PASSED
  INT $0x20 (EVENT_TYPE_SWINT): PASSED

One small nit: could the message above say "EPT/NPT" instead of "EPT", since the test also runs on AMD?

Thanks,
Shivansh

[1]: https://docs.amd.com/v/u/en-US/69191-PUB
[2]: https://lore.kernel.org/kvm/[email protected]/

maintainer
#101 lore raw
Quoted 5 lines · Shivansh Dhiman
Quoted 5 lines
Quoted 4 lines

Thanks for the series Sohil. I've been able to run SVM side of vFRED with changes rebased on top of this series. So, no incompatibilities in common plumbing as of now. Will let you know if anything comes up.

Quoted 8 lines
Quoted 3 lines

Can I remove the "Some AMD CPUs (Venice) incorrectly..." part of the commit message of
https://git.infradead.org/?p=users/dwmw2/linux.git;a=commitdiff;h=fred

Yes, you may go ahead and drop that sentence. AMD Zen 6 (Venice) supports event type 5 for INT1, and the FRED Virtualization spec [1] has been updated to reflect this.

That's wonderful!

-hpa

#102 lore raw
In reply to Sohil Mehta
Quoted 2 lines · Sohil Mehta

This series enables Intel flexible return and event delivery (FRED) with KVM VMX to allow guests to utilize FRED.

Hey Sohil,

So, one data point: I've been using these for the past few days on a piece of FRED-capable hardware to do kernel shadow stack development. At least for my purposes, they're working great.

Other than sashiko, it looks like there hasn't been much activity on v10. What are your plans for this? Are you going to rebase and repost after the merge window closes?

Is there anything else you know of holding this up?

#103 lore raw
Quoted 10 lines · Dave Hansen
Quoted 2 lines · Sohil Mehta

This series enables Intel flexible return and event delivery (FRED) with KVM VMX to allow guests to utilize FRED.

Hey Sohil,

So, one data point: I've been using these for the past few days on a piece of FRED-capable hardware to do kernel shadow stack development. At least for my purposes, they're working great.

Glad to hear that :)

Quoted 2 lines

Other than sashiko, it looks like there hasn't been much activity on v10. What are your plans for this?

I have been focussed on getting the LASS KVM series ready for merge. That is ready for Sean to look at.

Now, I am planning to focus on FRED KVM for the next few weeks. I'll go through the Sashiko comments this week and respond to them.

Quoted 2 lines

Are you going to rebase and repost after the merge window closes?

Yes, assuming that the Sashiko issues are minor, I'm hoping to time it with the KVM next branch around the -rc2 timeframe.

Quoted 1 line

Is there anything else you know of holding this up?

I've listed a few opens in the cover letter but most of them are not gating. There is *a* solution included for each open (except for the INT1 event type issue reported by David). However, depending on the KVM preference the code might need to be tweaked.

Overall, I think the patches need some human reviews. They have been cache cold for a while, so I thought reviewers might need some time to refresh.

With Plumbers done and folks in PRC back from holidays, hopefully we can build some momentum and get this series merge ready :)

#104 lore raw
In reply to Sohil Mehta
Quoted 3 lines · Sohil Mehta

Patch structure
---------------

Since now at the 10th iteration, and I saw Sean gave a bunch of feedback already, I suppose pieces are quite sorted out. So I'm more interested in how those pieces could be organized to make easier to follow, review, and integrate going forward.

Quoted 1 line

Patches 1-6: Enable the VMX controls and export the host stacks

These seem to be preparatory changes for supporting the state and extending event delivery later in this series.

Would it make sense to put the x86 core preparation up front rather than having it in the middle of the KVM changes?

Quoted 1 line

Patches 7-19: Virtualize the FRED context and advertise it to userspace

I think there are a few sub-groups here:
(1) patch07-10: Support FRED state context switching
(2) patch11-14: Extend event delivery
(3) patch15-17: Handle CR4
(4) patch18-19: Advertise the feature, etc.

At glance, (2) looks a little difficult to follow. Patch 13/14 in particular appear to mix the FRED support itself with some preparatory changes. IIUC, the code is saying everything outside of the is_fred_enabled() path has no functional change.

Perhaps, the changes outside of is_fred_enabled() could be separated out. That would make the actual is_fred_enabled() path easier to follow. Also, the part introduces the ABI immediately after adding is_fred_enabled(), before showing up the callsite of is_fred_enabled(). This flow is a bit abrupt.

For example, extending kvm_requeue_exception() alone could be one step. The next step could add the code under is_fred_enabled(), initially with is_fred_enabled() as a placeholder that simply returns false. I think that would better highlight which parts are actually FRED-specific and why this dynamic check is needed.

Since is_fred_enabled() depends on CR4 anyway, its actual implementation could then come with (3), or somewhere later. Finally, (2) could perhaps be completed by adding the new ABI at the end.

Quoted 1 line

Patches 20-25: Extend FRED virtualization to nested VMX

Since nVMX support comes after exposing the feature, does that also mean the series could be partitioned into two parts, one up through the advertisement (and tests) and another for nVMX support? Splitting up a complex series like this may make review and integration easier going forward.

Thanks,
Chang

#105 lore raw
Quoted 7 lines · Chang S. Bae
Quoted 3 lines · Sohil Mehta

Patch structure
---------------

So I'm more interested in how those pieces could be organized to make easier to follow, review, and integrate going forward.

Thanks! This is good feedback. I've been thinking about splitting and making this easier to review as well.

Quoted 9 lines
Quoted 2 lines

Patches   1-6: Enable the VMX controls and export the host stacks

These seem to be preparatory changes for supporting the state and extending event delivery later in this series.

Would it make sense to put the x86 core preparation up front rather than having it in the middle of the KVM changes?

Sure, I can move the x86 preparatory changes to the front of the series.

Actually, some of the x86 patches are good cleanups independent of the FRED KVM support. I am thinking of posting them separately and maybe those can be merged sooner to reduce the load on this series.

As you suggested below, it would be great if we can separate out the nested VMX support as well. But there are issues (like the one discussed in patch 19) that link the L1 guest support with the nested support.

I believe if we separate out the secondary VM-exit controls infrastructure (L1 and nested - independent of FRED) then it will get rid of the dependency.

Here's the rough structure I am working towards:

Part 1) Core x86 prep (3 patches)
Part 2) Secondary VM-exit control infra (3-4 patches) Part 3) FRED guest support (16–18 patches) Part 4) Nested FRED support (5-7 patches)

Parts 1 and 2 are independent of each other and can be posted and reviewed in parallel. The selftests can be posted with the relevant parts if appropriate.

Quoted 10 lines
Quoted 1 line

Patches  7-19: Virtualize the FRED context and advertise it to userspace

I think there are a few sub-groups here:
 (1) patch07-10: Support FRED state context switching
 (2) patch11-14: Extend event delivery
 (3) patch15-17: Handle CR4
 (4) patch18-19: Advertise the feature, etc.

Quoted 5 lines

At glance, (2) looks a little difficult to follow. Patch 13/14 in particular appear to mix the FRED support itself with some preparatory changes. IIUC, the code is saying everything outside of the is_fred_enabled() path has no functional change.

Sure, I'll try to incorporate this.

Quoted 6 lines

Perhaps, the changes outside of is_fred_enabled() could be separated out. That would make the actual is_fred_enabled() path easier to follow. Also, the part introduces the ABI immediately after adding is_fred_enabled(), before showing up the callsite of is_fred_enabled(). This flow is a bit abrupt.

Yes, I have identified a couple of simplifications to make the flow easier.

Quoted 6 lines

For example, extending kvm_requeue_exception() alone could be one step. The next step could add the code under is_fred_enabled(), initially with is_fred_enabled() as a placeholder that simply returns false. I think that would better highlight which parts are actually FRED-specific and why this dynamic check is needed.

I am not sure if the is_fred_enabled() false placeholder would buy us anything. is_fred_enabled() is expected to be false until the feature is advertised to guest. But I get the gist - Separating the non FRED-specific parts would make it easier to follow the FRED-specific ones.

Quoted 8 lines
Quoted 1 line

Patches 20-25: Extend FRED virtualization to nested VMX

Since nVMX support comes after exposing the feature, does that also mean the series could be partitioned into two parts, one up through the advertisement (and tests) and another for nVMX support? Splitting up a complex series like this may make review and integration easier going forward.

Yes, I am working towards making this possible.

Quoted 2 lines

Thanks,
Chang

#106 lore raw
In reply to Sohil Mehta
Quoted 1 line · Sohil Mehta
 42 files changed, 1471 insertions(+), 135 deletions(-)

This set is too big and is stuck. I also kinda want to see it move forward. Could you please take all of the cleanups out of here?

If it's plain non-KVM x86 gunk and you need it for this series. I'll merge it today if it's halfway sane. For instance, why is:

x86/cea: Prefix event stack names with ESTACK_

even *in* this stack?

Please just send those to me directly, in another series.

#107 lore raw
Quoted 6 lines · Dave Hansen
Quoted 1 line · Sohil Mehta
 42 files changed, 1471 insertions(+), 135 deletions(-)

This set is too big and is stuck. I also kinda want to see it move forward. Could you please take all of the cleanups out of here?

I am glad that you asked. I mentioned the same thing in my response to Chang yesterday.

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

Quoted 8 lines

If it's plain non-KVM x86 gunk and you need it for this series. I'll merge it today if it's halfway sane. For instance, why is:

x86/cea: Prefix event stack names with ESTACK_

even *in* this stack?

Please just send those to me directly, in another series.

Thanks! I will send something out soon.