Skip to contentSkip to conversation

KVM: nSVM: Optimize nSVM TLB flushes

PATCH In review Yosry Ahmed 4 participants 102 messages Oct 12 – Nov 5

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

v3 cover KVM: nSVM: Optimize nSVM TLB flushes

This series optimizes TLB flushes for nested SVM by using and maintaining a separate ASID for L2 for each vCPU (similar to VMX's handling of VPIDs), rather than sharing the same ASID and flushing everything on every nested transition.

The series also drops the dynamic ASID allocation scheme and uses a static ASID per vCPU (or two if using nested), bringing it closer to how VMX handles VPIDs. Modern CPUs (Rome, Milan, Genoa, Turin) advertise 32K ASIDs, so there is no need for dynamic allocation.

The Hyper-V bits only got build tested. The SEV bits were only tested using the SEV selftests.

Otherwise, this series was tested in two ways:
1. A new selftest:
- Tests most basic scenarios where L1 flushes the TLB for L2, as well as when KVM triggers a TLB flush for both L1 and L2.
- On AMD, also tests that flushing (or changing) L2's ASID flushes nested NPT translations for all nCR3 roots, not just the current one.
- Fails reliably when injecting manual TLB bugs (e.g. commenting out a

    flush).

- Caught an actual bug when I was rebasing the series on top of Paolo's MMU structures rework.
- Works for both SVM and VMX.
- Was used to repro a separate nVMX TLB bug [1].

2. An AI generated script (now 1300 lines of bash that I still don't dare to read):
- Runs 20 L1 VMs, split into two groups:
- 10 L1 VMs with vCPUs pinned 1:1 to dedicated host CPUs, each running a single L2 VM with as many vCPUs as L1. This avoids TLB flushes on vCPU migration and L2 ASID switching, which would otherwise hide missed flushes.
- 10 L1 VMs with vCPUs confined to half as many host CPUs, each running 4 L2 VMs. This overcommits CPU in both L0 and L1 to exercise TLB flushes on vCPU migration and L2 ASID switching.
- Each L2 VM runs a workload that writes to most of its memory and then validates its content from a different vCPU.
- L2 VMs overcommit memory in L1, and are periodically recycled to exercise ASID reallocation.
- L0 periodically reclaims memory from L1 VMs proactively (exercise L0-induced TLB flushes).
- The number of ASIDs is synthetically reduced (using a test-only patch) such that some L1 vCPUs use the fallback ASID for L2.
- Runs with NPT enabled/disabled in L0 and L1.
- Catches most manually injected TLB bugs, some only semi-reliably.
- Caught an actual bug when testing the fallback ASID logic with synthetically reduced number of ASIDs (in v1).

Overall, I think I am happy with the testing I put this series through, hence dropping the RFC tag at last.

Breakdown:
- Patch 1 is a bug fix that can be taken separately.
- Patches 2-11 implement the change to use static ASIDs per vCPU for SVM (including SEV-specific handling and fallback ASID optimization), and can also be taken separately if needed.
- Patches 12-26 add the L2 ASID and proper handling for it, leading to dropping the unconditional flushes on nested transitions.
- Patch 27 adds the nested TLB flush selftest.

v2 -> v3:
- Reworked INVLPGA emulation to free L2's shadow roots when NPT is disabled and L1 flushes L2's ASID, instead of syncing the flushed address.
- Dropped "KVM: x86/mmu: Rename __kvm_mmu_invalidate_addr() to kvm_mmu_sync_addr()" and "KVM: x86/mmu: Refactor kvm_mmu_invlpg() to allow skipping the GVA flush", as they are no longer needed.
- Use READ_ONCE()/WRITE_ONCE() to access the per-CPU fallback ASID vCPU tracking [Sashiko].
- Added a "memory" clobber to invlpga() in selftests [Sashiko].
- Clarified that VMRUN does not modify TLB_CONTROL in the changelog of "KVM: nSVM: Handle nested TLB flush requests through TLB_CONTROL".
- Collected Reviewed-by from Lai.
- Typo fixes.

v1 -> v2:
- Rebased on top of kvm-x86-next-2026.10.02. Drop the fixes to the dynamic ASID allocation that landed since v1 when switching to static ASIDs, as they are no longer needed (bumping the ASID generation on CPU online, resetting the ASID generation of both VMCBs on pCPU switch, and tracking pending full flushes per-CPU).
- Dropped "KVM: SVM: Duplicate pre-run ASID check for SEV and non-SEV guests", and keep syncing the ASID into the VMCB before VMRUN until static ASIDs are used, to avoid leaving vmcb02's ASID uninitialized for SEV guests in between [Sashiko].
- Explicitly initialize svm->asid during SEV VM migration in a separate patch, before the VMCB is initialized [Sashiko].
- Free any existing non-SEV ASID on the destination vCPUs during SEV VM migration to avoid leaking it, and decide whether an ASID needs to be freed based on the ASID range rather than the VM type [Sashiko].
- Update the L2 ASID (and vmcb02) during SEV VM migration if nested was already initialized on the destination vCPUs [Sashiko].
- Moved "KVM: nSVM: Drop svm->nested.initialized" before introducing the L2 ASID, so that the vmcb02 pointer can be reliably used to check if nested is initialized.
- Moved the WARN on L1 and L2 unexpectedly sharing an ASID to the patch that actually uses different ASIDs [Sashiko].
- Added KVM_REQ_MMU_SYNC_ALL_ROOTS, and sync all nested NPT roots (not just the current one) when L1 flushes or changes L2's ASID, as shadow NPT mappings are not tagged by ASID.
- Reset the last L2 ASID if nested VMRUN fails, to avoid losing the nested NPT sync.
- Extended the selftest to cover flushing with multiple nested NPT roots.
- Typo and changelog fixes.

RFC v2 -> v1:
- Dropped the RFC tag.
- Document KVM's handling of number of ASIDs in CPUID rather than increase the number of advertised ASIDs [Jim, Sean].
- Explicitly support reserved TLB tags rather than a minimum TLB tag [Sean].
- Set an upper bound on the number of TLB tags [Sean].
- Allow reserving all ASIDs to allow allocating all ASIDs to SEV (if at all possible). [Sashiko].
- Actually handle TLB flushes for nested on SEV [Sean, Sashiko].
- Optimize fallback ASID flushes by tracking the last vCPU using it on each pCPU instead of flushing it on every VMRUN [Sean].
- Drop svm->nested.initialized and properly NULLify the vmcb02 pointer instead (and use it).
- Make sure servicing local TLB flushes is done when both the VMCB and guest_mode are consistent [Sashiko].
- Always initialize last_asid to 0 to flush the TLB on the first use of L2's ASID [Sashiko].
- Open-code TLB flush handling on nested VM-Enter and VM-Exit instead of burying it in svm_switch_vmcb() [Sean].
- Always flush the hardware ASID on nested transitions if L1 and L2 share it (e.g. when using the fallback ASID, or for SEV guests) to prevent TLB entry leakage between L1 and L2.
- Rename __kvm_mmu_invalidate_addr() to kvm_mmu_sync_addr() [Sean].

RFC v1: https://lore.kernel.org/lkml/[email protected]/
RFC v2: https://lore.kernel.org/kvm/[email protected]/
v1: https://lore.kernel.org/kvm/[email protected]/
v2: https://lore.kernel.org/kvm/[email protected]/

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

Yosry Ahmed (27):
KVM: nSVM: Flush the TLB after forcefully leaving nested
KVM: SVM: Document number of ASIDs CPUID setting
KVM: VMX: Generalize VPID allocation to be vendor-neutral
KVM: x86/mmu: Support specifying reserved TLB tags
KVM: SVM: Add helpers to set/clear ASID flush in VMCB
KVM: SVM: Fallback to flush everything if FLUSHBYASID is not available
KVM: SEV: Do ASID initialization at VMCB initialization
KVM: SEV: Expose sev_get_asid() outside of sev.c
KVM: SEV: Explicitly initialize the per vCPU ASID on SEV VM migration
KVM: SVM: Use a static ASID per vCPU
KVM: SVM: Only flush the fallback ASID when used by a different vCPU
KVM: nSVM: Drop svm->nested.initialized
KVM: nSVM: Add a placeholder ASID for L2
KVM: x86: hyper-v: Rename kvm_hv_vcpu_purge_flush_tlb()
KVM: x86: hyper-v: Allow purging all TLB flush FIFOs
KVM: nSVM: Flush both L1 and L2 ASIDs on KVM_REQ_TLB_FLUSH
KVM: nSVM: Always switch VMCB before leaving guest mode
KVM: nSVM: Split nested_svm_transition_tlb_flush() into entry/exit fns
KVM: nSVM: Service local TLB flushes before nested transitions
KVM: x86: Add KVM_REQ_MMU_SYNC_ALL_ROOTS
KVM: nSVM: Handle nested TLB flush requests through TLB_CONTROL
KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12
KVM: nSVM: Do not reset TLB_CONTROL in vmcb02 on nested VM-Enter
KVM: nSVM: Flush L2's ASID when emulating INVLPGA
KVM: nSVM: Flush the ASID on nested transitions if shared by L1 and L2
KVM: nSVM: Use different ASIDs for L1 and L2
KVM: selftests: Add a test for nested TLB flushes

 Documentation/virt/kvm/api.rst                |  20 +
 arch/x86/include/asm/kvm_host.h               |   1 +
 arch/x86/kvm/cpuid.c                          |   4 +-
 arch/x86/kvm/hyperv.h                         |  33 +-
 arch/x86/kvm/mmu.h                            |  15 +
 arch/x86/kvm/mmu/mmu.c                        |  92 +++
 arch/x86/kvm/svm/nested.c                     | 151 +++--
 arch/x86/kvm/svm/sev.c                        |  37 +-
 arch/x86/kvm/svm/svm.c                        | 160 ++++--
 arch/x86/kvm/svm/svm.h                        |  55 +-
 arch/x86/kvm/vmx/vmx.c                        |  40 +-
 arch/x86/kvm/vmx/vmx.h                        |  28 +-
 arch/x86/kvm/x86.c                            |  13 +-
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../selftests/kvm/include/x86/processor.h     |   1 +
 tools/testing/selftests/kvm/include/x86/svm.h |   5 +
 tools/testing/selftests/kvm/include/x86/vmx.h |  21 +
 .../testing/selftests/kvm/lib/x86/processor.c |  36 ++
 .../selftests/kvm/x86/nested_tlb_flush_test.c | 526 ++++++++++++++++++
 19 files changed, 1076 insertions(+), 163 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86/nested_tlb_flush_test.c

base-commit: 6bd2905303c58679e303941b7d8ae8c074cd95ce

Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#1 lore raw

PATCH v3 1/27 KVM: nSVM: Flush the TLB after forcefully leaving nested

KVM flushes the TLB on nested VM-Enter and nested VM-Exit, but not when forcefully leaving nested. In this case, L2 TLB entries can leak into L1. Flush the TLB after forcefully exiting L2, similar to nested VM-Exits.

Note that vmx_leave_nested() handles this correctly, as it reuses nested_vmx_vmexit(), which handles the necessary TLB flushes on an L2 -> L1 transition.

---
 arch/x86/kvm/svm/nested.c | 2 ++
 1 file changed, 2 insertions(+)
arch/x86/kvm/svm/nested.c +2 -0
index af0ef678433d7..2bfc9d2c341b1 100644
@@ -1558,6 +1558,8 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
 
 		svm_switch_vmcb(svm, &svm->vmcb01);
 
+		nested_svm_transition_tlb_flush(vcpu);
+
 		nested_svm_uninit_mmu_context(vcpu);
 		vmcb_mark_all_dirty(svm->vmcb);
 
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 1/27
#2 lore raw

Re: [PATCH v3 01/27] KVM: nSVM: Flush the TLB after forcefully leaving nested

Quoted 9 lines · Yosry Ahmed

KVM flushes the TLB on nested VM-Enter and nested VM-Exit, but not when forcefully leaving nested. In this case, L2 TLB entries can leak into L1. Flush the TLB after forcefully exiting L2, similar to nested VM-Exits.

Note that vmx_leave_nested() handles this correctly, as it reuses nested_vmx_vmexit(), which handles the necessary TLB flushes on an L2 -> L1 transition.

Fixes ???
Quoted 2 lines
#3 lore raw

Re: [PATCH v3 01/27] KVM: nSVM: Flush the TLB after forcefully leaving nested

Quoted 8 lines · Jim Mattson
Quoted 6 lines · Yosry Ahmed

KVM flushes the TLB on nested VM-Enter and nested VM-Exit, but not when forcefully leaving nested. In this case, L2 TLB entries can leak into L1. Flush the TLB after forcefully exiting L2, similar to nested VM-Exits.

Quoted 5 lines
Quoted 3 lines

Note that vmx_leave_nested() handles this correctly, as it reuses nested_vmx_vmexit(), which handles the necessary TLB flushes on an L2 -> L1 transition.

Fixes ???

I figured it was too old to be meaningful (i.e. we'll backport to all active stable kernels anyway).

But I think it should be:

Fixes c513f484c558 ("KVM: nSVM: leave guest mode when clearing EFER.SVME")
Quoted 3 lines
Quoted 2 lines
#4 lore raw

Re: [PATCH v3 01/27] KVM: nSVM: Flush the TLB after forcefully leaving nested

Quoted 14 lines · Yosry Ahmed
Quoted 12 lines · Jim Mattson
Quoted 9 lines · Yosry Ahmed

KVM flushes the TLB on nested VM-Enter and nested VM-Exit, but not when forcefully leaving nested. In this case, L2 TLB entries can leak into L1. Flush the TLB after forcefully exiting L2, similar to nested VM-Exits.

Note that vmx_leave_nested() handles this correctly, as it reuses nested_vmx_vmexit(), which handles the necessary TLB flushes on an L2 -> L1 transition.

Quoted 8 lines
Quoted 1 line
Fixes ???

I figured it was too old to be meaningful (i.e. we'll backport to all active stable kernels anyway).

But I think it should be:

Fixes c513f484c558 ("KVM: nSVM: leave guest mode when clearing EFER.SVME")

I concur.

#5 lore raw

PATCH v3 2/27 KVM: SVM: Document number of ASIDs CPUID setting

In reply to Yosry Ahmed

KVM arbitrarily advertises 8 ASIDs in KVM_GET_SUPPORTED_CPUID for historical reasons. Advertising a small number of ASIDs to L1 is currently harmless, as KVM (L0) uses the same ASID for both L1 and L2, and flushes that ASID on nested transitions.

However, following changes will add proper ASID emulation and a separate ASID for L2, minimizing the TLB flushes on nested transitions. At that point, a full TLB flush from a KVM guest (L1) would flush both L1 and L2 ASIDs, so should be avoided as much as possible by advertising more ASIDs to L1.

Increasing the value advertised by KVM is tricky, because a VMM copying the number of ASIDs from KVM_GET_SUPPORTED_CPUID may perceive a new VM with a higher number of ASIDs as incompatible with older KVM (which is not true).

Avoid changing the value advertised by KVM, but document that it is essentially meaningless and does not represent a limit or a hint. Also, more-or-less encourage userspace to advertise a higher value to avoid potential unnecessary TLB flushes from an L1 hypervisor.

---
 Documentation/virt/kvm/api.rst | 20 ++++++++++++++++++++
 arch/x86/kvm/cpuid.c           |  4 ++--
 2 files changed, 22 insertions(+), 2 deletions(-)
Documentation/virt/kvm/api.rst +20 -0
index ddc61ea36ac59..60f49b3675920 100644
@@ -9770,6 +9770,26 @@ the APIC ID is found in EDX for all subleaves of 0x0b and 0x1f, and in EAX
 for 0x8000001e; the latter also encodes the core id and node id in bits
 7:0 of EBX and ECX respectively.
 
+Number of ASIDs (nested SVM)
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+CPUID[0x8000000A]:EBX reports the number of ASIDs supported by the processor
+on AMD CPUs. KVM's ``KVM_GET_SUPPORTED_CPUID`` hardcodes this value to 8 for
+historical reasons. This value is arbitrary and does not represent a limit
+on the supported number of ASIDs, or even a reasonable default value.
+
+KVM allows userspace to set any value (up to 0xFFFFFFFF), and emulates those
+ASIDs by multiplexing them onto hardware ASIDs. AMD CPUs have only ever
+supported 3 values: 0x40, 0x8000, and 0x1000 -- with modern CPUs advertising
+0x8000.
+
+Advertising a small number of ASIDs could lead an L1 hypervisor to perform
+unnecessary TLB flushes (e.g. older KVM would flush the entire TLB when running
+out of ASIDs). Userspace should probably set the number of ASIDs to a
+reasonably high power of 2 value to remain consistent with hardware and avoid
+any misbehavior by L1 hypervisors, ideally one of the values advertised by
+actual hardware.
+
 Obsolete ioctls and capabilities
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
arch/x86/kvm/cpuid.c +2 -2
index adafd6fa2c542..e45c01d6faeaf 100644
@@ -1846,8 +1846,8 @@ static inline int __do_cpuid_func(struct kvm_cpuid_array *array, u32 function)
 			break;
 		}
 		entry->eax = 1; /* SVM revision 1 */
-		entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
-				   ASID emulation to nested SVM */
+		entry->ebx = 8; /* Arbitrary value for historical reasons. KVM
+				   practically allows and ignores all values. */
 		entry->ecx = 0; /* Reserved */
 		cpuid_entry_override(entry, CPUID_8000_000A_EDX);
 		break;
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 2/27
#6 lore raw

Re: [PATCH v3 02/27] KVM: SVM: Document number of ASIDs CPUID setting

Quoted 17 lines · Yosry Ahmed

KVM arbitrarily advertises 8 ASIDs in KVM_GET_SUPPORTED_CPUID for historical reasons. Advertising a small number of ASIDs to L1 is currently harmless, as KVM (L0) uses the same ASID for both L1 and L2, and flushes that ASID on nested transitions.

However, following changes will add proper ASID emulation and a separate ASID for L2, minimizing the TLB flushes on nested transitions. At that point, a full TLB flush from a KVM guest (L1) would flush both L1 and L2 ASIDs, so should be avoided as much as possible by advertising more ASIDs to L1.

Increasing the value advertised by KVM is tricky, because a VMM copying the number of ASIDs from KVM_GET_SUPPORTED_CPUID may perceive a new VM with a higher number of ASIDs as incompatible with older KVM (which is not true).

Quoted 7 lines

Avoid changing the value advertised by KVM, but document that it is essentially meaningless and does not represent a limit or a hint. Also, more-or-less encourage userspace to advertise a higher value to avoid potential unnecessary TLB flushes from an L1 hypervisor.

#7 lore raw

PATCH v3 3/27 KVM: VMX: Generalize VPID allocation to be vendor-neutral

In reply to Yosry Ahmed

In preparation for sharing with SVM, generalize the VMX VPID allocation code and move it to common code as a TLB tags allocator. Parameterize the TLB tags allocator by the number of tags, and allocate the bitmap dynamically. Opportunisitcally use guards to acquire the lock instead of spin_{lock/unlock}().

Keep the number of allowed tags capped at VMX's hardware cap, to avoid allocating a huge bitmap if L0 advertises a huge number of ASIDs to an L1 KVM. Realistically, the number of actual hardware ASIDs wouldn't be that large so there is no benefit.

Initialize the TLB tags allocator during hardware setup/unsetup, and reserve tag=0 during initialziation, similar to how VPID=0 is currently reserved in the VMX-specific bitmap during hardware setup.

Allow nr=0 to allow allocating all ASIDs to SEV on AMD without failing hardware setup, if at all possible, in which case any tag allocation fails (SEV won't use the tag allocator). The number of tags includes tag=0, which is not usable. The interface is a little confusing in that regard, but this will be changed soon when reserved tags are explicitly introduced.

Keep allocate_vpid() and free_vpid() as wrapper that check enable_vpid to avoid checking at all callsites, and add init_vpids() and destroy_vpids() to wrap init/destroy calls as well.

No functional change intended.

---
 arch/x86/kvm/mmu.h     |  8 +++++
 arch/x86/kvm/mmu/mmu.c | 78 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/vmx.c | 40 +++++-----------------
 arch/x86/kvm/vmx/vmx.h | 28 ++++++++++++---
 4 files changed, 119 insertions(+), 35 deletions(-)
arch/x86/kvm/mmu.h +8 -0
index 2ae7f9ed4cf86..de79e002edf8f 100644
@@ -410,4 +410,12 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn)
 {
 	return gfn & kvm_gfn_direct_bits(kvm);
 }
+
+typedef unsigned int kvm_tlb_tag_t;
+
+int kvm_init_tlb_tags(unsigned int nr);
+void kvm_destroy_tlb_tags(void);
+kvm_tlb_tag_t kvm_alloc_tlb_tag(void);
+void kvm_free_tlb_tag(kvm_tlb_tag_t tag);
+
 #endif
arch/x86/kvm/mmu/mmu.c +78 -0

84 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.c +9 -31
index b341af4c6057a..a1caa2bd04d7a 100644
@@ -598,9 +598,6 @@ DEFINE_PER_CPU(struct vmcs *, current_vmcs);
  */
 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
 
-static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
-static DEFINE_SPINLOCK(vmx_vpid_lock);
-
 struct vmcs_config vmcs_config __ro_after_init;
 struct vmx_capability vmx_capability __ro_after_init;
 
@@ -4092,31 +4089,6 @@ static void seg_setup(int seg)
 	vmcs_write32(sf->ar_bytes, ar);
 }
 
-int allocate_vpid(void)
-{
-	int vpid;
-
-	if (!enable_vpid)
-		return 0;
-	spin_lock(&vmx_vpid_lock);
-	vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
-	if (vpid < VMX_NR_VPIDS)
-		__set_bit(vpid, vmx_vpid_bitmap);
-	else
-		vpid = 0;
-	spin_unlock(&vmx_vpid_lock);
-	return vpid;
-}
-
-void free_vpid(int vpid)
-{
-	if (!enable_vpid || vpid == 0)
-		return;
-	spin_lock(&vmx_vpid_lock);
-	__clear_bit(vpid, vmx_vpid_bitmap);
-	spin_unlock(&vmx_vpid_lock);
-}
-
 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx)
 {
 	/*
@@ -8415,6 +8387,8 @@ void vmx_hardware_unsetup(void)
 
 	if (nested)
 		nested_vmx_hardware_unsetup();
+
+	destroy_vpids();
 }
 
 void vmx_vm_destroy(struct kvm *kvm)
@@ -8640,8 +8614,6 @@ __init int vmx_hardware_setup(void)
 	kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection();
 	kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit();
 
-	set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
-
 	if (enable_ept)
 		kvm_mmu_set_ept_masks(enable_ept_ad_bits);
 	else
@@ -8681,6 +8653,10 @@ __init int vmx_hardware_setup(void)
 
 	vmx_set_cpu_caps();
 
+	r = init_vpids();
+	if (r)
+		return r;
+
 	/*
 	 * Configure nested capabilities after core CPU capabilities so that
 	 * nested support can be conditional on base support, e.g. so that KVM
@@ -8688,8 +8664,10 @@ __init int vmx_hardware_setup(void)
 	 */
 	if (nested) {
 		r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers);
-		if (r)
+		if (r) {
+			destroy_vpids();
 			return r;
+		}
 	}
 	vmx_nested_ops.enabled = nested;
 
arch/x86/kvm/vmx/vmx.h +24 -4
index 6c9dd5b2365d5..a8df797163ecc 100644
@@ -182,7 +182,7 @@ struct nested_vmx {
 	u64 pre_vmenter_ssp;
 	u64 pre_vmenter_ssp_tbl;
 
-	u16 vpid02;
+	kvm_tlb_tag_t vpid02;
 	u16 last_vpid;
 
 	int tsc_autostore_slot;
@@ -256,7 +256,7 @@ struct vcpu_vmx {
 			u32 ar;
 		} seg[8];
 	} segment_cache;
-	int vpid;
+	kvm_tlb_tag_t vpid;
 
 	/* Support for a guest hypervisor (nested VMX) */
 	struct nested_vmx nested;
@@ -297,9 +297,29 @@ struct kvm_vmx {
 	u64 *pid_table;
 };
 
+static __always_inline int init_vpids(void)
+{
+	return enable_vpid ? kvm_init_tlb_tags(VMX_NR_VPIDS) : 0;
+}
+
+static __always_inline void destroy_vpids(void)
+{
+	if (enable_vpid)
+		kvm_destroy_tlb_tags();
+}
+
+static __always_inline kvm_tlb_tag_t allocate_vpid(void)
+{
+	return enable_vpid ? kvm_alloc_tlb_tag() : 0;
+}
+
+static __always_inline void free_vpid(kvm_tlb_tag_t vpid)
+{
+	if (enable_vpid)
+		kvm_free_tlb_tag(vpid);
+}
+
 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu);
-int allocate_vpid(void);
-void free_vpid(int vpid);
 void vmx_set_constant_host_state(struct vcpu_vmx *vmx);
 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu);
 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#8 lore raw

Re: [PATCH v3 03/27] KVM: VMX: Generalize VPID allocation to be vendor-neutral

Quoted 5 lines · Yosry Ahmed

In preparation for sharing with SVM, generalize the VMX VPID allocation code and move it to common code as a TLB tags allocator. Parameterize the TLB tags allocator by the number of tags, and allocate the bitmap dynamically. Opportunisitcally use guards to acquire the lock instead of

s/Opportunisitcally/Opportunistically/

Quoted 9 lines

spin_{lock/unlock}().

Keep the number of allowed tags capped at VMX's hardware cap, to avoid allocating a huge bitmap if L0 advertises a huge number of ASIDs to an L1 KVM. Realistically, the number of actual hardware ASIDs wouldn't be that large so there is no benefit.

Initialize the TLB tags allocator during hardware setup/unsetup, and reserve tag=0 during initialziation, similar to how VPID=0 is currently

s/initialziation/initialization/

Quoted 9 lines

reserved in the VMX-specific bitmap during hardware setup.

Allow nr=0 to allow allocating all ASIDs to SEV on AMD without failing hardware setup, if at all possible, in which case any tag allocation fails (SEV won't use the tag allocator). The number of tags includes tag=0, which is not usable. The interface is a little confusing in that regard, but this will be changed soon when reserved tags are explicitly introduced.

Quoted 5 lines

Keep allocate_vpid() and free_vpid() as wrapper that check enable_vpid to avoid checking at all callsites, and add init_vpids() and destroy_vpids() to wrap init/destroy calls as well.

No functional change intended.

I don't think that's really true. If it is, then you failed. For example, the new -ENOMEM when the bitmap can't be dynamically allocated.

Quoted 30 lines
---
 arch/x86/kvm/mmu.h     |  8 +++++
 arch/x86/kvm/mmu/mmu.c | 78 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/vmx.c | 40 +++++-----------------
 arch/x86/kvm/vmx/vmx.h | 28 ++++++++++++---
 4 files changed, 119 insertions(+), 35 deletions(-)
arch/x86/kvm/mmu.h +8 -0
index 2ae7f9ed4cf86..de79e002edf8f 100644
@@ -410,4 +410,12 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn)
 {
        return gfn & kvm_gfn_direct_bits(kvm);
 }
+
+typedef unsigned int kvm_tlb_tag_t;
+
+int kvm_init_tlb_tags(unsigned int nr);
+void kvm_destroy_tlb_tags(void);
+kvm_tlb_tag_t kvm_alloc_tlb_tag(void);
+void kvm_free_tlb_tag(kvm_tlb_tag_t tag);
+
 #endif
arch/x86/kvm/mmu/mmu.c +0 -0
index aadd5bdc2c97a..97d49247d9d82 100644

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 8185

Quoted 8 lines
arch/x86/kvm/mmu/mmu.c +5 -0
@@ -8178,6 +8178,84 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
                vhost_task_stop(kvm->arch.nx_huge_page_recovery_thread);
 }
 
+static struct {
+       spinlock_t      lock;
+       unsigned long   *bitmap;
+       unsigned int    nr;
+} tlb_tags;

Can we statically initialize this to avoid the call to spin_lock_init()?

... tlb_tags = {
.lock = __SPIN_LOCK_UNLOCKED(tlb_tags.lock),
};

Quoted 31 lines
arch/x86/kvm/mmu/mmu.c +31 -0
+
+int kvm_init_tlb_tags(unsigned int nr)
+{
+       /*
+        * Limit the number of TLB tags to VMX's hardcoded maximum of 0x10000
+        * to avoid wasting memory for the bitmap in the unlikely scenario the
+        * CPU supports an inordinate number of ASIDs (on AMD).  If userspace
+        * wants to concurrently run tens of thousands of vCPUs, they'll likely
+        * need a solution that works for both Intel and AMD.
+        */
+       const unsigned int MAX_NR_TLB_TAGS = VMX_NR_VPIDS;
+
+       if (!nr)
+               return 0;
+
+       if (nr > MAX_NR_TLB_TAGS) {
+               pr_warn_once("Number of TLB tags capped (%u instead of %u)\n",
+                            MAX_NR_TLB_TAGS, nr);
+               nr = MAX_NR_TLB_TAGS;
+       }
+
+       tlb_tags.bitmap = bitmap_zalloc(nr, GFP_KERNEL);
+       if (!tlb_tags.bitmap)
+               return -ENOMEM;
+
+       /*
+        * 0 is the host's TLB tag for both VMX's VPID and SVM's ASID, and is
+        * returned on failed allocations (e.g. no more tags left).
+        */
+       __set_bit(0, tlb_tags.bitmap);
+

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 8226

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+       tlb_tags.nr = nr;
+       spin_lock_init(&tlb_tags.lock);
+       return 0;
+}
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_init_tlb_tags);
+
+void kvm_destroy_tlb_tags(void)
+{
+       bitmap_free(tlb_tags.bitmap);
+       tlb_tags.bitmap = NULL;

For consistency and future-proofing, it might be wise to clear tlb_tags.nr here.

Quoted 2 lines
arch/x86/kvm/mmu/mmu.c +2 -0
+}
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_destroy_tlb_tags);
#9 lore raw

Re: [PATCH v3 03/27] KVM: VMX: Generalize VPID allocation to be vendor-neutral

Quoted 35 lines · Jim Mattson
Quoted 5 lines · Yosry Ahmed

In preparation for sharing with SVM, generalize the VMX VPID allocation code and move it to common code as a TLB tags allocator. Parameterize the TLB tags allocator by the number of tags, and allocate the bitmap dynamically. Opportunisitcally use guards to acquire the lock instead of

s/Opportunisitcally/Opportunistically/

Quoted 9 lines

spin_{lock/unlock}().

Keep the number of allowed tags capped at VMX's hardware cap, to avoid allocating a huge bitmap if L0 advertises a huge number of ASIDs to an L1 KVM. Realistically, the number of actual hardware ASIDs wouldn't be that large so there is no benefit.

Initialize the TLB tags allocator during hardware setup/unsetup, and reserve tag=0 during initialziation, similar to how VPID=0 is currently

s/initialziation/initialization/

Quoted 13 lines

reserved in the VMX-specific bitmap during hardware setup.

Allow nr=0 to allow allocating all ASIDs to SEV on AMD without failing hardware setup, if at all possible, in which case any tag allocation fails (SEV won't use the tag allocator). The number of tags includes tag=0, which is not usable. The interface is a little confusing in that regard, but this will be changed soon when reserved tags are explicitly introduced.

Keep allocate_vpid() and free_vpid() as wrapper that check enable_vpid to avoid checking at all callsites, and add init_vpids() and destroy_vpids() to wrap init/destroy calls as well.

Quoted 5 lines
Quoted 1 line

No functional change intended.

I don't think that's really true. If it is, then you failed. For example, the new -ENOMEM when the bitmap can't be dynamically allocated.

Point taken, will remove the claim.

Quoted 42 lines
Quoted 31 lines
---
 arch/x86/kvm/mmu.h     |  8 +++++
 arch/x86/kvm/mmu/mmu.c | 78 ++++++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/vmx.c | 40 +++++-----------------
 arch/x86/kvm/vmx/vmx.h | 28 ++++++++++++---
 4 files changed, 119 insertions(+), 35 deletions(-)
arch/x86/kvm/mmu.h +8 -0
index 2ae7f9ed4cf86..de79e002edf8f 100644
@@ -410,4 +410,12 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn)
 {
        return gfn & kvm_gfn_direct_bits(kvm);
 }
+
+typedef unsigned int kvm_tlb_tag_t;
+
+int kvm_init_tlb_tags(unsigned int nr);
+void kvm_destroy_tlb_tags(void);
+kvm_tlb_tag_t kvm_alloc_tlb_tag(void);
+void kvm_free_tlb_tag(kvm_tlb_tag_t tag);
+
 #endif
arch/x86/kvm/mmu/mmu.c +0 -0
index aadd5bdc2c97a..97d49247d9d82 100644

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 8185

Quoted 8 lines
arch/x86/kvm/mmu/mmu.c +5 -0
@@ -8178,6 +8178,84 @@ void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
                vhost_task_stop(kvm->arch.nx_huge_page_recovery_thread);
 }
 
+static struct {
+       spinlock_t      lock;
+       unsigned long   *bitmap;
+       unsigned int    nr;
+} tlb_tags;

Can we statically initialize this to avoid the call to spin_lock_init()?

Quoted 3 lines

... tlb_tags = {
.lock = __SPIN_LOCK_UNLOCKED(tlb_tags.lock),
};

The call to spin_lock_init() is less code, but I can make the change. I don't have a preference.

Quoted 36 lines
Quoted 36 lines
arch/x86/kvm/mmu/mmu.c +35 -0
+
+int kvm_init_tlb_tags(unsigned int nr)
+{
+       /*
+        * Limit the number of TLB tags to VMX's hardcoded maximum of 0x10000
+        * to avoid wasting memory for the bitmap in the unlikely scenario the
+        * CPU supports an inordinate number of ASIDs (on AMD).  If userspace
+        * wants to concurrently run tens of thousands of vCPUs, they'll likely
+        * need a solution that works for both Intel and AMD.
+        */
+       const unsigned int MAX_NR_TLB_TAGS = VMX_NR_VPIDS;
+
+       if (!nr)
+               return 0;
+
+       if (nr > MAX_NR_TLB_TAGS) {
+               pr_warn_once("Number of TLB tags capped (%u instead of %u)\n",
+                            MAX_NR_TLB_TAGS, nr);
+               nr = MAX_NR_TLB_TAGS;
+       }
+
+       tlb_tags.bitmap = bitmap_zalloc(nr, GFP_KERNEL);
+       if (!tlb_tags.bitmap)
+               return -ENOMEM;
+
+       /*
+        * 0 is the host's TLB tag for both VMX's VPID and SVM's ASID, and is
+        * returned on failed allocations (e.g. no more tags left).
+        */
+       __set_bit(0, tlb_tags.bitmap);
+
+       tlb_tags.nr = nr;
+       spin_lock_init(&tlb_tags.lock);
+       return 0;
+}
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 8226

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_init_tlb_tags);
+
+void kvm_destroy_tlb_tags(void)
+{
+       bitmap_free(tlb_tags.bitmap);
+       tlb_tags.bitmap = NULL;

For consistency and future-proofing, it might be wise to clear tlb_tags.nr here.

Can do.

Quoted 3 lines
Quoted 3 lines
arch/x86/kvm/mmu/mmu.c +2 -0
+}
+EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_destroy_tlb_tags);
#10 lore raw

Re: [PATCH v3 03/27] KVM: VMX: Generalize VPID allocation to be vendor-neutral

Quoted 12 lines · Yosry Ahmed
Quoted 10 lines · Jim Mattson

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 8185

Quoted 5 lines · Yosry Ahmed
arch/x86/kvm/mmu/mmu.c +5 -0
+static struct {
+       spinlock_t      lock;
+       unsigned long   *bitmap;
+       unsigned int    nr;
+} tlb_tags;

Can we statically initialize this to avoid the call to spin_lock_init()?

Quoted 6 lines
Quoted 3 lines

... tlb_tags = {
.lock = __SPIN_LOCK_UNLOCKED(tlb_tags.lock),
};

The call to spin_lock_init() is less code, but I can make the change. I don't have a preference.

Your call.

#11 lore raw

PATCH v3 4/27 KVM: x86/mmu: Support specifying reserved TLB tags

In reply to Yosry Ahmed

In preparation for using the TLB tags allocator for SVM, which has a range of ASIDs allocated for SEV/SNP, pass in the number of reserved TLB tags when initializing the TLB tags allocator. The bitmap is conceptually shifted such that bit=0 corresponds to tag=nr_reserved.

Specifying the minimum value during initialization also makes the API clearer, as tag=0 is now explicitly reserved by the caller.

No functional change intended for VMX as VPID=0 was already implicitly reserved.

---
 arch/x86/kvm/mmu.h     |  2 +-
 arch/x86/kvm/mmu/mmu.c | 42 ++++++++++++++++++++++++++++--------------
 arch/x86/kvm/vmx/vmx.h |  2 +-
 3 files changed, 30 insertions(+), 16 deletions(-)
arch/x86/kvm/mmu.h +1 -1
index de79e002edf8f..b443a5083bfb0 100644
@@ -413,7 +413,7 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn)
 
 typedef unsigned int kvm_tlb_tag_t;
 
-int kvm_init_tlb_tags(unsigned int nr);
+int kvm_init_tlb_tags(unsigned int nr_total, unsigned int nr_reserved);
 void kvm_destroy_tlb_tags(void);
 kvm_tlb_tag_t kvm_alloc_tlb_tag(void);
 void kvm_free_tlb_tag(kvm_tlb_tag_t tag);
arch/x86/kvm/mmu/mmu.c +28 -14

87 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.h +1 -1
index a8df797163ecc..3e1ecd9148e9c 100644
@@ -299,7 +299,7 @@ struct kvm_vmx {
 
 static __always_inline int init_vpids(void)
 {
-	return enable_vpid ? kvm_init_tlb_tags(VMX_NR_VPIDS) : 0;
+	return enable_vpid ? kvm_init_tlb_tags(VMX_NR_VPIDS, 1) : 0;
 }
 
 static __always_inline void destroy_vpids(void)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#12 lore raw

Re: [PATCH v3 04/27] KVM: x86/mmu: Support specifying reserved TLB tags

Quoted 39 lines · Yosry Ahmed

In preparation for using the TLB tags allocator for SVM, which has a range of ASIDs allocated for SEV/SNP, pass in the number of reserved TLB tags when initializing the TLB tags allocator. The bitmap is conceptually shifted such that bit=0 corresponds to tag=nr_reserved.

Specifying the minimum value during initialization also makes the API clearer, as tag=0 is now explicitly reserved by the caller.

No functional change intended for VMX as VPID=0 was already implicitly reserved.

---
 arch/x86/kvm/mmu.h     |  2 +-
 arch/x86/kvm/mmu/mmu.c | 42 ++++++++++++++++++++++++++++--------------
 arch/x86/kvm/vmx/vmx.h |  2 +-
 3 files changed, 30 insertions(+), 16 deletions(-)
arch/x86/kvm/mmu.h +1 -1
index de79e002edf8f..b443a5083bfb0 100644
@@ -413,7 +413,7 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn)
 
 typedef unsigned int kvm_tlb_tag_t;
 
-int kvm_init_tlb_tags(unsigned int nr);
+int kvm_init_tlb_tags(unsigned int nr_total, unsigned int nr_reserved);
 void kvm_destroy_tlb_tags(void);
 kvm_tlb_tag_t kvm_alloc_tlb_tag(void);
 void kvm_free_tlb_tag(kvm_tlb_tag_t tag);
arch/x86/kvm/mmu/mmu.c +0 -0
index 97d49247d9d82..c096c1a2b4684 100644
@@ -8182,9 +8182,17 @@ static struct {
        spinlock_t      lock;
        unsigned long   *bitmap;

arch/x86/kvm/mmu/mmu.c static struct { · line 8192

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +6 -1
        unsigned int    nr;
+       kvm_tlb_tag_t   start;
 } tlb_tags;
 
-int kvm_init_tlb_tags(unsigned int nr)
+/*
+ * Initialize @nr_total TLB tags, where @nr_reserved of those tags are reserved.
+ * Reserved tags start at 0 and are contiguous. Hence, usable tags are
+ * [nr_reserved, nr_total). At least one reserved tag is required, as 0 is the
+ * host TLB tag on both VMX and AMD, and is the value returned on a failed tag

Nit: VMX and SVM -or- Intel and AMD

Quoted 21 lines
arch/x86/kvm/mmu/mmu.c +8 -0
+ * allocation.
+ */
+int kvm_init_tlb_tags(unsigned int nr_total, unsigned int nr_reserved)
 {
        /*
         * Limit the number of TLB tags to VMX's hardcoded maximum of 0x10000
@@ -8194,7 +8202,12 @@ int kvm_init_tlb_tags(unsigned int nr)
         * need a solution that works for both Intel and AMD.
         */
        const unsigned int MAX_NR_TLB_TAGS = VMX_NR_VPIDS;
+       unsigned int nr;
 
+       if (WARN_ON_ONCE(!nr_reserved || nr_reserved > nr_total))
+               return -EINVAL;
+
+       nr = nr_total - nr_reserved;
        if (!nr)
                return 0;
 
@@ -8208,13 +8221,8 @@ int kvm_init_tlb_tags(unsigned int nr)
        if (!tlb_tags.bitmap)

arch/x86/kvm/mmu/mmu.c int kvm_init_tlb_tags(unsigned int nr) · line 8225

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +1 -6
                return -ENOMEM;
 
-       /*
-        * 0 is the host's TLB tag for both VMX's VPID and SVM's ASID, and is
-        * returned on failed allocations (e.g. no more tags left).
-        */
-       __set_bit(0, tlb_tags.bitmap);
-
        tlb_tags.nr = nr;
+       tlb_tags.start = nr_reserved;

Can you also clear tlb_tags.start in kvm_destroy_tlb_tags()?

#13 lore raw

Re: [PATCH v3 04/27] KVM: x86/mmu: Support specifying reserved TLB tags

Quoted 45 lines · Jim Mattson
Quoted 43 lines · Yosry Ahmed

In preparation for using the TLB tags allocator for SVM, which has a range of ASIDs allocated for SEV/SNP, pass in the number of reserved TLB tags when initializing the TLB tags allocator. The bitmap is conceptually shifted such that bit=0 corresponds to tag=nr_reserved.

Specifying the minimum value during initialization also makes the API clearer, as tag=0 is now explicitly reserved by the caller.

No functional change intended for VMX as VPID=0 was already implicitly reserved.

---
 arch/x86/kvm/mmu.h     |  2 +-
 arch/x86/kvm/mmu/mmu.c | 42 ++++++++++++++++++++++++++++--------------
 arch/x86/kvm/vmx/vmx.h |  2 +-
 3 files changed, 30 insertions(+), 16 deletions(-)
arch/x86/kvm/mmu.h +1 -1
index de79e002edf8f..b443a5083bfb0 100644
@@ -413,7 +413,7 @@ static inline bool kvm_is_gfn_alias(struct kvm *kvm, gfn_t gfn)
 
 typedef unsigned int kvm_tlb_tag_t;
 
-int kvm_init_tlb_tags(unsigned int nr);
+int kvm_init_tlb_tags(unsigned int nr_total, unsigned int nr_reserved);
 void kvm_destroy_tlb_tags(void);
 kvm_tlb_tag_t kvm_alloc_tlb_tag(void);
 void kvm_free_tlb_tag(kvm_tlb_tag_t tag);
arch/x86/kvm/mmu/mmu.c +1 -0
index 97d49247d9d82..c096c1a2b4684 100644
@@ -8182,9 +8182,17 @@ static struct {
        spinlock_t      lock;
        unsigned long   *bitmap;
        unsigned int    nr;
+       kvm_tlb_tag_t   start;
 } tlb_tags;
 
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c static struct { · line 8192

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +5 -1
-int kvm_init_tlb_tags(unsigned int nr)
+/*
+ * Initialize @nr_total TLB tags, where @nr_reserved of those tags are reserved.
+ * Reserved tags start at 0 and are contiguous. Hence, usable tags are
+ * [nr_reserved, nr_total). At least one reserved tag is required, as 0 is the
+ * host TLB tag on both VMX and AMD, and is the value returned on a failed tag

Nit: VMX and SVM -or- Intel and AMD

LOL, how did I end up with that.

Quoted 24 lines
Quoted 24 lines
arch/x86/kvm/mmu/mmu.c +8 -0
+ * allocation.
+ */
+int kvm_init_tlb_tags(unsigned int nr_total, unsigned int nr_reserved)
 {
        /*
         * Limit the number of TLB tags to VMX's hardcoded maximum of 0x10000
@@ -8194,7 +8202,12 @@ int kvm_init_tlb_tags(unsigned int nr)
         * need a solution that works for both Intel and AMD.
         */
        const unsigned int MAX_NR_TLB_TAGS = VMX_NR_VPIDS;
+       unsigned int nr;
 
+       if (WARN_ON_ONCE(!nr_reserved || nr_reserved > nr_total))
+               return -EINVAL;
+
+       nr = nr_total - nr_reserved;
        if (!nr)
                return 0;
 
@@ -8208,13 +8221,8 @@ int kvm_init_tlb_tags(unsigned int nr)
        if (!tlb_tags.bitmap)
                return -ENOMEM;
 
Quoted 10 lines

arch/x86/kvm/mmu/mmu.c int kvm_init_tlb_tags(unsigned int nr) · line 8225

Quoted 8 lines
arch/x86/kvm/mmu/mmu.c +1 -6
-       /*
-        * 0 is the host's TLB tag for both VMX's VPID and SVM's ASID, and is
-        * returned on failed allocations (e.g. no more tags left).
-        */
-       __set_bit(0, tlb_tags.bitmap);
-
        tlb_tags.nr = nr;
+       tlb_tags.start = nr_reserved;

Can you also clear tlb_tags.start in kvm_destroy_tlb_tags()?

Can do.

#14 lore raw

PATCH v3 5/27 KVM: SVM: Add helpers to set/clear ASID flush in VMCB

In reply to Yosry Ahmed

Introduce set/clear helpers to set tlb_ctl to TLB_CONTROL_FLUSH_ASID or TLB_CONTROL_DO_NOTHING. Incoming changes will eliminate the use of TLB_CONTROL_FLUSH_ALL_ASID except as a fallback when FLUSHBYASID is not available, so the helpers will create a common path for this.

---
 arch/x86/kvm/svm/nested.c |  2 +-
 arch/x86/kvm/svm/sev.c    |  2 +-
 arch/x86/kvm/svm/svm.c    |  4 ++--
 arch/x86/kvm/svm/svm.h    | 10 ++++++++++
 4 files changed, 14 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/nested.c +1 -1
index 2bfc9d2c341b1..c3c12a4d6fe07 100644
@@ -939,7 +939,7 @@ static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
 	/* Done at vmrun: asid.  */
 
 	/* Also overwritten later if necessary.  */
-	vmcb02->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
+	vmcb_clr_flush_asid(vmcb02);
 
 	/* Use vmcb01 MMU and format if guest does not use nNPT */
 	if (nested_npt_enabled(svm)) {
arch/x86/kvm/svm/sev.c +1 -1
index fad72cab76cf4..74c4555a32650 100644
@@ -3637,7 +3637,7 @@ int pre_sev_run(struct vcpu_svm *svm, int cpu)
 		return 0;
 
 	sd->sev_vmcbs[asid] = svm->vmcb;
-	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+	vmcb_set_flush_asid(svm->vmcb);
 	return 0;
 }
 
arch/x86/kvm/svm/svm.c +2 -2
index 136069dfcd44f..ad4f172f170d9 100644
@@ -4327,7 +4327,7 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
 	 * VM-Exit (via kvm_mmu_reset_context()).
 	 */
 	if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
-		svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+		vmcb_set_flush_asid(svm->vmcb);
 	else
 		svm->current_vmcb->asid_generation--;
 }
@@ -4746,7 +4746,7 @@ static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags)
 
 	if (!svm_is_vmrun_failure(svm->vmcb->control.exit_code)) {
 		this_cpu_ptr(&svm_data)->flush_all_asids = false;
-		svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
+		vmcb_clr_flush_asid(svm->vmcb);
 
 		/*
 		 * Unconditionally mask off the CLEAR_RAP bit, the AND is just
arch/x86/kvm/svm/svm.h +10 -0
index 6d0242966dc87..ba5077b9838c0 100644
@@ -480,6 +480,16 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
 	vmcb_mark_dirty(vmcb, VMCB_NPT);
 }
 
+static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
+{
+	vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+}
+
+static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)
+{
+	vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
+}
+
 static __always_inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
 {
 	return container_of(vcpu, struct vcpu_svm, vcpu);
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#15 lore raw

Re: [PATCH v3 05/27] KVM: SVM: Add helpers to set/clear ASID flush in VMCB

Quoted 6 lines · Yosry Ahmed

Introduce set/clear helpers to set tlb_ctl to TLB_CONTROL_FLUSH_ASID or TLB_CONTROL_DO_NOTHING. Incoming changes will eliminate the use of TLB_CONTROL_FLUSH_ALL_ASID except as a fallback when FLUSHBYASID is not available, so the helpers will create a common path for this.

No functional change intended? :)

Quoted 9 lines
---
 arch/x86/kvm/svm/nested.c |  2 +-
 arch/x86/kvm/svm/sev.c    |  2 +-
 arch/x86/kvm/svm/svm.c    |  4 ++--
 arch/x86/kvm/svm/svm.h    | 10 ++++++++++
 4 files changed, 14 insertions(+), 4 deletions(-)

[ ... ]

Quoted 5 lines
arch/x86/kvm/svm/svm.h +0 -0
index 6d0242966dc87..ba5077b9838c0 100644

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 9 lines
arch/x86/kvm/svm/svm.h +6 -0
@@ -480,6 +480,16 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
        vmcb_mark_dirty(vmcb, VMCB_NPT);
 }
 
+static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
+{
+       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+}
+
+static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)

The name of this function makes it sound like the inverse of vmcb_set_flush_asid(), which it isn't. Maybe vmcb_clr_tlb_ctl()?

Quoted 10 lines
arch/x86/kvm/svm/svm.h +4 -1
+{
+       vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
+}
+
 static __always_inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
 {
        return container_of(vcpu, struct vcpu_svm, vcpu);
--

2.56.0.385.gd3acb90ef8-goog

#16 lore raw

Re: [PATCH v3 05/27] KVM: SVM: Add helpers to set/clear ASID flush in VMCB

Quoted 29 lines · Jim Mattson
Quoted 6 lines · Yosry Ahmed

Introduce set/clear helpers to set tlb_ctl to TLB_CONTROL_FLUSH_ASID or TLB_CONTROL_DO_NOTHING. Incoming changes will eliminate the use of TLB_CONTROL_FLUSH_ALL_ASID except as a fallback when FLUSHBYASID is not available, so the helpers will create a common path for this.

No functional change intended? :)

Quoted 9 lines
---
 arch/x86/kvm/svm/nested.c |  2 +-
 arch/x86/kvm/svm/sev.c    |  2 +-
 arch/x86/kvm/svm/svm.c    |  4 ++--
 arch/x86/kvm/svm/svm.h    | 10 ++++++++++
 4 files changed, 14 insertions(+), 4 deletions(-)

[ ... ]

Quoted 8 lines
arch/x86/kvm/svm/svm.h +0 -0
index 6d0242966dc87..ba5077b9838c0 100644
@@ -480,6 +480,16 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
        vmcb_mark_dirty(vmcb, VMCB_NPT);
 }
 
Quoted 9 lines

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 6 lines
arch/x86/kvm/svm/svm.h +6 -0
+static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
+{
+       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+}
+
+static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)

The name of this function makes it sound like the inverse of vmcb_set_flush_asid(), which it isn't. Maybe vmcb_clr_tlb_ctl()?

Why not? vmcb_set_flush_asid() sets FLUSH_ASID and vmcb_clr_flush_asid() clears it, right?

Quoted 11 lines
Quoted 11 lines
arch/x86/kvm/svm/svm.h +4 -1
+{
+       vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
+}
+
 static __always_inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
 {
        return container_of(vcpu, struct vcpu_svm, vcpu);
--

2.56.0.385.gd3acb90ef8-goog

#17 lore raw

Re: [PATCH v3 05/27] KVM: SVM: Add helpers to set/clear ASID flush in VMCB

Quoted 41 lines · Yosry Ahmed
Quoted 29 lines · Jim Mattson
Quoted 6 lines · Yosry Ahmed

Introduce set/clear helpers to set tlb_ctl to TLB_CONTROL_FLUSH_ASID or TLB_CONTROL_DO_NOTHING. Incoming changes will eliminate the use of TLB_CONTROL_FLUSH_ALL_ASID except as a fallback when FLUSHBYASID is not available, so the helpers will create a common path for this.

No functional change intended? :)

Quoted 9 lines
---
 arch/x86/kvm/svm/nested.c |  2 +-
 arch/x86/kvm/svm/sev.c    |  2 +-
 arch/x86/kvm/svm/svm.c    |  4 ++--
 arch/x86/kvm/svm/svm.h    | 10 ++++++++++
 4 files changed, 14 insertions(+), 4 deletions(-)

[ ... ]

Quoted 8 lines
arch/x86/kvm/svm/svm.h +0 -0
index 6d0242966dc87..ba5077b9838c0 100644
@@ -480,6 +480,16 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
        vmcb_mark_dirty(vmcb, VMCB_NPT);
 }
 
Quoted 9 lines

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 6 lines
arch/x86/kvm/svm/svm.h +6 -0
+static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
+{
+       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+}
+
+static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)

The name of this function makes it sound like the inverse of vmcb_set_flush_asid(), which it isn't. Maybe vmcb_clr_tlb_ctl()?

Quoted 2 lines

Why not? vmcb_set_flush_asid() sets FLUSH_ASID and vmcb_clr_flush_asid() clears it, right?

Not exactly. The tlb_ctl field is not a boolean.

vmcb_set_flush_asid() sets tlb_ctl to 3 (flush current ASID). vmcb_clr_flush_asid() sets tlb_ctl to 0 (do not flush).

Other legal values are 1 (flush entire TLB) and 7 (flush non-global entries of current ASID).

And, in fact, these values were chosen so that older hardware would see both 3 and 7 as "flush entire TLB."

So, it's a little more nuanced than set and clear "flush by ASID."

Maybe vmcb_set_flush_asid() and vmcb_set_flush_nothing()?

#18 lore raw

Re: [PATCH v3 05/27] KVM: SVM: Add helpers to set/clear ASID flush in VMCB

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 6 lines
arch/x86/kvm/svm/svm.h +6 -0
+static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
+{
+       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+}
+
+static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)

The name of this function makes it sound like the inverse of vmcb_set_flush_asid(), which it isn't. Maybe vmcb_clr_tlb_ctl()?

Quoted 4 lines
Quoted 2 lines

Why not? vmcb_set_flush_asid() sets FLUSH_ASID and vmcb_clr_flush_asid() clears it, right?

Not exactly. The tlb_ctl field is not a boolean.

Right, but the current implementation treats it as such (with the exception of falling back to FLUSH_ALL_ASID, but that becomes transparent to the callers).

Quoted 11 lines

vmcb_set_flush_asid() sets tlb_ctl to 3 (flush current ASID). vmcb_clr_flush_asid() sets tlb_ctl to 0 (do not flush).

Other legal values are 1 (flush entire TLB) and 7 (flush non-global entries of current ASID).

And, in fact, these values were chosen so that older hardware would see both 3 and 7 as "flush entire TLB."

So, it's a little more nuanced than set and clear "flush by ASID."

I agree, I chose to abstract it as a boolean, but I understand it can be confusing.

Quoted 2 lines

Maybe vmcb_set_flush_asid() and vmcb_set_flush_nothing()?

I would prefer vmcb_set_flush_asid() and vmcb_set_no_flush().

#19 lore raw

Re: [PATCH v3 05/27] KVM: SVM: Add helpers to set/clear ASID flush in VMCB

Quoted 1 line · Yosry Ahmed

I would prefer vmcb_set_flush_asid() and vmcb_set_no_flush().

SGTM

#20 lore raw

PATCH v3 6/27 KVM: SVM: Fallback to flush everything if FLUSHBYASID is not available

In reply to Yosry Ahmed

Currently, if FLUSHBYASID is not available when performing a TLB flush, the fallback is decrementing the ASID generation to trigger allocating a new ASID. In preparation for using a static ASID per vCPU (like VMX), just fallback to flushing everything if FLUSHBYASID is not available. This is probably worse from a performance perspective, but FLUSHBYASID has been around for ~15 years and it's not worth carrying the complexity.

Move the fallback logic into vmcb_set_flush_asid(), as more callers will be added and will need the fallback as well. The only other current caller is from SEV code, and no CPUs support SEV but not FLUSHBYASID (at least according to AI).

---
 arch/x86/kvm/svm/svm.c | 5 +----
 arch/x86/kvm/svm/svm.h | 5 ++++-
 2 files changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/svm.c +1 -4
index ad4f172f170d9..0c3befd9bc850 100644
@@ -4326,10 +4326,7 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
 	 * unconditionally does a TLB flush on both nested VM-Enter and nested
 	 * VM-Exit (via kvm_mmu_reset_context()).
 	 */
-	if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
-		vmcb_set_flush_asid(svm->vmcb);
-	else
-		svm->current_vmcb->asid_generation--;
+	vmcb_set_flush_asid(svm->vmcb);
 }
 
 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +4 -1
index ba5077b9838c0..3b59561d6cc2c 100644
@@ -482,7 +482,10 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
 
 static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
 {
-	vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+	if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
+		vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+	else
+		vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
 }
 
 static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#21 lore raw

Re: [PATCH v3 06/27] KVM: SVM: Fallback to flush everything if FLUSHBYASID is not available

Quoted 9 lines · Yosry Ahmed

Currently, if FLUSHBYASID is not available when performing a TLB flush, the fallback is decrementing the ASID generation to trigger allocating a new ASID. In preparation for using a static ASID per vCPU (like VMX), just fallback to flushing everything if FLUSHBYASID is not available. This is probably worse from a performance perspective, but FLUSHBYASID has been around for ~15 years and it's not worth carrying the complexity.

Quoted 4 lines

Move the fallback logic into vmcb_set_flush_asid(), as more callers will be added and will need the fallback as well. The only other current caller is from SEV code, and no CPUs support SEV but not FLUSHBYASID (at least according to AI).

A more compelling argument is that sev_hardware_setup() requires FLUSHBYASID.

Quoted 28 lines
---
 arch/x86/kvm/svm/svm.c | 5 +----
 arch/x86/kvm/svm/svm.h | 5 ++++-
 2 files changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/svm.c +1 -4
index ad4f172f170d9..0c3befd9bc850 100644
@@ -4326,10 +4326,7 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
         * unconditionally does a TLB flush on both nested VM-Enter and nested
         * VM-Exit (via kvm_mmu_reset_context()).
         */
-       if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
-               vmcb_set_flush_asid(svm->vmcb);
-       else
-               svm->current_vmcb->asid_generation--;
+       vmcb_set_flush_asid(svm->vmcb);
 }
 
 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +0 -0
index ba5077b9838c0..3b59561d6cc2c 100644

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 8 lines
arch/x86/kvm/svm/svm.h +4 -1
@@ -482,7 +482,10 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
 
 static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
 {
-       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+       if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
+               vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+       else
+               vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;

This is unnecessary. Hardware that doesn't have FLUSHBYASID only looks at tlb_ctl bit 0 to decide whether or not to flush the entire TLB. The other bits are ignored.

Quoted 6 lines
arch/x86/kvm/svm/svm.h +0 -1
 }
 
 static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)
--

2.56.0.385.gd3acb90ef8-goog

#22 lore raw

Re: [PATCH v3 06/27] KVM: SVM: Fallback to flush everything if FLUSHBYASID is not available

Quoted 11 lines · Jim Mattson
Quoted 9 lines · Yosry Ahmed

Currently, if FLUSHBYASID is not available when performing a TLB flush, the fallback is decrementing the ASID generation to trigger allocating a new ASID. In preparation for using a static ASID per vCPU (like VMX), just fallback to flushing everything if FLUSHBYASID is not available. This is probably worse from a performance perspective, but FLUSHBYASID has been around for ~15 years and it's not worth carrying the complexity.

Quoted 6 lines
Quoted 4 lines

Move the fallback logic into vmcb_set_flush_asid(), as more callers will be added and will need the fallback as well. The only other current caller is from SEV code, and no CPUs support SEV but not FLUSHBYASID (at least according to AI).

A more compelling argument is that sev_hardware_setup() requires FLUSHBYASID.

Huh, I didn't realize this.

Quoted 30 lines
Quoted 30 lines
---
 arch/x86/kvm/svm/svm.c | 5 +----
 arch/x86/kvm/svm/svm.h | 5 ++++-
 2 files changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/svm.c +1 -4
index ad4f172f170d9..0c3befd9bc850 100644
@@ -4326,10 +4326,7 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
         * unconditionally does a TLB flush on both nested VM-Enter and nested
         * VM-Exit (via kvm_mmu_reset_context()).
         */
-       if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
-               vmcb_set_flush_asid(svm->vmcb);
-       else
-               svm->current_vmcb->asid_generation--;
+       vmcb_set_flush_asid(svm->vmcb);
 }
 
 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +0 -0
index ba5077b9838c0..3b59561d6cc2c 100644
@@ -482,7 +482,10 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
 
Quoted 11 lines

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 7 lines
arch/x86/kvm/svm/svm.h +4 -1
 static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
 {
-       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+       if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
+               vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+       else
+               vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;

This is unnecessary. Hardware that doesn't have FLUSHBYASID only looks at tlb_ctl bit 0 to decide whether or not to flush the entire TLB. The other bits are ignored.

I think it's clearer to do the fallback since the APM doesn't specifically call this out, or maybe it does but I can't find it.

Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/svm/svm.h +0 -1
 }
 
 static inline void vmcb_clr_flush_asid(struct vmcb *vmcb)
--

2.56.0.385.gd3acb90ef8-goog

#23 lore raw

Re: [PATCH v3 06/27] KVM: SVM: Fallback to flush everything if FLUSHBYASID is not available

Quoted 64 lines · Yosry Ahmed
Quoted 11 lines · Jim Mattson
Quoted 9 lines · Yosry Ahmed

Currently, if FLUSHBYASID is not available when performing a TLB flush, the fallback is decrementing the ASID generation to trigger allocating a new ASID. In preparation for using a static ASID per vCPU (like VMX), just fallback to flushing everything if FLUSHBYASID is not available. This is probably worse from a performance perspective, but FLUSHBYASID has been around for ~15 years and it's not worth carrying the complexity.

Quoted 6 lines
Quoted 4 lines

Move the fallback logic into vmcb_set_flush_asid(), as more callers will be added and will need the fallback as well. The only other current caller is from SEV code, and no CPUs support SEV but not FLUSHBYASID (at least according to AI).

A more compelling argument is that sev_hardware_setup() requires FLUSHBYASID.

Huh, I didn't realize this.

Quoted 30 lines
Quoted 30 lines
---
 arch/x86/kvm/svm/svm.c | 5 +----
 arch/x86/kvm/svm/svm.h | 5 ++++-
 2 files changed, 5 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/svm.c +1 -4
index ad4f172f170d9..0c3befd9bc850 100644
@@ -4326,10 +4326,7 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
         * unconditionally does a TLB flush on both nested VM-Enter and nested
         * VM-Exit (via kvm_mmu_reset_context()).
         */
-       if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
-               vmcb_set_flush_asid(svm->vmcb);
-       else
-               svm->current_vmcb->asid_generation--;
+       vmcb_set_flush_asid(svm->vmcb);
 }
 
 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +0 -0
index ba5077b9838c0..3b59561d6cc2c 100644
@@ -482,7 +482,10 @@ static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data)
 
Quoted 11 lines

arch/x86/kvm/svm/svm.h static inline void vmcb_set_gpat(struct vmcb *vmcb, u64 data) · line 488

Quoted 7 lines
arch/x86/kvm/svm/svm.h +4 -1
 static inline void vmcb_set_flush_asid(struct vmcb *vmcb)
 {
-       vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+       if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
+               vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
+       else
+               vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;

This is unnecessary. Hardware that doesn't have FLUSHBYASID only looks at tlb_ctl bit 0 to decide whether or not to flush the entire TLB. The other bits are ignored.

Quoted 2 lines

I think it's clearer to do the fallback since the APM doesn't specifically call this out, or maybe it does but I can't find it.

Fair point. I dug up a copy of the SVM manual from 2005, and it actually seems to indicate that there isn't a bit toggle, but rather the entire field value is consulted:

Quoted 1 line

The TLB_CONTROL field in the VMCB currently has one command implemented. When the VMM sets the TLB_CONTROL field to 1, the VMRUN instruction flushes the TLB for all ASIDs, for both global and non-global pages.

That isn't how the hardware works, though.

#24 lore raw

PATCH v3 7/27 KVM: SEV: Do ASID initialization at VMCB initialization

In reply to Yosry Ahmed

The per-vCPU ASID does not change for SEV guests, so move the per-vCPU (and per-VMCB) ASID initialization to sev_init_vmcb() to do it once, instead of setting it before every VMRUN.

No functional change intended.

---
 arch/x86/kvm/svm/sev.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
arch/x86/kvm/svm/sev.c +4 -3
index 74c4555a32650..b58e3831b8f05 100644
@@ -3623,9 +3623,6 @@ int pre_sev_run(struct vcpu_svm *svm, int cpu)
 	if (!cpumask_test_cpu(cpu, to_kvm_sev_info(kvm)->have_run_cpus))
 		cpumask_set_cpu(cpu, to_kvm_sev_info(kvm)->have_run_cpus);
 
-	/* Assign the asid allocated with this SEV guest */
-	svm->asid = asid;
-
 	/*
 	 * Flush guest TLB:
 	 *
@@ -4889,6 +4886,10 @@ void sev_init_vmcb(struct vcpu_svm *svm, bool init_event)
 	svm->vmcb->control.misc_ctl |= SVM_MISC_ENABLE_SEV;
 	clr_exception_intercept(svm, UD_VECTOR);
 
+	svm->asid = sev_get_asid(vcpu->kvm);
+	svm->vmcb->control.asid = svm->asid;
+	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
+
 	/*
 	 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as
 	 * KVM can't decrypt guest memory to decode the faulting instruction.
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 7/27
#25 lore raw

Re: [PATCH v3 07/27] KVM: SEV: Do ASID initialization at VMCB initialization

Quoted 8 lines · Yosry Ahmed

The per-vCPU ASID does not change for SEV guests, so move the per-vCPU (and per-VMCB) ASID initialization to sev_init_vmcb() to do it once, instead of setting it before every VMRUN.

No functional change intended.

#26 lore raw

PATCH v3 8/27 KVM: SEV: Expose sev_get_asid() outside of sev.c

In reply to Yosry Ahmed

Move the function definition to svm.h in preparation for using it in more SVM code.

No functional change intended.

---
 arch/x86/kvm/svm/sev.c |  5 -----
 arch/x86/kvm/svm/svm.h | 10 ++++++++++
 2 files changed, 10 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/sev.c +0 -5
index b58e3831b8f05..706a91db7b44a 100644
@@ -315,11 +315,6 @@ static int sev_asid_new(struct kvm_sev_info *sev, unsigned long vm_type)
 	return ret;
 }
 
-static unsigned int sev_get_asid(struct kvm *kvm)
-{
-	return to_kvm_sev_info(kvm)->asid;
-}
-
 static void sev_asid_free(struct kvm_sev_info *sev)
 {
 	struct svm_cpu_data *sd;
arch/x86/kvm/svm/svm.h +10 -0
index 3b59561d6cc2c..14b57c5cdf916 100644
@@ -432,6 +432,11 @@ static __always_inline bool is_sev_snp_guest(struct kvm_vcpu *vcpu)
 {
 	return ____sev_snp_guest(vcpu->kvm);
 }
+
+static __always_inline unsigned int sev_get_asid(struct kvm *kvm)
+{
+	return to_kvm_sev_info(kvm)->asid;
+}
 #else
 static __always_inline bool is_sev_guest(struct kvm_vcpu *vcpu)
 {
@@ -446,6 +451,11 @@ static __always_inline bool is_sev_snp_guest(struct kvm_vcpu *vcpu)
 {
 	return false;
 }
+
+static __always_inline unsigned int sev_get_asid(struct kvm *kvm)
+{
+	return 0;
+}
 #endif
 
 static inline bool ghcb_gpa_is_registered(struct vcpu_svm *svm, u64 val)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#28 lore raw

PATCH v3 9/27 KVM: SEV: Explicitly initialize the per vCPU ASID on SEV VM migration

In reply to Yosry Ahmed

Explicitly initialize svm->asid on the destination vCPUs as part of SEV VM migration, before calling sev_init_vmcb() to make sure the per-vCPU ASID is initialized before the VMCB. This is currently unnecessary as sev_init_vmcb() initializes the per-vCPU ASID anyway, but will be needed when the ASID initialization is moved to vCPU creation.

Add a helper function for the ASID migration as more changes will be needed with incoming changes.

Note that svm->asid is left as-is on the source vCPUs, even though the ASID now belongs to the destination VM. Clearing it would be a nice hardening measure, but it is not as simple as clearing src_svm->asid, as the source and destination VMs do not necessarily have the same number of vCPUs (e.g. for non SEV-ES), so NULL-handling would be needed in a couple of places. Leave it alone for now.

---
 arch/x86/kvm/svm/sev.c | 7 +++++++
 1 file changed, 7 insertions(+)
arch/x86/kvm/svm/sev.c +7 -0
index 706a91db7b44a..0fbb72d57e6da 100644
@@ -2032,6 +2032,12 @@ static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
 	atomic_set_release(&src_sev->migration_in_progress, 0);
 }
 
+static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm,
+				  unsigned int asid)
+{
+	dst_svm->asid = asid;
+}
+
 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
 {
 	struct kvm_sev_info *dst = to_kvm_sev_info(dst_kvm);
@@ -2096,6 +2102,7 @@ static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
 	kvm_for_each_vcpu(i, dst_vcpu, dst_kvm) {
 		dst_svm = to_svm(dst_vcpu);
 
+		sev_vcpu_migrate_asid(dst_svm, dst->asid);
 		sev_init_vmcb(dst_svm, false);
 
 		if (!dst->es_active)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 9/27
#29 lore raw

Re: [PATCH v3 09/27] KVM: SEV: Explicitly initialize the per vCPU ASID on SEV VM migration

Quoted 10 lines · Yosry Ahmed

Explicitly initialize svm->asid on the destination vCPUs as part of SEV VM migration, before calling sev_init_vmcb() to make sure the per-vCPU ASID is initialized before the VMCB. This is currently unnecessary as sev_init_vmcb() initializes the per-vCPU ASID anyway, but will be needed when the ASID initialization is moved to vCPU creation.

Add a helper function for the ASID migration as more changes will be needed with incoming changes.

Quoted 8 lines

Note that svm->asid is left as-is on the source vCPUs, even though the ASID now belongs to the destination VM. Clearing it would be a nice hardening measure, but it is not as simple as clearing src_svm->asid, as the source and destination VMs do not necessarily have the same number of vCPUs (e.g. for non SEV-ES), so NULL-handling would be needed in a couple of places. Leave it alone for now.

#30 lore raw

PATCH v3 10/27 KVM: SVM: Use a static ASID per vCPU

In reply to Yosry Ahmed

Switch from dynamic ASID allocation to a static per-vCPU ASID. The dynamic ASID allocation logic is now only effectively used when running out of ASIDs on a CPU (uncommon on modern hardware), or switching CPUs.

The per-VMCB ASID generation is initialized to 0, which never matches the per-CPU ASID generation (bumped every time a CPU is enabled for virtualization). This leads to a TLB flush of the ASID on the first VMRUN, allocating a new ASID, and bumping the per-VMCB generation to match the per-CPU generation. The ASID remains static until one of the following:

- The vCPU runs on a new CPU, in which case KVM resets the generation of both VMCBs to allocate a new ASID on the new CPU.

- KVM hits the maximum ASID on a CPU and increments the per-CPU ASID generation, at which point all vCPUs on this CPU will allocate a new ASID.

- The CPU is re-enabled for virtualization (e.g. after CPU hotplug), at which point the per-CPU generation is bumped and all vCPUs that previously ran on it will allocate a new ASID.

Drop the complexity and make the ASID static for each vCPU. This makes SVM's handling of ASIDs closer to VMX's handling of VPIDs, and simplifies the code. It also completely avoids full TLB flushes (i.e. TLB_CONTROL_FLUSH_ALL_ASID) on systems with FlushByAsid. Full flushes previously happened when updating the generation, so not so common, but should generally be avoided as they cause a VMRUN to invalidate the TLB entries for other VMs as well as the host.

When a vCPU is migrated to a new physical CPU, flush the (now static) ASID instead of allocating a new one. This might cause extra TLB flushes when switching CPUs (compared to just using a new ASID), but odds are that the TLB is cold on the new CPU anyway.

Static ASIDs also make the following fixes to the dynamic ASID allocation scheme unnecessary, so drop them:

- Bumping the per-CPU generation when enabling virtualization on a CPU, added by commit 25f744ffa0c8 ("KVM: SVM: Bump asid_generation on CPU online to avoid ASID collision after hotplug"). A vCPU can no longer run with an ASID that is (re)assigned to another vCPU.

- Resetting the generation of both VMCBs on a CPU switch, added by commit bf260dc9e7b8 ("KVM: SVM: Trigger new ASID allocation in both VMCBs on pCPU switch"). An ASID is now owned by the same vCPU on all CPUs, so a VMCB that misses a CPU switch can no longer end up using an ASID owned by another vCPU on that CPU.

- Tracking a pending full flush per-CPU (i.e. flush_all_asids), added by commit 60d93c27859f ("KVM: SVM: Preserve TLB control (i.e. pending TLB flush) on failed VMRUN"). The full flush on generation wraparound was needed on behalf of all vCPUs on the CPU, as their ASIDs were about to be recycled, so it had to be tracked per-CPU instead of in the VMCB of the vCPU that happened to trigger the wraparound. With static ASIDs, TLB flushes are only needed for the vCPU's own ASID, so tracking them in the VMCB is sufficient, and a pending flush in the VMCB is still preserved on a failed VMRUN.

As using ASIDs cannot be disabled like VPIDs, allocate a fallback ASID to be shared by all vCPUs after running out of ASIDs (and flushed on every vCPU run, for now). If a fallback ASID cannot be allocated, fail vCPU creation (for non-SEV guests), but do not fail SVM initialization, to allow for allocating all ASIDs for SEV (if at all possible).

For SEV, the same ASID continues to be used by all vCPUs in a VM. Move svm->asid initialization from SEV-specific VMCB initialization to vCPU creation, such that svm->asid is always initialized on vCPU creation for both SEV and non-SEV vCPUs. This makes the logic simpler to follow, and makes it easier to hide it in allocate_asid() and free_asid() helpers. Decide whether to free an ASID based on the ASID range rather than the VM type, as an SEV VM's vCPUs may stop being SEV vCPUs (or vice versa) as a result of SEV VM migration.

Keep the ASID initialization in sev_init_vmcb(), even though it's already done in init_vmcb(), to handle SEV VM migration. svm->asid is already reinitialized on destination SEV VMs during migration before VMCB initialization, so the ASID ends up correctly in the VMCB. Additionally, free any existing non-SEV ASID on the destination vCPU before overwriting it, to avoid leaking ASIDs when creating vCPUs then migrating an SEV VM onto them.

Note: A nice side-effect is reading the min/max ASIDs once during initialization, instead of once per-CPU.

---
 arch/x86/kvm/svm/nested.c |  4 +-
 arch/x86/kvm/svm/sev.c    |  7 +++-
 arch/x86/kvm/svm/svm.c    | 79 +++++++++++++++------------------------
 arch/x86/kvm/svm/svm.h    | 25 +++++++++----
 4 files changed, 55 insertions(+), 60 deletions(-)
arch/x86/kvm/svm/nested.c +2 -2
index c3c12a4d6fe07..5d63ae47ebb6c 100644
@@ -936,9 +936,9 @@ static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
 	else
 		vmcb02->control.bus_lock_counter = 0;
 
-	/* Done at vmrun: asid.  */
+	vmcb02->control.asid = vmcb01->control.asid;
 
-	/* Also overwritten later if necessary.  */
+	/* Overwritten later if necessary.  */
 	vmcb_clr_flush_asid(vmcb02);
 
 	/* Use vmcb01 MMU and format if guest does not use nNPT */
arch/x86/kvm/svm/sev.c +6 -1
index 0fbb72d57e6da..99577859e1aab 100644
@@ -2035,6 +2035,11 @@ static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
 static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm,
 				  unsigned int asid)
 {
+	/*
+	 * Free the (potentially non-SEV) ASID on the destination vCPU before
+	 * setting the new SEV ASID.
+	 */
+	free_asid(dst_svm->asid);
 	dst_svm->asid = asid;
 }
 
@@ -4888,7 +4893,7 @@ void sev_init_vmcb(struct vcpu_svm *svm, bool init_event)
 	svm->vmcb->control.misc_ctl |= SVM_MISC_ENABLE_SEV;
 	clr_exception_intercept(svm, UD_VECTOR);
 
-	svm->asid = sev_get_asid(vcpu->kvm);
+	WARN_ON_ONCE(svm->asid != sev_get_asid(vcpu->kvm));
 	svm->vmcb->control.asid = svm->asid;
 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
 
arch/x86/kvm/svm/svm.c +30 -49

170 lines not on this page · raw message

arch/x86/kvm/svm/svm.h +17 -8
index 14b57c5cdf916..53c5ed2d93d91 100644
@@ -26,6 +26,7 @@
 #include "regs.h"
 #include "x86.h"
 #include "pmu.h"
+#include "mmu.h"
 
 /*
  * Helpers to convert to/from physical addresses for pages whose address is
@@ -145,7 +146,6 @@ struct kvm_vmcb_info {
 	struct vmcb *ptr;
 	unsigned long pa;
 	int cpu;
-	uint64_t asid_generation;
 };
 
 struct vmcb_save_area_cached {
@@ -285,7 +285,7 @@ struct vcpu_svm {
 	struct vmcb *vmcb;
 	struct kvm_vmcb_info vmcb01;
 	struct kvm_vmcb_info *current_vmcb;
-	u32 asid;
+	kvm_tlb_tag_t asid;
 	u32 sysenter_esp_hi;
 	u32 sysenter_eip_hi;
 	uint64_t tsc_aux;
@@ -372,12 +372,6 @@ struct vcpu_svm {
 };
 
 struct svm_cpu_data {
-	u64 asid_generation;
-	u32 max_asid;
-	u32 next_asid;
-	u32 min_asid;
-
-	bool flush_all_asids;
 	bool bp_spec_reduce_set;
 
 	struct vmcb *save_area;
@@ -1080,6 +1074,21 @@ static inline struct vmcb_save_area *sev_decrypt_vmsa(struct kvm_vcpu *vcpu)
 static inline void sev_free_decrypted_vmsa(struct kvm_vcpu *vcpu, struct vmcb_save_area *vmsa) {}
 #endif
 
+extern kvm_tlb_tag_t fallback_asid;
+
+static inline kvm_tlb_tag_t allocate_asid(struct kvm_vcpu *vcpu)
+{
+	if (is_sev_guest(vcpu))
+		return sev_get_asid(vcpu->kvm);
+	return kvm_alloc_tlb_tag() ?: fallback_asid;
+}
+
+static inline void free_asid(kvm_tlb_tag_t asid)
+{
+	if (asid > max_sev_asid && asid != fallback_asid)
+		kvm_free_tlb_tag(asid);
+}
+
 /* vmenter.S */
 
 void __svm_sev_es_vcpu_run(struct vcpu_svm *svm, unsigned int flags,
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#31 lore raw

Re: [PATCH v3 10/27] KVM: SVM: Use a static ASID per vCPU

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] kvm: svm: source SEV VM retains and uses migrated SEV ASID --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] kvm: svm: source SEV VM retains and uses migrated SEV ASID
--

commit 9452efa2aa9c0c4c26d340a238f30fbe12b3e4cc
Author: Yosry Ahmed <[email protected]>

KVM: SVM: Use a static ASID per vCPU

Switch from dynamic ASID allocation to a static per-vCPU ASID. The dynamic ASID allocation logic is now only effectively used when running out of ASIDs on a CPU, or switching CPUs.

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

[ ... ]

Quoted 1 line
arch/x86/kvm/svm/svm.c +0 -0
@@ -3875,37 +3868,24 @@ static void svm_set_nested_run_soft_int_state(struct kvm_vcpu *vcpu)

[ ... ]

Quoted 2 lines

static int pre_svm_run(struct kvm_vcpu *vcpu)
{

[ ... ]

arch/x86/kvm/svm/svm.c static void svm_set_nested_run_soft_int_state(struct kvm_vcpu *vcpu) · line 3891

Quoted 11 lines
arch/x86/kvm/svm/svm.c +2 -3
 	if (is_sev_guest(vcpu))
 		return pre_sev_run(svm, vcpu->cpu);
 
-	/* FIXME: handle wraparound of asid_generation */
-	if (svm->current_vmcb->asid_generation != sd->asid_generation)
-		new_asid(svm, sd);
+	if (unlikely(svm->vmcb->control.asid == fallback_asid))
+		vmcb_set_flush_asid(svm->vmcb);
 
 	return 0;
 }

[Severity: Critical]
When an intra-host SEV VM migration occurs via KVM_VM_MOVE_ENC_CONTEXT_FROM, the migration path in sev_vm_move_enc_context_from() transfers the SEV ASID to the destination VM and marks the source VM as non-SEV by setting sev->active to false. However, the source vCPUs retain the SEV ASID in their svm->asid and vmcb->control.asid.

Previously, this was safely mitigated here in pre_svm_run() because the generation mismatch (the SEV ASID generation was 0) triggered new_asid(), allocating a new normal ASID for the source vCPU.

By removing the generation check here, does this allow a malicious host userspace to execute KVM_RUN on the source vCPUs as non-SEV vCPUs while still using the destination VM's SEV ASID? Could this break SEV confidentiality and integrity by allowing the host to inject arbitrary translations or read data from the destination SEV VM's TLB?

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

Re: [PATCH v3 10/27] KVM: SVM: Use a static ASID per vCPU

Quoted 46 lines · On Mon, Oct 12, 2026 at 4:54 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] kvm: svm: source SEV VM retains and uses migrated SEV ASID
--

commit 9452efa2aa9c0c4c26d340a238f30fbe12b3e4cc
Author: Yosry Ahmed <[email protected]>

KVM: SVM: Use a static ASID per vCPU

Switch from dynamic ASID allocation to a static per-vCPU ASID. The dynamic ASID allocation logic is now only effectively used when running out of ASIDs on a CPU, or switching CPUs.

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

[ ... ]

Quoted 1 line
arch/x86/kvm/svm/svm.c +0 -0
@@ -3875,37 +3868,24 @@ static void svm_set_nested_run_soft_int_state(struct kvm_vcpu *vcpu)

[ ... ]

Quoted 2 lines

static int pre_svm_run(struct kvm_vcpu *vcpu)
{

[ ... ]

arch/x86/kvm/svm/svm.c static void svm_set_nested_run_soft_int_state(struct kvm_vcpu *vcpu) · line 3891

Quoted 11 lines
      if (is_sev_guest(vcpu))
              return pre_sev_run(svm, vcpu->cpu);
arch/x86/kvm/svm/svm.c +2 -3
-     /* FIXME: handle wraparound of asid_generation */
-     if (svm->current_vmcb->asid_generation != sd->asid_generation)
-             new_asid(svm, sd);
+     if (unlikely(svm->vmcb->control.asid == fallback_asid))
+             vmcb_set_flush_asid(svm->vmcb);
 
      return 0;
 }

[Severity: Critical]
When an intra-host SEV VM migration occurs via KVM_VM_MOVE_ENC_CONTEXT_FROM, the migration path in sev_vm_move_enc_context_from() transfers the SEV ASID to the destination VM and marks the source VM as non-SEV by setting sev->active to false. However, the source vCPUs retain the SEV ASID in their svm->asid and vmcb->control.asid.

Previously, this was safely mitigated here in pre_svm_run() because the generation mismatch (the SEV ASID generation was 0) triggered new_asid(), allocating a new normal ASID for the source vCPU.

Quoted 5 lines

By removing the generation check here, does this allow a malicious host userspace to execute KVM_RUN on the source vCPUs as non-SEV vCPUs while still using the destination VM's SEV ASID? Could this break SEV confidentiality and integrity by allowing the host to inject arbitrary translations or read data from the destination SEV VM's TLB?

As mentioned in the previous version, the sev_vm_move_enc_context_from() prevents the source VM from running again by calling kvm_vm_dead(source_kvm).

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10

#33 lore raw

PATCH v3 11/27 KVM: SVM: Only flush the fallback ASID when used by a different vCPU

In reply to Yosry Ahmed

Instead of always flushing the fallback ASID on every vCPU run, only flush it if the last vCPU that used it on the pCPU changes. This avoids constant TLB flushing on a vCPU using the fallback ASID if no other vCPUs that use the same ASID ran on the same pCPU.

Note that checking (and flushing) the current ASID on vCPU load is not sufficient, as it is possible that a vCPU is using the fallback ASID only for L1 or only for L2. To do this correctly on vCPU load, both L1 and L2 ASIDs would need to be checked, and the respective VMCB would need to be flushed. This would not be much simpler, and would perform unnecessary flushes in some cases (e.g. loading a vCPU that uses the fallback ASID for L2, but L2 doesn't actually run until the vCPU is unloaded).

Another alternative is always flushing on vCPU load if the current ASID is the fallback ASID, and flushing on nested transitions if the new ASID is the fallback ASID. Again, this is not much simpler and also incurs unnecessary flushes in some cases.

Do the logical thing and track the vCPU using the fallback ASID instead.

---
 arch/x86/kvm/svm/svm.c | 13 ++++++++++++-
 arch/x86/kvm/svm/svm.h |  3 +++
 2 files changed, 15 insertions(+), 1 deletion(-)
arch/x86/kvm/svm/svm.c +12 -1
index 8f27722bc4faf..65d6b6fa35b21 100644
@@ -1405,6 +1405,8 @@ static int svm_vcpu_create(struct kvm_vcpu *vcpu)
 static void svm_vcpu_free(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
+	struct svm_cpu_data *sd;
+	int cpu;
 
 	WARN_ON_ONCE(!list_empty(&svm->ir_list));
 
@@ -1422,6 +1424,11 @@ static void svm_vcpu_free(struct kvm_vcpu *vcpu)
 	svm_vcpu_free_msrpm(svm->msrpm);
 
 	free_asid(svm->asid);
+
+	for_each_possible_cpu(cpu) {
+		sd = per_cpu_ptr(&svm_data, cpu);
+		cmpxchg(&sd->fallback_asid_vcpu, vcpu, NULL);
+	}
 }
 
 #ifdef CONFIG_CPU_MITIGATIONS
@@ -3868,6 +3875,7 @@ static void svm_set_nested_run_soft_int_state(struct kvm_vcpu *vcpu)
 
 static int pre_svm_run(struct kvm_vcpu *vcpu)
 {
+	struct svm_cpu_data *sd = this_cpu_ptr(&svm_data);
 	struct vcpu_svm *svm = to_svm(vcpu);
 
 	/*
@@ -3884,8 +3892,11 @@ static int pre_svm_run(struct kvm_vcpu *vcpu)
 	if (is_sev_guest(vcpu))
 		return pre_sev_run(svm, vcpu->cpu);
 
-	if (unlikely(svm->vmcb->control.asid == fallback_asid))
+	if (unlikely(svm->vmcb->control.asid == fallback_asid &&
+		     READ_ONCE(sd->fallback_asid_vcpu) != vcpu)) {
 		vmcb_set_flush_asid(svm->vmcb);
+		WRITE_ONCE(sd->fallback_asid_vcpu, vcpu);
+	}
 
 	return 0;
 }
arch/x86/kvm/svm/svm.h +3 -0
index 53c5ed2d93d91..d386f2a4f72d7 100644
@@ -377,6 +377,9 @@ struct svm_cpu_data {
 	struct vmcb *save_area;
 	unsigned long save_area_pa;
 
+	/* Last vCPU to use fallback_asid on this CPU */
+	struct kvm_vcpu *fallback_asid_vcpu;
+
 	/* index = sev_asid, value = vmcb pointer */
 	struct vmcb **sev_vmcbs;
 };
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#34 lore raw

Re: [PATCH v3 11/27] KVM: SVM: Only flush the fallback ASID when used by a different vCPU

Quoted 15 lines · Yosry Ahmed

Instead of always flushing the fallback ASID on every vCPU run, only flush it if the last vCPU that used it on the pCPU changes. This avoids constant TLB flushing on a vCPU using the fallback ASID if no other vCPUs that use the same ASID ran on the same pCPU.

Note that checking (and flushing) the current ASID on vCPU load is not sufficient, as it is possible that a vCPU is using the fallback ASID only for L1 or only for L2. To do this correctly on vCPU load, both L1 and L2 ASIDs would need to be checked, and the respective VMCB would need to be flushed. This would not be much simpler, and would perform unnecessary flushes in some cases (e.g. loading a vCPU that uses the fallback ASID for L2, but L2 doesn't actually run until the vCPU is unloaded).

Quoted 6 lines

Another alternative is always flushing on vCPU load if the current ASID is the fallback ASID, and flushing on nested transitions if the new ASID is the fallback ASID. Again, this is not much simpler and also incurs unnecessary flushes in some cases.

Do the logical thing and track the vCPU using the fallback ASID instead.

Wouldn't it be simpler to track the VMCB associated with the fallback ASID on each pCPU? Then, you avoid any confusion regarding whether L1, L2, or both have been assigned the fallback ASID.

#35 lore raw

Re: [PATCH v3 11/27] KVM: SVM: Only flush the fallback ASID when used by a different vCPU

Quoted 22 lines · Jim Mattson
Quoted 20 lines · Yosry Ahmed

Instead of always flushing the fallback ASID on every vCPU run, only flush it if the last vCPU that used it on the pCPU changes. This avoids constant TLB flushing on a vCPU using the fallback ASID if no other vCPUs that use the same ASID ran on the same pCPU.

Note that checking (and flushing) the current ASID on vCPU load is not sufficient, as it is possible that a vCPU is using the fallback ASID only for L1 or only for L2. To do this correctly on vCPU load, both L1 and L2 ASIDs would need to be checked, and the respective VMCB would need to be flushed. This would not be much simpler, and would perform unnecessary flushes in some cases (e.g. loading a vCPU that uses the fallback ASID for L2, but L2 doesn't actually run until the vCPU is unloaded).

Another alternative is always flushing on vCPU load if the current ASID is the fallback ASID, and flushing on nested transitions if the new ASID is the fallback ASID. Again, this is not much simpler and also incurs unnecessary flushes in some cases.

Quoted 5 lines
Quoted 1 line

Do the logical thing and track the vCPU using the fallback ASID instead.

Wouldn't it be simpler to track the VMCB associated with the fallback ASID on each pCPU? Then, you avoid any confusion regarding whether L1, L2, or both have been assigned the fallback ASID.

It would be if we went with checking the ASID on vCPU and nested transitions. But since we're checking in pre_svm_run(), I don't think it simplifies things. Oh, I guess it doesn't simplify this specific patch, but we don't need to check if both L1 and L2 use the fallback ASID on nested transitions.. but we have to check if they both use the same ASID anyway for SEV.

OTOH, it would make cleanup more complicated, as we'd need to do it in both vCPU freeing and nested freeing.

Did I miss something?

#36 lore raw

Re: [PATCH v3 11/27] KVM: SVM: Only flush the fallback ASID when used by a different vCPU

Quoted 37 lines · Yosry Ahmed
Quoted 22 lines · Jim Mattson
Quoted 20 lines · Yosry Ahmed

Instead of always flushing the fallback ASID on every vCPU run, only flush it if the last vCPU that used it on the pCPU changes. This avoids constant TLB flushing on a vCPU using the fallback ASID if no other vCPUs that use the same ASID ran on the same pCPU.

Note that checking (and flushing) the current ASID on vCPU load is not sufficient, as it is possible that a vCPU is using the fallback ASID only for L1 or only for L2. To do this correctly on vCPU load, both L1 and L2 ASIDs would need to be checked, and the respective VMCB would need to be flushed. This would not be much simpler, and would perform unnecessary flushes in some cases (e.g. loading a vCPU that uses the fallback ASID for L2, but L2 doesn't actually run until the vCPU is unloaded).

Another alternative is always flushing on vCPU load if the current ASID is the fallback ASID, and flushing on nested transitions if the new ASID is the fallback ASID. Again, this is not much simpler and also incurs unnecessary flushes in some cases.

Quoted 5 lines
Quoted 1 line

Do the logical thing and track the vCPU using the fallback ASID instead.

Wouldn't it be simpler to track the VMCB associated with the fallback ASID on each pCPU? Then, you avoid any confusion regarding whether L1, L2, or both have been assigned the fallback ASID.

It would be if we went with checking the ASID on vCPU and nested transitions. But since we're checking in pre_svm_run(), I don't think it simplifies things. Oh, I guess it doesn't simplify this specific patch, but we don't need to check if both L1 and L2 use the fallback ASID on nested transitions.. but we have to check if they both use the same ASID anyway for SEV.

Quoted 4 lines

OTOH, it would make cleanup more complicated, as we'd need to do it in both vCPU freeing and nested freeing.

Did I miss something?

I trust your judgment.

#37 lore raw

PATCH v3 12/27 KVM: nSVM: Drop svm->nested.initialized

In reply to Yosry Ahmed

Do NULL checks on svm->nested.vmcb02.ptr instead of using a dedicated proxy 'initialized' field. Make sure svm->nested.vmcb02.ptr is correctly set to NULL on initialization failures, as it is currently left as a dangling pointer.

This makes it possible to directly do a NULL check on svm->nested.vmcb02.ptr before using it, instead of checking a different field, which is less error-prone.

---
 arch/x86/kvm/svm/nested.c | 14 ++++++--------
 arch/x86/kvm/svm/svm.h    |  2 --
 2 files changed, 6 insertions(+), 10 deletions(-)
arch/x86/kvm/svm/nested.c +6 -8
index 5d63ae47ebb6c..bfb297b7d71ab 100644
@@ -1142,7 +1142,7 @@ int nested_svm_vmrun(struct kvm_vcpu *vcpu)
 		return ret;
 	}
 
-	if (WARN_ON_ONCE(!svm->nested.initialized))
+	if (WARN_ON_ONCE(!svm->nested.vmcb02.ptr))
 		return -EINVAL;
 
 	vmcb12_gpa = kvm_rax_read(vcpu);
@@ -1489,21 +1489,21 @@ int svm_allocate_nested(struct vcpu_svm *svm)
 {
 	struct page *vmcb02_page;
 
-	if (svm->nested.initialized)
+	if (svm->nested.vmcb02.ptr)
 		return 0;
 
 	vmcb02_page = snp_safe_alloc_page();
 	if (!vmcb02_page)
 		return -ENOMEM;
-	svm->nested.vmcb02.ptr = page_address(vmcb02_page);
-	svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
 
 	svm->nested.msrpm = svm_vcpu_alloc_msrpm();
 	if (!svm->nested.msrpm)
 		goto err_free_vmcb02;
 
 	svm->nested.vmcb02.cpu = -1;
-	svm->nested.initialized = true;
+	svm->nested.vmcb02.ptr = page_address(vmcb02_page);
+	svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
+
 	return 0;
 
 err_free_vmcb02:
@@ -1513,7 +1513,7 @@ int svm_allocate_nested(struct vcpu_svm *svm)
 
 void svm_free_nested(struct vcpu_svm *svm)
 {
-	if (!svm->nested.initialized)
+	if (!svm->nested.vmcb02.ptr)
 		return;
 
 	if (WARN_ON_ONCE(svm->vmcb != svm->vmcb01.ptr))
@@ -1533,8 +1533,6 @@ void svm_free_nested(struct vcpu_svm *svm)
 	 * When the vmcb02 is freed, this optimization becomes invalid.
 	 */
 	svm->nested.last_vmcb12_gpa = INVALID_GPA;
-
-	svm->nested.initialized = false;
 }
 
 void svm_leave_nested(struct kvm_vcpu *vcpu)
arch/x86/kvm/svm/svm.h +0 -2
index d386f2a4f72d7..2e1b5481ddd92 100644
@@ -234,8 +234,6 @@ struct svm_nested_state {
 	 */
 	struct vmcb_save_area_cached save;
 
-	bool initialized;
-
 	/*
 	 * Indicates whether MSR bitmap for L2 needs to be rebuilt due to
 	 * changes in MSR bitmap for L1 or switching to a different L2. Note,
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 12/27
#38 lore raw

Re: [PATCH v3 12/27] KVM: nSVM: Drop svm->nested.initialized

Quoted 11 lines · Yosry Ahmed

Do NULL checks on svm->nested.vmcb02.ptr instead of using a dedicated proxy 'initialized' field. Make sure svm->nested.vmcb02.ptr is correctly set to NULL on initialization failures, as it is currently left as a dangling pointer.

This makes it possible to directly do a NULL check on svm->nested.vmcb02.ptr before using it, instead of checking a different field, which is less error-prone.

#39 lore raw

PATCH v3 13/27 KVM: nSVM: Add a placeholder ASID for L2

In reply to Yosry Ahmed

In preparation for introducing a separate ASID for L2, introduce a 'placeholder' ASID that is still the same as L1's ASID. This will facilitate future changes that need to distinguish L1 and L2's ASIDs, before actually using a different ASID for L1 and L2.

On SEV VM migration, copy the new SEV ASID into asid02 and vmcb02, in case nested was already initialized on the destination vCPU before migration.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 5 +++--
 arch/x86/kvm/svm/sev.c    | 9 +++++++++
 arch/x86/kvm/svm/svm.h    | 2 ++
 3 files changed, 14 insertions(+), 2 deletions(-)
arch/x86/kvm/svm/nested.c +3 -2
index bfb297b7d71ab..780132725bb79 100644
@@ -701,7 +701,6 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
 	 *  - Honor L1's request to flush an ASID on nested VMRUN
 	 *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
 	 *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-	 *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST
 	 *
 	 * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
 	 *     NPT guest-physical mappings on VMRUN.
@@ -936,7 +935,7 @@ static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
 	else
 		vmcb02->control.bus_lock_counter = 0;
 
-	vmcb02->control.asid = vmcb01->control.asid;
+	vmcb02->control.asid = svm->nested.asid02;
 
 	/* Overwritten later if necessary.  */
 	vmcb_clr_flush_asid(vmcb02);
@@ -1504,6 +1503,8 @@ int svm_allocate_nested(struct vcpu_svm *svm)
 	svm->nested.vmcb02.ptr = page_address(vmcb02_page);
 	svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
 
+	svm->nested.asid02 = svm->asid;
+
 	return 0;
 
 err_free_vmcb02:
arch/x86/kvm/svm/sev.c +9 -0
index 99577859e1aab..b2e6acfbb081f 100644
@@ -2041,6 +2041,15 @@ static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm,
 	 */
 	free_asid(dst_svm->asid);
 	dst_svm->asid = asid;
+
+	/*
+	 * If nested is already initialized on the destination vCPU, also update
+	 * the nested ASID to match the new SEV ASID.
+	 */
+	if (dst_svm->nested.vmcb02.ptr) {
+		dst_svm->nested.asid02 = asid;
+		dst_svm->nested.vmcb02.ptr->control.asid = asid;
+	}
 }
 
 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
arch/x86/kvm/svm/svm.h +2 -0
index 2e1b5481ddd92..ed67c18e2b900 100644
@@ -234,6 +234,8 @@ struct svm_nested_state {
 	 */
 	struct vmcb_save_area_cached save;
 
+	kvm_tlb_tag_t asid02;
+
 	/*
 	 * Indicates whether MSR bitmap for L2 needs to be rebuilt due to
 	 * changes in MSR bitmap for L1 or switching to a different L2. Note,
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#40 lore raw

Re: [PATCH v3 13/27] KVM: nSVM: Add a placeholder ASID for L2

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] kvm: nSVM: missing vmcb_mark_dirty() when updating L2 ASID in SEV migration --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] kvm: nSVM: missing vmcb_mark_dirty() when updating L2 ASID in SEV migration --

commit c8f241845a6790f522df58195167e95ce8fea046
Author: Yosry Ahmed <[email protected]>

KVM: nSVM: Add a placeholder ASID for L2

This commit adds a placeholder ASID for L2 to prepare for future changes where L1 and L2 will use different ASIDs. It also updates the SEV migration path to copy the new ASID into asid02 and vmcb02 if nested is already initialized on the destination vCPU.

Quoted 4 lines
arch/x86/kvm/svm/sev.c +0 -0
index 99577859e1aab..b2e6acfbb081f 100644

[ ... ]

arch/x86/kvm/svm/sev.c static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm, · line 2051

Quoted 12 lines
arch/x86/kvm/svm/sev.c +8 -0
@@ -2041,6 +2041,15 @@ static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm,
 	 */
 	free_asid(dst_svm->asid);
 	dst_svm->asid = asid;
+
+	/*
+	 * If nested is already initialized on the destination vCPU, also update
+	 * the nested ASID to match the new SEV ASID.
+	 */
+	if (dst_svm->nested.vmcb02.ptr) {
+		dst_svm->nested.asid02 = asid;
+		dst_svm->nested.vmcb02.ptr->control.asid = asid;

[Severity: High]
Does this code need a call to vmcb_mark_dirty(dst_svm->nested.vmcb02.ptr, VMCB_ASID)?

If userspace creates a non-SEV VM, runs it in nested SVM (allocating vmcb02 and caching it on a physical CPU), and then uses it as the destination for an intra-host migration, the migration path updates the ASID here.

If the vCPU is scheduled back onto the same physical CPU, pre_svm_run() skips vmcb_mark_all_dirty(). Since the VMCB_ASID clean bit might still be set from the last exit from L2, could the CPU ignore the new ASID in memory and incorrectly reuse the old non-SEV ASID from its internal VMCB cache?

Quoted 4 lines
arch/x86/kvm/svm/sev.c +1 -0
+	}
 }
 
 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#41 lore raw

Re: [PATCH v3 13/27] KVM: nSVM: Add a placeholder ASID for L2

Quoted 36 lines · On Mon, Oct 12, 2026 at 5:01 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] kvm: nSVM: missing vmcb_mark_dirty() when updating L2 ASID in SEV migration --

commit c8f241845a6790f522df58195167e95ce8fea046
Author: Yosry Ahmed <[email protected]>

KVM: nSVM: Add a placeholder ASID for L2

This commit adds a placeholder ASID for L2 to prepare for future changes where L1 and L2 will use different ASIDs. It also updates the SEV migration path to copy the new ASID into asid02 and vmcb02 if nested is already initialized on the destination vCPU.

Quoted 4 lines
arch/x86/kvm/svm/sev.c +0 -0
index 99577859e1aab..b2e6acfbb081f 100644

[ ... ]

arch/x86/kvm/svm/sev.c static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm, · line 2051

Quoted 12 lines
arch/x86/kvm/svm/sev.c +8 -0
@@ -2041,6 +2041,15 @@ static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm,
       */
      free_asid(dst_svm->asid);
      dst_svm->asid = asid;
+
+     /*
+      * If nested is already initialized on the destination vCPU, also update
+      * the nested ASID to match the new SEV ASID.
+      */
+     if (dst_svm->nested.vmcb02.ptr) {
+             dst_svm->nested.asid02 = asid;
+             dst_svm->nested.vmcb02.ptr->control.asid = asid;

[Severity: High]
Does this code need a call to vmcb_mark_dirty(dst_svm->nested.vmcb02.ptr, VMCB_ASID)?

Quoted 8 lines

If userspace creates a non-SEV VM, runs it in nested SVM (allocating vmcb02 and caching it on a physical CPU), and then uses it as the destination for an intra-host migration, the migration path updates the ASID here.

If the vCPU is scheduled back onto the same physical CPU, pre_svm_run() skips vmcb_mark_all_dirty(). Since the VMCB_ASID clean bit might still be set from the last exit from L2, could the CPU ignore the new ASID in memory and incorrectly reuse the old non-SEV ASID from its internal VMCB cache?

If the migrated SEV has nested enabled, restoring the nested state should mark vmcb02 dirty in svm_set_nested_state(). But yeah we should probably mark VMCB_ASID dirty here. Not sure if this is worth respinning for it tho.

#42 lore raw

Re: [PATCH v3 13/27] KVM: nSVM: Add a placeholder ASID for L2

In reply to Yosry Ahmed
Quoted 24 lines · Yosry Ahmed

In preparation for introducing a separate ASID for L2, introduce a 'placeholder' ASID that is still the same as L1's ASID. This will facilitate future changes that need to distinguish L1 and L2's ASIDs, before actually using a different ASID for L1 and L2.

On SEV VM migration, copy the new SEV ASID into asid02 and vmcb02, in case nested was already initialized on the destination vCPU before migration.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 5 +++--
 arch/x86/kvm/svm/sev.c    | 9 +++++++++
 arch/x86/kvm/svm/svm.h    | 2 ++
 3 files changed, 14 insertions(+), 2 deletions(-)
arch/x86/kvm/svm/nested.c +0 -0
index bfb297b7d71ab..780132725bb79 100644

arch/x86/kvm/svm/nested.c static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu) · line 704

Quoted 4 lines
arch/x86/kvm/svm/nested.c +0 -1
@@ -701,7 +701,6 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
         *  - Honor L1's request to flush an ASID on nested VMRUN
         *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
         *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-        *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST

Um...How does this patch either do this TODO or render it moot?

Quoted 3 lines
arch/x86/kvm/svm/nested.c +0 -0
         *
         * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
         *     NPT guest-physical mappings on VMRUN.

[ ... ]

arch/x86/kvm/svm/nested.c

Quoted 7 lines
arch/x86/kvm/svm/nested.c +7 -0
+       /*
+        * If nested is already initialized on the destination vCPU, also update
+        * the nested ASID to match the new SEV ASID.
+        */
+       if (dst_svm->nested.vmcb02.ptr) {
+               dst_svm->nested.asid02 = asid;
+               dst_svm->nested.vmcb02.ptr->control.asid = asid;

+1 to Sashiko.

#43 lore raw

Re: [PATCH v3 13/27] KVM: nSVM: Add a placeholder ASID for L2

Quoted 21 lines · Jim Mattson
Quoted 19 lines · Yosry Ahmed

In preparation for introducing a separate ASID for L2, introduce a 'placeholder' ASID that is still the same as L1's ASID. This will facilitate future changes that need to distinguish L1 and L2's ASIDs, before actually using a different ASID for L1 and L2.

On SEV VM migration, copy the new SEV ASID into asid02 and vmcb02, in case nested was already initialized on the destination vCPU before migration.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 5 +++--
 arch/x86/kvm/svm/sev.c    | 9 +++++++++
 arch/x86/kvm/svm/svm.h    | 2 ++
 3 files changed, 14 insertions(+), 2 deletions(-)
Quoted 11 lines

arch/x86/kvm/svm/nested.c static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu) · line 704

Quoted 9 lines
arch/x86/kvm/svm/nested.c +0 -1
index bfb297b7d71ab..780132725bb79 100644
@@ -701,7 +701,6 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
         *  - Honor L1's request to flush an ASID on nested VMRUN
         *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
         *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-        *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST

Um...How does this patch either do this TODO or render it moot?

L1 now has a separate ASID from L2, and it's the one we're already flushing with KVM_REQ_TLB_FLUSH_GUEST. It's kinda already moot because we already flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST.. or maybe it's actually *wrong* because KVM_REQ_TLB_FLUSH_GUEST needs to flush the current ASID, not always L1's ASID.

I can drop it separately if that helps.

Quoted 15 lines
Quoted 4 lines
arch/x86/kvm/svm/nested.c +0 -0
         *
         * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
         *     NPT guest-physical mappings on VMRUN.

[ ... ]

arch/x86/kvm/svm/nested.c

Quoted 7 lines
arch/x86/kvm/svm/nested.c +7 -0
+       /*
+        * If nested is already initialized on the destination vCPU, also update
+        * the nested ASID to match the new SEV ASID.
+        */
+       if (dst_svm->nested.vmcb02.ptr) {
+               dst_svm->nested.asid02 = asid;
+               dst_svm->nested.vmcb02.ptr->control.asid = asid;
Quoted 1 line

+1 to Sashiko.

Will do in the next version.

#44 lore raw

Re: [PATCH v3 13/27] KVM: nSVM: Add a placeholder ASID for L2

Quoted 35 lines · Yosry Ahmed
Quoted 21 lines · Jim Mattson
Quoted 19 lines · Yosry Ahmed

In preparation for introducing a separate ASID for L2, introduce a 'placeholder' ASID that is still the same as L1's ASID. This will facilitate future changes that need to distinguish L1 and L2's ASIDs, before actually using a different ASID for L1 and L2.

On SEV VM migration, copy the new SEV ASID into asid02 and vmcb02, in case nested was already initialized on the destination vCPU before migration.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 5 +++--
 arch/x86/kvm/svm/sev.c    | 9 +++++++++
 arch/x86/kvm/svm/svm.h    | 2 ++
 3 files changed, 14 insertions(+), 2 deletions(-)
Quoted 11 lines

arch/x86/kvm/svm/nested.c static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu) · line 704

Quoted 9 lines
arch/x86/kvm/svm/nested.c +0 -1
index bfb297b7d71ab..780132725bb79 100644
@@ -701,7 +701,6 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
         *  - Honor L1's request to flush an ASID on nested VMRUN
         *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
         *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-        *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST

Um...How does this patch either do this TODO or render it moot?

Quoted 7 lines

L1 now has a separate ASID from L2, and it's the one we're already flushing with KVM_REQ_TLB_FLUSH_GUEST. It's kinda already moot because we already flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST.. or maybe it's actually *wrong* because KVM_REQ_TLB_FLUSH_GUEST needs to flush the current ASID, not always L1's ASID.

I can drop it separately if that helps.

You could just explain it in the commit message.

#45 lore raw

Re: [PATCH v3 13/27] KVM: nSVM: Add a placeholder ASID for L2

Quoted 18 lines
Quoted 18 lines
Quoted 11 lines

arch/x86/kvm/svm/nested.c static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu) · line 704

Quoted 9 lines
arch/x86/kvm/svm/nested.c +0 -1
index bfb297b7d71ab..780132725bb79 100644
@@ -701,7 +701,6 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
         *  - Honor L1's request to flush an ASID on nested VMRUN
         *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
         *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-        *  - Flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST

Um...How does this patch either do this TODO or render it moot?

L1 now has a separate ASID from L2, and it's the one we're already flushing with KVM_REQ_TLB_FLUSH_GUEST. It's kinda already moot because we already flush L1's ASID on KVM_REQ_TLB_FLUSH_GUEST.. or maybe it's actually *wrong* because KVM_REQ_TLB_FLUSH_GUEST needs to flush the current ASID, not always L1's ASID.

Quoted 3 lines
Quoted 1 line

I can drop it separately if that helps.

You could just explain it in the commit message.

Will do.

#46 lore raw

PATCH v3 14/27 KVM: x86: hyper-v: Rename kvm_hv_vcpu_purge_flush_tlb()

In reply to Yosry Ahmed

Rename kvm_hv_vcpu_purge_flush_tlb() to kvm_hv_purge_tlb_flush_fifo() to clarify that it purges the TLB flush FIFO, not purge *and* flush the TLB.

No functional change intended.

---
 arch/x86/kvm/hyperv.h  | 4 ++--
 arch/x86/kvm/svm/svm.c | 2 +-
 arch/x86/kvm/x86.c     | 2 +-
 3 files changed, 4 insertions(+), 4 deletions(-)
arch/x86/kvm/hyperv.h +2 -2
index 622a6553e9ac2..03cc65f8cc52d 100644
@@ -312,7 +312,7 @@ static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc
 	return &hv_vcpu->tlb_flush_fifo[i];
 }
 
-static inline void kvm_hv_vcpu_purge_flush_tlb(struct kvm_vcpu *vcpu)
+static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
 {
 	struct kvm_vcpu_hv_tlb_flush_fifo *tlb_flush_fifo;
 
@@ -396,7 +396,7 @@ static inline int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
 {
 	return HV_STATUS_ACCESS_DENIED;
 }
-static inline void kvm_hv_vcpu_purge_flush_tlb(struct kvm_vcpu *vcpu) {}
+static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu) {}
 static inline bool kvm_hv_synic_has_vector(struct kvm_vcpu *vcpu, int vector)
 {
 	return false;
arch/x86/kvm/svm/svm.c +1 -1
index 65d6b6fa35b21..851db95dc3f95 100644
@@ -4308,7 +4308,7 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
 	 * A TLB flush for the current ASID flushes both "host" and "guest" TLB
 	 * entries, and thus is a superset of Hyper-V's fine grained flushing.
 	 */
-	kvm_hv_vcpu_purge_flush_tlb(vcpu);
+	kvm_hv_purge_tlb_flush_fifo(vcpu);
 
 	/*
 	 * Flush only the current ASID even if the TLB flush was invoked via
arch/x86/kvm/x86.c +1 -1
index 32563a91fba99..12eaeaea51633 100644
@@ -2030,7 +2030,7 @@ static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
 	 * grained flushing.
 	 */
-	kvm_hv_vcpu_purge_flush_tlb(vcpu);
+	kvm_hv_purge_tlb_flush_fifo(vcpu);
 }
 
 
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#48 lore raw

PATCH v3 15/27 KVM: x86: hyper-v: Allow purging all TLB flush FIFOs

In reply to Yosry Ahmed

Refactor kvm_hv_purge_tlb_flush_fifo() to introduce an inner helper, __kvm_hv_purge_tlb_flush_fifo(), parameterized by an optional FIFO. If a FIFO is not passed in, all FIFOs are purged.

Note that KVM_REQ_HV_TLB_FLUSH is consumed by __kvm_hv_purge_tlb_flush_fifo(), so a selective purge on one FIFO will render any subsequent non-selective purge useless. This is not a problem because purging TLB flush FIFOs is an optimization (and there are currently no users of the non-selective purges).

No functional change intended as a FIFO is always being passed in now.

---
 arch/x86/kvm/hyperv.h | 25 ++++++++++++++++++-------
 1 file changed, 18 insertions(+), 7 deletions(-)
arch/x86/kvm/hyperv.h +18 -7
index 03cc65f8cc52d..a23ef05c1075c 100644
@@ -312,18 +312,29 @@ static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc
 	return &hv_vcpu->tlb_flush_fifo[i];
 }
 
-static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
+/* Purge pending TLB flushes in @fifo, or in all FIFOs if @fifo is NULL */
+static inline void __kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu,
+						 struct kvm_vcpu_hv_tlb_flush_fifo *fifo)
 {
-	struct kvm_vcpu_hv_tlb_flush_fifo *tlb_flush_fifo;
+	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
+	int i;
 
-	if (!kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
+	if (!hv_vcpu || !kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
 		return;
 
-	tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(vcpu, is_guest_mode(vcpu));
-	if (!tlb_flush_fifo)
-		return;
+	for (i = 0; i < ARRAY_SIZE(hv_vcpu->tlb_flush_fifo); i++) {
+		if (!fifo || fifo == &hv_vcpu->tlb_flush_fifo[i])
+			kfifo_reset_out(&hv_vcpu->tlb_flush_fifo[i].entries);
+	}
+}
+
+static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
+{
+	struct kvm_vcpu_hv_tlb_flush_fifo *fifo;
 
-	kfifo_reset_out(&tlb_flush_fifo->entries);
+	fifo = kvm_hv_get_tlb_flush_fifo(vcpu, is_guest_mode(vcpu));
+	if (fifo)
+		__kvm_hv_purge_tlb_flush_fifo(vcpu, fifo);
 }
 
 static inline bool guest_hv_cpuid_has_l2_tlb_flush(struct kvm_vcpu *vcpu)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#49 lore raw

Re: [PATCH v3 15/27] KVM: x86: hyper-v: Allow purging all TLB flush FIFOs

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] x86/kvm: redundant guest TLB flush due to uncleared KVM_REQ_HV_TLB_FLUSH --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] x86/kvm: redundant guest TLB flush due to uncleared KVM_REQ_HV_TLB_FLUSH --

commit fd7f6324f98d1c559f015e78c148b1f3ca58d78f
Author: Yosry Ahmed <[email protected]>

KVM: x86: hyper-v: Allow purging all TLB flush FIFOs

This commit refactors kvm_hv_purge_tlb_flush_fifo() by introducing an inner helper __kvm_hv_purge_tlb_flush_fifo() to allow purging a specific FIFO or all FIFOs. The refactoring delegates the KVM_REQ_HV_TLB_FLUSH request check to the inner helper, which is now skipped if no FIFO is found.

Quoted 4 lines
arch/x86/kvm/hyperv.h +0 -0
index 03cc65f8cc52d..a23ef05c1075c 100644

[ ... ]

Quoted 9 lines
arch/x86/kvm/hyperv.h +3 -1
@@ -312,18 +312,29 @@ static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc
 	return &hv_vcpu->tlb_flush_fifo[i];
 }
 
-static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
+/* Purge pending TLB flushes in @fifo, or in all FIFOs if @fifo is NULL */
+static inline void __kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu,
+						 struct kvm_vcpu_hv_tlb_flush_fifo *fifo)
 {

[ ... ]

arch/x86/kvm/hyperv.h static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc · line 338

Quoted 9 lines
arch/x86/kvm/hyperv.h +6 -1
+static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
+{
+	struct kvm_vcpu_hv_tlb_flush_fifo *fifo;
 
-	kfifo_reset_out(&tlb_flush_fifo->entries);
+	fifo = kvm_hv_get_tlb_flush_fifo(vcpu, is_guest_mode(vcpu));
+	if (fifo)
+		__kvm_hv_purge_tlb_flush_fifo(vcpu, fifo);
 }

[Severity: Low]
Does this change inadvertently leave the KVM_REQ_HV_TLB_FLUSH bit uncleared when fifo is NULL?

Prior to this patch, kvm_hv_purge_tlb_flush_fifo() unconditionally evaluated and cleared kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) before returning early if the vCPU lacked an initialized Hyper-V state.

With this update, if a Hyper-V VM-wide TLB flush sets the request bit on a vCPU without initialized Hyper-V state, kvm_hv_get_tlb_flush_fifo() returns NULL. The helper __kvm_hv_purge_tlb_flush_fifo() is skipped entirely, meaning the request bit remains uncleared.

If a standard guest TLB flush request arrives and triggers the purge path in kvm_service_local_tlb_flush_requests(), the uncleared Hyper-V request bit will still be pending when execution reaches vcpu_enter_guest():

arch/x86/kvm/x86.c:vcpu_enter_guest() {
        ...
        if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
            kvm_hv_vcpu_flush_tlb(vcpu))
                kvm_vcpu_flush_tlb_guest(vcpu);
        ...
}

Since kvm_hv_vcpu_flush_tlb() fails (returns -EINVAL) for a vCPU without Hyper-V state, would this fallback path execute a second, redundant kvm_vcpu_flush_tlb_guest() operation?

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

Re: [PATCH v3 15/27] KVM: x86: hyper-v: Allow purging all TLB flush FIFOs

Quoted 65 lines · On Mon, Oct 12, 2026 at 4:56 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] x86/kvm: redundant guest TLB flush due to uncleared KVM_REQ_HV_TLB_FLUSH --

commit fd7f6324f98d1c559f015e78c148b1f3ca58d78f
Author: Yosry Ahmed <[email protected]>

KVM: x86: hyper-v: Allow purging all TLB flush FIFOs

This commit refactors kvm_hv_purge_tlb_flush_fifo() by introducing an inner helper __kvm_hv_purge_tlb_flush_fifo() to allow purging a specific FIFO or all FIFOs. The refactoring delegates the KVM_REQ_HV_TLB_FLUSH request check to the inner helper, which is now skipped if no FIFO is found.

Quoted 4 lines
arch/x86/kvm/hyperv.h +0 -0
index 03cc65f8cc52d..a23ef05c1075c 100644

[ ... ]

Quoted 9 lines
arch/x86/kvm/hyperv.h +3 -1
@@ -312,18 +312,29 @@ static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc
      return &hv_vcpu->tlb_flush_fifo[i];
 }
 
-static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
+/* Purge pending TLB flushes in @fifo, or in all FIFOs if @fifo is NULL */
+static inline void __kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu,
+                                              struct kvm_vcpu_hv_tlb_flush_fifo *fifo)
 {

[ ... ]

arch/x86/kvm/hyperv.h static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc · line 338

Quoted 9 lines
arch/x86/kvm/hyperv.h +6 -1
+static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
+{
+     struct kvm_vcpu_hv_tlb_flush_fifo *fifo;
 
-     kfifo_reset_out(&tlb_flush_fifo->entries);
+     fifo = kvm_hv_get_tlb_flush_fifo(vcpu, is_guest_mode(vcpu));
+     if (fifo)
+             __kvm_hv_purge_tlb_flush_fifo(vcpu, fifo);
 }

[Severity: Low]
Does this change inadvertently leave the KVM_REQ_HV_TLB_FLUSH bit uncleared when fifo is NULL?

Prior to this patch, kvm_hv_purge_tlb_flush_fifo() unconditionally evaluated and cleared kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) before returning early if the vCPU lacked an initialized Hyper-V state.

With this update, if a Hyper-V VM-wide TLB flush sets the request bit on a vCPU without initialized Hyper-V state, kvm_hv_get_tlb_flush_fifo() returns NULL. The helper __kvm_hv_purge_tlb_flush_fifo() is skipped entirely, meaning the request bit remains uncleared.

If a standard guest TLB flush request arrives and triggers the purge path in kvm_service_local_tlb_flush_requests(), the uncleared Hyper-V request bit will still be pending when execution reaches vcpu_enter_guest():

arch/x86/kvm/x86.c:vcpu_enter_guest() {
        ...
        if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
            kvm_hv_vcpu_flush_tlb(vcpu))
                kvm_vcpu_flush_tlb_guest(vcpu);
        ...
}
Quoted 3 lines

Since kvm_hv_vcpu_flush_tlb() fails (returns -EINVAL) for a vCPU without Hyper-V state, would this fallback path execute a second, redundant kvm_vcpu_flush_tlb_guest() operation?

Yes, this one seems to be real, although it's not a big deal IIUC.

I defaulted to checking hv_vcpu first as to skip the expensive request check if it's NULL:

if (!hv_vcpu || !kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))

But I think we need to do the opposite to maintain the existing behavior, i.e.:

if (!kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) || !hv_vcpu)

I won't respin for this for now, will wait for more feedback. It can also be folded in probably.

Quoted 3 lines

--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15

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

Re: [PATCH v3 15/27] KVM: x86: hyper-v: Allow purging all TLB flush FIFOs

In reply to Yosry Ahmed
Quoted 11 lines · Yosry Ahmed

Refactor kvm_hv_purge_tlb_flush_fifo() to introduce an inner helper, __kvm_hv_purge_tlb_flush_fifo(), parameterized by an optional FIFO. If a FIFO is not passed in, all FIFOs are purged.

Note that KVM_REQ_HV_TLB_FLUSH is consumed by __kvm_hv_purge_tlb_flush_fifo(), so a selective purge on one FIFO will render any subsequent non-selective purge useless. This is not a problem because purging TLB flush FIFOs is an optimization (and there are currently no users of the non-selective purges).

Quoted 3 lines

No functional change intended as a FIFO is always being passed in now.

#52 lore raw

PATCH v3 16/27 KVM: nSVM: Flush both L1 and L2 ASIDs on KVM_REQ_TLB_FLUSH

In reply to Yosry Ahmed

Flush both L1 and L2 ASIDs in svm_flush_tlb_all() to appropriately handle KVM_REQ_TLB_FLUSH by flushing all TLB entries in all contexts (e.g. for kvm_flush_remote_tlbs()). Since both L1 and L2 currently share an ASID, this is effectively a noop, but it won't be once L2 has a separate ASID.

Purge all Hyper-V TLB FIFOs (for both L1 and L2), since both ASIDs are flushed, and an ASID flush is a superset of Hyper-V's fine-grained flushing (see comment in svm_flush_tlb_asid()).

Note that if one TLB flush FIFO is purged (e.g. as a result of KVM_REQ_TLB_FLUSH_CURRENT), it will consume KVM_REQ_HV_TLB_FLUSH, and a subsequent KVM_REQ_TLB_FLUSH will not flush the other FIFO. This is alright as flushing both FIFOs is a (newly introduced) optimization anyway. The other FIFO will be checked after a nested transition, as KVM_REQ_HV_TLB_FLUSH is always set on nested transitions.

---
 arch/x86/kvm/hyperv.h     | 6 ++++++
 arch/x86/kvm/svm/nested.c | 1 -
 arch/x86/kvm/svm/svm.c    | 8 +++++++-
 3 files changed, 13 insertions(+), 2 deletions(-)
arch/x86/kvm/hyperv.h +6 -0
index a23ef05c1075c..b82f70e6fcea1 100644
@@ -337,6 +337,11 @@ static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu)
 		__kvm_hv_purge_tlb_flush_fifo(vcpu, fifo);
 }
 
+static inline void kvm_hv_purge_all_tlb_flush_fifos(struct kvm_vcpu *vcpu)
+{
+	__kvm_hv_purge_tlb_flush_fifo(vcpu, NULL);
+}
+
 static inline bool guest_hv_cpuid_has_l2_tlb_flush(struct kvm_vcpu *vcpu)
 {
 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
@@ -408,6 +413,7 @@ static inline int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
 	return HV_STATUS_ACCESS_DENIED;
 }
 static inline void kvm_hv_purge_tlb_flush_fifo(struct kvm_vcpu *vcpu) {}
+static inline void kvm_hv_purge_all_tlb_flush_fifos(struct kvm_vcpu *vcpu) {}
 static inline bool kvm_hv_synic_has_vector(struct kvm_vcpu *vcpu, int vector)
 {
 	return false;
arch/x86/kvm/svm/nested.c +0 -1
index 780132725bb79..75ada771026b2 100644
@@ -697,7 +697,6 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
 	 * TODO: optimize unconditional TLB flush/MMU sync.  A partial list of
 	 * things to fix before this can be conditional:
 	 *
-	 *  - Flush TLBs for both L1 and L2 remote TLB flush
 	 *  - Honor L1's request to flush an ASID on nested VMRUN
 	 *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
 	 *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
arch/x86/kvm/svm/svm.c +7 -1
index 851db95dc3f95..97a5577a25d9f 100644
@@ -4338,6 +4338,8 @@ static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
 
 static void svm_flush_tlb_all(struct kvm_vcpu *vcpu)
 {
+	struct vcpu_svm *svm = to_svm(vcpu);
+
 	/*
 	 * When running on Hyper-V with EnlightenedNptTlb enabled, remote TLB
 	 * flushes should be routed to hv_flush_remote_tlbs() without requesting
@@ -4348,7 +4350,11 @@ static void svm_flush_tlb_all(struct kvm_vcpu *vcpu)
 	if (WARN_ON_ONCE(svm_hv_is_enlightened_tlb_enabled(vcpu)))
 		hv_flush_remote_tlbs(vcpu->kvm);
 
-	svm_flush_tlb_asid(vcpu);
+	kvm_hv_purge_all_tlb_flush_fifos(vcpu);
+
+	vmcb_set_flush_asid(svm->vmcb01.ptr);
+	if (svm->nested.vmcb02.ptr)
+		vmcb_set_flush_asid(svm->nested.vmcb02.ptr);
 }
 
 static void svm_flush_tlb_guest(struct kvm_vcpu *vcpu)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 16/27
#53 lore raw

Re: [PATCH v3 16/27] KVM: nSVM: Flush both L1 and L2 ASIDs on KVM_REQ_TLB_FLUSH

Quoted 11 lines · Yosry Ahmed

Flush both L1 and L2 ASIDs in svm_flush_tlb_all() to appropriately handle KVM_REQ_TLB_FLUSH by flushing all TLB entries in all contexts (e.g. for kvm_flush_remote_tlbs()). Since both L1 and L2 currently share an ASID, this is effectively a noop, but it won't be once L2 has a separate ASID.

Purge all Hyper-V TLB FIFOs (for both L1 and L2), since both ASIDs are flushed, and an ASID flush is a superset of Hyper-V's fine-grained flushing (see comment in svm_flush_tlb_asid()).

Quoted 8 lines

Note that if one TLB flush FIFO is purged (e.g. as a result of KVM_REQ_TLB_FLUSH_CURRENT), it will consume KVM_REQ_HV_TLB_FLUSH, and a subsequent KVM_REQ_TLB_FLUSH will not flush the other FIFO. This is alright as flushing both FIFOs is a (newly introduced) optimization anyway. The other FIFO will be checked after a nested transition, as KVM_REQ_HV_TLB_FLUSH is always set on nested transitions.

#54 lore raw

PATCH v3 17/27 KVM: nSVM: Always switch VMCB before leaving guest mode

In reply to Yosry Ahmed

Move svm_switch_vmcb() calls ahead of leave_guest_mode(), as nothing between the calls depends on svm->vmcb being set to vmcb01. This makes the nested VM-Exit path consistent with the nested VM-Enter path, and having the calls to svm_switch_vmcb() and leave_guest_mode() close makes it easier to reason about incoming changes that depend on both VMCB and guest_mode context.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
arch/x86/kvm/svm/nested.c +2 -5
index 75ada771026b2..27f78228a42d5 100644
@@ -1329,7 +1329,7 @@ void nested_svm_vmexit(struct vcpu_svm *svm)
 	if (nested_svm_vmexit_update_vmcb12(vcpu))
 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
 
-	/* Exit Guest-Mode */
+	svm_switch_vmcb(svm, &svm->vmcb01);
 	leave_guest_mode(vcpu);
 	svm_pmu_handle_nested_transition(svm);
 
@@ -1356,8 +1356,6 @@ void nested_svm_vmexit(struct vcpu_svm *svm)
 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_ERAPS))
 		vmcb01->control.erap_ctl |= ERAP_CONTROL_CLEAR_RAP;
 
-	svm_switch_vmcb(svm, &svm->vmcb01);
-
 	/*
 	 * Rules for synchronizing int_ctl bits from vmcb02 to vmcb01:
 	 *
@@ -1543,6 +1541,7 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
 		vcpu->arch.nested_run_pending = 0;
 		svm->nested.vmcb12_gpa = INVALID_GPA;
 
+		svm_switch_vmcb(svm, &svm->vmcb01);
 		leave_guest_mode(vcpu);
 
 		/*
@@ -1554,8 +1553,6 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
 		 */
 		__svm_pmu_handle_nested_transition(svm, true);
 
-		svm_switch_vmcb(svm, &svm->vmcb01);
-
 		nested_svm_transition_tlb_flush(vcpu);
 
 		nested_svm_uninit_mmu_context(vcpu);
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 17/27
#55 lore raw

Re: [PATCH v3 17/27] KVM: nSVM: Always switch VMCB before leaving guest mode

Quoted 11 lines · Yosry Ahmed

Move svm_switch_vmcb() calls ahead of leave_guest_mode(), as nothing between the calls depends on svm->vmcb being set to vmcb01. This makes the nested VM-Exit path consistent with the nested VM-Enter path, and having the calls to svm_switch_vmcb() and leave_guest_mode() close makes it easier to reason about incoming changes that depend on both VMCB and guest_mode context.

No functional change intended.

#56 lore raw

PATCH v3 18/27 KVM: nSVM: Split nested_svm_transition_tlb_flush() into entry/exit fns

In reply to Yosry Ahmed

The handling for the entry and exit TLB flushes will diverge significantly in the following changes. Instead of adding an 'is_vmenter' argument like nested_vmx_transition_tlb_flush(), just split the function into two variants for 'entry' and 'exit'.

No functional change intended.

---
 arch/x86/kvm/svm/nested.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/nested.c +12 -4
index 27f78228a42d5..efe7a39b53656 100644
@@ -688,7 +688,7 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 	vmcb12->control.exit_int_info = exit_int_info;
 }
 
-static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
+static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
 	/* Handle pending Hyper-V TLB flush requests */
 	kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
@@ -708,6 +708,14 @@ static void nested_svm_transition_tlb_flush(struct kvm_vcpu *vcpu)
 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
 }
 
+static void nested_svm_exit_tlb_flush(struct kvm_vcpu *vcpu)
+{
+	kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
+
+	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
+	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
+}
+
 /*
  * Load guest's/host's cr3 on nested vmentry or vmexit. @nested_npt is true
  * if we are emulating VM-Entry into a guest with NPT enabled.
@@ -858,7 +866,7 @@ static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
 	struct vmcb *vmcb01 = svm->vmcb01.ptr;
 	struct kvm_vcpu *vcpu = &svm->vcpu;
 
-	nested_svm_transition_tlb_flush(vcpu);
+	nested_svm_entry_tlb_flush(vcpu);
 
 	/* Enter Guest-Mode */
 	enter_guest_mode(vcpu);
@@ -1434,7 +1442,7 @@ void nested_svm_vmexit(struct vcpu_svm *svm)
 	svm->vcpu.arch.dr7 = DR7_FIXED_1;
 	kvm_update_dr7(&svm->vcpu);
 
-	nested_svm_transition_tlb_flush(vcpu);
+	nested_svm_exit_tlb_flush(vcpu);
 
 	nested_svm_uninit_mmu_context(vcpu);
 
@@ -1553,7 +1561,7 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
 		 */
 		__svm_pmu_handle_nested_transition(svm, true);
 
-		nested_svm_transition_tlb_flush(vcpu);
+		nested_svm_exit_tlb_flush(vcpu);
 
 		nested_svm_uninit_mmu_context(vcpu);
 		vmcb_mark_all_dirty(svm->vmcb);
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 18/27
#57 lore raw

Re: [PATCH v3 18/27] KVM: nSVM: Split nested_svm_transition_tlb_flush() into entry/exit fns

Quoted 9 lines · Yosry Ahmed

The handling for the entry and exit TLB flushes will diverge significantly in the following changes. Instead of adding an 'is_vmenter' argument like nested_vmx_transition_tlb_flush(), just split the function into two variants for 'entry' and 'exit'.

No functional change intended.

#58 lore raw

PATCH v3 19/27 KVM: nSVM: Service local TLB flushes before nested transitions

In reply to Yosry Ahmed

Service pending TLB flushes for a specific context (L1 vs. L2) before entering/leaving guest mode, as KVM does not track TLB flush requests for L1 vs. L2. This is not currently required as KVM always flushes the TLB on nested transitions, but it is a requirement to drop the unconditional flushes.

TLB flushes are performed through the VMCB's TLB_CONTROL field, so service the flushes before every VMCB switch (except the precautionary switch in svm_free_nested()). Servicing flushes may end up purging the relevant HV TLB flush FIFO, which is based on guest_mode, so make sure local TLB flushes are handled before calling {enter/leave}_guest_mode().

This is conceptually similar to how nVMX calls kvm_service_local_tlb_flush_requests(), except that the VMX calls only have ordering requirements on {enter/leave}_guest_mode(), and not switching the VMCS, because VPID used for TLB flushes depends on guest_mode, and flushes are not VMCS-based.

Note that nested_svm_{entry/exit}_tlb_flush() must be called after kvm_service_local_tlb_flush_requests(), otherwise the TLB flushes will be immediately applied on the outgoing VMCB rather than the incoming one.

---
 arch/x86/kvm/svm/nested.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
arch/x86/kvm/svm/nested.c +22 -0
index efe7a39b53656..e216818f68372 100644
@@ -1044,6 +1044,20 @@ static void nested_svm_copy_common_state(struct vmcb *from_vmcb, struct vmcb *to
 	to_vmcb->save.spec_ctrl = from_vmcb->save.spec_ctrl;
 }
 
+static void nested_svm_service_local_tlb_flushes(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+
+	/*
+	 * TLB flushes are applied to the VMCB, so apply any pending TLB flushes
+	 * on the outgoing VMCB before switching to a new one. A TLB flush could
+	 * purge the relevant HV TLB flush FIFO depending on guest_mode, so make
+	 * sure the VMCB and guest_mode context is consistent.
+	 */
+	WARN_ON_ONCE(is_guest_mode(vcpu) != (svm->vmcb == svm->nested.vmcb02.ptr));
+	kvm_service_local_tlb_flush_requests(vcpu);
+}
+
 int enter_svm_guest_mode(struct kvm_vcpu *vcpu, u64 vmcb12_gpa, bool from_vmrun)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
@@ -1075,6 +1089,8 @@ int enter_svm_guest_mode(struct kvm_vcpu *vcpu, u64 vmcb12_gpa, bool from_vmrun)
 
 	nested_svm_copy_common_state(svm->vmcb01.ptr, svm->nested.vmcb02.ptr);
 
+	nested_svm_service_local_tlb_flushes(vcpu);
+
 	svm_switch_vmcb(svm, &svm->nested.vmcb02);
 	nested_vmcb02_prepare_control(svm);
 	nested_vmcb02_prepare_save(svm);
@@ -1337,6 +1353,8 @@ void nested_svm_vmexit(struct vcpu_svm *svm)
 	if (nested_svm_vmexit_update_vmcb12(vcpu))
 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
 
+	nested_svm_service_local_tlb_flushes(vcpu);
+
 	svm_switch_vmcb(svm, &svm->vmcb01);
 	leave_guest_mode(vcpu);
 	svm_pmu_handle_nested_transition(svm);
@@ -1549,6 +1567,8 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
 		vcpu->arch.nested_run_pending = 0;
 		svm->nested.vmcb12_gpa = INVALID_GPA;
 
+		nested_svm_service_local_tlb_flushes(vcpu);
+
 		svm_switch_vmcb(svm, &svm->vmcb01);
 		leave_guest_mode(vcpu);
 
@@ -2089,6 +2109,8 @@ static int svm_set_nested_state(struct kvm_vcpu *vcpu,
 	svm_copy_vmrun_state(vcpu, &svm->vmcb01.ptr->save, save);
 	nested_copy_vmcb_control_to_cache(svm, ctl);
 
+	nested_svm_service_local_tlb_flushes(vcpu);
+
 	svm_switch_vmcb(svm, &svm->nested.vmcb02);
 
 	if (use_separate_l2_pat)
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#59 lore raw

Re: [PATCH v3 19/27] KVM: nSVM: Service local TLB flushes before nested transitions

Quoted 28 lines · Yosry Ahmed

Service pending TLB flushes for a specific context (L1 vs. L2) before entering/leaving guest mode, as KVM does not track TLB flush requests for L1 vs. L2. This is not currently required as KVM always flushes the TLB on nested transitions, but it is a requirement to drop the unconditional flushes.

TLB flushes are performed through the VMCB's TLB_CONTROL field, so service the flushes before every VMCB switch (except the precautionary switch in svm_free_nested()). Servicing flushes may end up purging the relevant HV TLB flush FIFO, which is based on guest_mode, so make sure local TLB flushes are handled before calling {enter/leave}_guest_mode().

This is conceptually similar to how nVMX calls kvm_service_local_tlb_flush_requests(), except that the VMX calls only have ordering requirements on {enter/leave}_guest_mode(), and not switching the VMCS, because VPID used for TLB flushes depends on guest_mode, and flushes are not VMCS-based.

Note that nested_svm_{entry/exit}_tlb_flush() must be called after kvm_service_local_tlb_flush_requests(), otherwise the TLB flushes will be immediately applied on the outgoing VMCB rather than the incoming one.

---
 arch/x86/kvm/svm/nested.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

[ ... ]

arch/x86/kvm/svm/nested.c void svm_leave_nested(struct kvm_vcpu *vcpu) · line 1571

Quoted 6 lines
arch/x86/kvm/svm/nested.c +2 -0
@@ -1549,6 +1567,8 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
                vcpu->arch.nested_run_pending = 0;
                svm->nested.vmcb12_gpa = INVALID_GPA;
 
+               nested_svm_service_local_tlb_flushes(vcpu);
+

When called from svm_vcpu_free() during teardown, kvm_service_local_tlb_flush_requests() will be called for a vCPU that is being destroyed--and isn't loaded. By that point, the MMU has already been unloaded. Is that safe?

#60 lore raw

Re: [PATCH v3 19/27] KVM: nSVM: Service local TLB flushes before nested transitions

Quoted 37 lines · Jim Mattson
Quoted 28 lines · Yosry Ahmed

Service pending TLB flushes for a specific context (L1 vs. L2) before entering/leaving guest mode, as KVM does not track TLB flush requests for L1 vs. L2. This is not currently required as KVM always flushes the TLB on nested transitions, but it is a requirement to drop the unconditional flushes.

TLB flushes are performed through the VMCB's TLB_CONTROL field, so service the flushes before every VMCB switch (except the precautionary switch in svm_free_nested()). Servicing flushes may end up purging the relevant HV TLB flush FIFO, which is based on guest_mode, so make sure local TLB flushes are handled before calling {enter/leave}_guest_mode().

This is conceptually similar to how nVMX calls kvm_service_local_tlb_flush_requests(), except that the VMX calls only have ordering requirements on {enter/leave}_guest_mode(), and not switching the VMCS, because VPID used for TLB flushes depends on guest_mode, and flushes are not VMCS-based.

Note that nested_svm_{entry/exit}_tlb_flush() must be called after kvm_service_local_tlb_flush_requests(), otherwise the TLB flushes will be immediately applied on the outgoing VMCB rather than the incoming one.

---
 arch/x86/kvm/svm/nested.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

[ ... ]

Quoted 4 lines
arch/x86/kvm/svm/nested.c +0 -0
@@ -1549,6 +1567,8 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
                vcpu->arch.nested_run_pending = 0;
                svm->nested.vmcb12_gpa = INVALID_GPA;
 
Quoted 7 lines

Review void svm_leave_nested(struct kvm_vcpu *vcpu) · line 1571

Quoted 2 lines
(quoted diff) +2 -0
+               nested_svm_service_local_tlb_flushes(vcpu);
+

When called from svm_vcpu_free() during teardown, kvm_service_local_tlb_flush_requests() will be called for a vCPU that is being destroyed--and isn't loaded. By that point, the MMU has already been unloaded. Is that safe?

It should be, VMX already does it.

I am assuming you are specifically asking about kvm_vcpu_flush_tlb_guest(), as it could end up syncing roots with TDP off. kvm_mmu_unload() should set all roots to INVALID_PAGE. Both kvm_mmu_sync_roots() and kvm_mmu_sync_prev_roots() will then gracefully skip.

#61 lore raw

Re: [PATCH v3 19/27] KVM: nSVM: Service local TLB flushes before nested transitions

Quoted 47 lines · Yosry Ahmed
Quoted 37 lines · Jim Mattson
Quoted 28 lines · Yosry Ahmed

Service pending TLB flushes for a specific context (L1 vs. L2) before entering/leaving guest mode, as KVM does not track TLB flush requests for L1 vs. L2. This is not currently required as KVM always flushes the TLB on nested transitions, but it is a requirement to drop the unconditional flushes.

TLB flushes are performed through the VMCB's TLB_CONTROL field, so service the flushes before every VMCB switch (except the precautionary switch in svm_free_nested()). Servicing flushes may end up purging the relevant HV TLB flush FIFO, which is based on guest_mode, so make sure local TLB flushes are handled before calling {enter/leave}_guest_mode().

This is conceptually similar to how nVMX calls kvm_service_local_tlb_flush_requests(), except that the VMX calls only have ordering requirements on {enter/leave}_guest_mode(), and not switching the VMCS, because VPID used for TLB flushes depends on guest_mode, and flushes are not VMCS-based.

Note that nested_svm_{entry/exit}_tlb_flush() must be called after kvm_service_local_tlb_flush_requests(), otherwise the TLB flushes will be immediately applied on the outgoing VMCB rather than the incoming one.

---
 arch/x86/kvm/svm/nested.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

[ ... ]

Quoted 4 lines
arch/x86/kvm/svm/nested.c +0 -0
@@ -1549,6 +1567,8 @@ void svm_leave_nested(struct kvm_vcpu *vcpu)
                vcpu->arch.nested_run_pending = 0;
                svm->nested.vmcb12_gpa = INVALID_GPA;
 
Quoted 7 lines

Review void svm_leave_nested(struct kvm_vcpu *vcpu) · line 1571

Quoted 2 lines
(quoted diff) +2 -0
+               nested_svm_service_local_tlb_flushes(vcpu);
+

When called from svm_vcpu_free() during teardown, kvm_service_local_tlb_flush_requests() will be called for a vCPU that is being destroyed--and isn't loaded. By that point, the MMU has already been unloaded. Is that safe?

Quoted 7 lines

It should be, VMX already does it.

I am assuming you are specifically asking about kvm_vcpu_flush_tlb_guest(), as it could end up syncing roots with TDP off. kvm_mmu_unload() should set all roots to INVALID_PAGE. Both kvm_mmu_sync_roots() and kvm_mmu_sync_prev_roots() will then gracefully skip.

I'm just paranoid about process teardown and borrowed MMs.

#62 lore raw

PATCH v3 20/27 KVM: x86: Add KVM_REQ_MMU_SYNC_ALL_ROOTS

In reply to Yosry Ahmed

Add a new x86 request to sync all roots, current and previous. This will be used when syncing the shadow NPTs on nested VMRUN when an ASID flush (or new ASID) is requested by L1, as all physical translations in all roots should be sync'd (since shadow mappings are not tagged with an ASID).

Refactor syncing all roots (currently only done by kvm_vcpu_flush_tlb_guest()) to a helper, and use it to handle the request.

Clear KVM_REQ_MMU_SYNC when handling KVM_REQ_MMU_SYNC_ALL_ROOTS as the latter is a superset. Do not do so inside kvm_mmu_sync_all_roots(), to avoid any subtle behavioral changes from kvm_vcpu_flush_tlb_guest() clearing KVM_REQ_MMU_SYNC. It makes sense to always clear it when syncing the MMU, but there might be weird dependencies on the sync only happening before the actual vCPU run, and kvm_vcpu_flush_tlb_guest() is called in other code paths than handling KVM_REQ_TLB_FLUSH_GUEST before vCPU run.

No functional change intended.

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/kvm/mmu.h              |  7 +++++++
 arch/x86/kvm/x86.c              | 11 ++++++++---
 3 files changed, 16 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +1 -0
index e2eef7057bd35..1d28bb7e92c7f 100644
@@ -127,6 +127,7 @@
 	KVM_ARCH_REQ_FLAGS(33, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
 #define KVM_REQ_UPDATE_PROTECTED_GUEST_STATE \
 	KVM_ARCH_REQ_FLAGS(34, KVM_REQUEST_WAIT)
+#define KVM_REQ_MMU_SYNC_ALL_ROOTS	KVM_ARCH_REQ(35)
 
 #define INVALID_PAGE (~(hpa_t)0)
 #define VALID_PAGE(x) ((x) != INVALID_PAGE)
arch/x86/kvm/mmu.h +7 -0
index b443a5083bfb0..b6ad0ff72393e 100644
@@ -170,6 +170,13 @@ void kvm_mmu_unload(struct kvm_vcpu *vcpu);
 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu);
 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu);
 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu);
+
+static inline void kvm_mmu_sync_all_roots(struct kvm_vcpu *vcpu)
+{
+	kvm_mmu_sync_roots(vcpu);
+	kvm_mmu_sync_prev_roots(vcpu);
+}
+
 void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
 			 int bytes);
 
arch/x86/kvm/x86.c +8 -3
index 12eaeaea51633..a54e9da2ed09e 100644
@@ -2020,8 +2020,7 @@ static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
 		 * a forced sync of the shadow page tables.  Ensure all the
 		 * roots are synced and the guest TLB in hardware is clean.
 		 */
-		kvm_mmu_sync_roots(vcpu);
-		kvm_mmu_sync_prev_roots(vcpu);
+		kvm_mmu_sync_all_roots(vcpu);
 	}
 
 	kvm_x86_call(flush_tlb_guest)(vcpu);
@@ -8167,8 +8166,14 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 			if (unlikely(r))
 				goto out;
 		}
-		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
+
+		if (kvm_check_request(KVM_REQ_MMU_SYNC_ALL_ROOTS, vcpu)) {
+			kvm_mmu_sync_all_roots(vcpu);
+			kvm_clear_request(KVM_REQ_MMU_SYNC, vcpu);
+		} else if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu)) {
 			kvm_mmu_sync_roots(vcpu);
+		}
+
 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
 			kvm_mmu_load_pgd(vcpu);
 
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 20/27
#63 lore raw

Re: [PATCH v3 20/27] KVM: x86: Add KVM_REQ_MMU_SYNC_ALL_ROOTS

Quoted 20 lines · Yosry Ahmed

Add a new x86 request to sync all roots, current and previous. This will be used when syncing the shadow NPTs on nested VMRUN when an ASID flush (or new ASID) is requested by L1, as all physical translations in all roots should be sync'd (since shadow mappings are not tagged with an ASID).

Refactor syncing all roots (currently only done by kvm_vcpu_flush_tlb_guest()) to a helper, and use it to handle the request.

Clear KVM_REQ_MMU_SYNC when handling KVM_REQ_MMU_SYNC_ALL_ROOTS as the latter is a superset. Do not do so inside kvm_mmu_sync_all_roots(), to avoid any subtle behavioral changes from kvm_vcpu_flush_tlb_guest() clearing KVM_REQ_MMU_SYNC. It makes sense to always clear it when syncing the MMU, but there might be weird dependencies on the sync only happening before the actual vCPU run, and kvm_vcpu_flush_tlb_guest() is called in other code paths than handling KVM_REQ_TLB_FLUSH_GUEST before vCPU run.

Quoted 4 lines

No functional change intended.

#64 lore raw

PATCH v3 21/27 KVM: nSVM: Handle nested TLB flush requests through TLB_CONTROL

In reply to Yosry Ahmed

Handle L1's requests to flush L2's TLB through the TLB_CONTROL field of VMCB12. According to the APM, TLB_CONTROL is not modified by VMRUN, so only read the field from VMCB12 but do not clear it.

On nested VM-Enter, flush L2's ASID if any flush is specified in TLB_CONTROL. This handles TLB_CONTROL_FLUSH_ASID and TLB_CONTROL_FLUSH_ASID_LOCAL equally for simplicity.

On nested VM-Exit, flush L1's own ASID if L1 requested a *full* TLB flush (i.e. TLB_CONTROL_FLUSH_ALL_ASID).

Essentially, TLB_CONTROL_FLUSH_ASID[_LOCAL] cause a TLB flush on nested VM-Enter only, while TLB_CONTROL_FLUSH_ALL_ASID causes a TLB flush on both nested VM-Enter and nested VM-Exit.

Additionally, sync the nested NPTs on nested VM-Enter on an ASID flush, as ASID flushes also invalidate guest-physical translations on SVM (unlike VMX, which has separate VPID-based and EPT-based flushing). Sync all roots, as shadow mappings are not tagged with an ASID, and there could be translations belonging to the outgoing or flushed ASID in previous roots.

All TLB_CONTROL values can be handled by KVM regardless of FLUSHBYASID support on the underlying CPU, so keep advertising FLUSHBYASID to the guest unconditionally.

Note, TLB_CONTROL_FLUSH_ALL_ASID is never propagated from the vmcb12 to the vmcb02 (unless FLUSHBYASID is not available), as this gives the guest the power to flush the entire physical TLB (including translations for the host and other VMs).

---
 arch/x86/kvm/svm/nested.c | 31 ++++++++++++++++++++++++++-----
 arch/x86/kvm/svm/svm.c    |  5 ++---
 2 files changed, 28 insertions(+), 8 deletions(-)
arch/x86/kvm/svm/nested.c +26 -5
index e216818f68372..e04cc4f7669ea 100644
@@ -690,19 +690,34 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
+	struct vcpu_svm *svm = to_svm(vcpu);
+
 	/* Handle pending Hyper-V TLB flush requests */
 	kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
+	/*
+	 * If L1 requested a TLB flush for L2, flush L2's TLB on nested entry
+	 * and sync the nested NPT MMU, as TLB_CONTROL also flushes NPT
+	 * guest-physical mappings. Sync all roots, since the TLB flush is not
+	 * specific to the currently loaded nCR3.
+	 *
+	 * If L1 requested a full TLB flush for all ASIDs (including its own),
+	 * L1's own ASID is also flushed on nested VM-Exit, before running L1.
+	 *
+	 * TLB_CONTROL_FLUSH_ASID and TLB_CONTROL_FLUSH_ASID_LOCAL are handled
+	 * equally for simplicity.
+	 */
+	if (svm->nested.ctl.tlb_ctl != TLB_CONTROL_DO_NOTHING) {
+		if (nested_npt_enabled(svm))
+			kvm_make_request(KVM_REQ_MMU_SYNC_ALL_ROOTS, vcpu);
+		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
+	}
+
 	/*
 	 * TODO: optimize unconditional TLB flush/MMU sync.  A partial list of
 	 * things to fix before this can be conditional:
 	 *
-	 *  - Honor L1's request to flush an ASID on nested VMRUN
-	 *  - Sync nested NPT MMU on VMRUN that flushes L2's ASID[*]
 	 *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-	 *
-	 * [*] Unlike nested EPT, SVM's ASID management can invalidate nested
-	 *     NPT guest-physical mappings on VMRUN.
 	 */
 	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
@@ -710,8 +725,14 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 
 static void nested_svm_exit_tlb_flush(struct kvm_vcpu *vcpu)
 {
+	struct vcpu_svm *svm = to_svm(vcpu);
+
 	kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
+	/* Flush L1's own ASID if it requested a *full* TLB flush on VMRUN */
+	if (svm->nested.ctl.tlb_ctl == TLB_CONTROL_FLUSH_ALL_ASID)
+		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
+
 	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
 }
arch/x86/kvm/svm/svm.c +2 -3
index 97a5577a25d9f..8f2542357e78d 100644
@@ -5645,9 +5645,8 @@ static __init void svm_set_cpu_caps(void)
 		kvm_cpu_cap_set(X86_FEATURE_VMCBCLEAN);
 
 		/*
-		 * KVM currently flushes TLBs on *every* nested SVM transition,
-		 * and so for all intents and purposes KVM supports flushing by
-		 * ASID, i.e. KVM is guaranteed to honor every L1 ASID flush.
+		 * KVM handles all TLB_CONTROL values set by L1, even if the
+		 * underlying CPU does not.
 		 */
 		kvm_cpu_cap_set(X86_FEATURE_FLUSHBYASID);
 
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 21/27
#65 lore raw

Re: [PATCH v3 21/27] KVM: nSVM: Handle nested TLB flush requests through TLB_CONTROL

Quoted 27 lines · Yosry Ahmed

Handle L1's requests to flush L2's TLB through the TLB_CONTROL field of VMCB12. According to the APM, TLB_CONTROL is not modified by VMRUN, so only read the field from VMCB12 but do not clear it.

On nested VM-Enter, flush L2's ASID if any flush is specified in TLB_CONTROL. This handles TLB_CONTROL_FLUSH_ASID and TLB_CONTROL_FLUSH_ASID_LOCAL equally for simplicity.

On nested VM-Exit, flush L1's own ASID if L1 requested a *full* TLB flush (i.e. TLB_CONTROL_FLUSH_ALL_ASID).

Essentially, TLB_CONTROL_FLUSH_ASID[_LOCAL] cause a TLB flush on nested VM-Enter only, while TLB_CONTROL_FLUSH_ALL_ASID causes a TLB flush on both nested VM-Enter and nested VM-Exit.

Additionally, sync the nested NPTs on nested VM-Enter on an ASID flush, as ASID flushes also invalidate guest-physical translations on SVM (unlike VMX, which has separate VPID-based and EPT-based flushing). Sync all roots, as shadow mappings are not tagged with an ASID, and there could be translations belonging to the outgoing or flushed ASID in previous roots.

All TLB_CONTROL values can be handled by KVM regardless of FLUSHBYASID support on the underlying CPU, so keep advertising FLUSHBYASID to the guest unconditionally.

Quoted 6 lines

Note, TLB_CONTROL_FLUSH_ALL_ASID is never propagated from the vmcb12 to the vmcb02 (unless FLUSHBYASID is not available), as this gives the guest the power to flush the entire physical TLB (including translations for the host and other VMs).

#66 lore raw

PATCH v3 22/27 KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12

In reply to Yosry Ahmed

KVM uses a single ASID for L2 guests per-vCPU. Hence, when L1 changes L2's ASID in vmcb12 (e.g. due to switching to a different L2 vCPU or simply to avoid flushing an existing ASID), KVM needs to flush the L2 ASID to correctly emulate different ASIDs as different TLB domains.

Additionally, the nested NPT needs to be resync'd, as the MMU context is not tagged by ASID, and KVM cannot reuse nested NPT entries across different L2 ASIDs.

Essentially, L1 switching L2's ASID is treated exactly the same as L1 flushing L2's ASID, which is consistent with the APM:

Software may effectively flush the guest's TLB entries by allocating a new ASID for the guest and not reusing the old ASID until the entire TLB has been flushed at least once.

This is similar to nVMX's handling of last_vpid, except that when L1 changes VPID12, KVM does *not* need to resync the nested EPT, because VMX VPIDs, unlike SVM ASIDs, do not tag guest-physical translations (i.e. nGPA to GPA translations).

Reset last_asid when nested VMRUN fails to force a flush and sync on the next nested VMRUN. The TLB flush request survives the failure, but the request to sync the nested NPT does not, as it ends up being serviced in L1's MMU context after the synthesized VM-Exit.

Drop the commentary about vmcb12's ASID being copied around only for the consistency checks, as they no longer apply, and opportunistically fix whitespace alignment.

This is currently functionally a noop, as a full flush and sync is triggered on every nested transition, but is a step toward eliminating that.

---
 arch/x86/kvm/svm/nested.c | 29 +++++++++++++++++++++++------
 arch/x86/kvm/svm/svm.h    |  2 ++
 2 files changed, 25 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/nested.c +23 -6
index e04cc4f7669ea..8e4686b0d603a 100644
@@ -556,10 +556,8 @@ void __nested_copy_vmcb_control_to_cache(struct kvm_vcpu *vcpu,
 	to->nested_cr3          = from->nested_cr3;
 	to->pause_filter_count  = from->pause_filter_count;
 	to->pause_filter_thresh = from->pause_filter_thresh;
-
-	/* Copy asid here because nested_vmcb_check_controls() will check it */
-	to->asid           = from->asid;
-	to->clean = from->clean;
+	to->asid		= from->asid;
+	to->clean		= from->clean;
 
 #ifdef CONFIG_KVM_HYPERV
 	/* Hyper-V extensions (Enlightened VMCB) */
@@ -691,23 +689,35 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
+	bool new_asid = false;
 
 	/* Handle pending Hyper-V TLB flush requests */
 	kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
+	if (svm->nested.ctl.asid != svm->nested.last_asid) {
+		svm->nested.last_asid = svm->nested.ctl.asid;
+		new_asid = true;
+	}
+
 	/*
 	 * If L1 requested a TLB flush for L2, flush L2's TLB on nested entry
 	 * and sync the nested NPT MMU, as TLB_CONTROL also flushes NPT
 	 * guest-physical mappings. Sync all roots, since the TLB flush is not
 	 * specific to the currently loaded nCR3.
 	 *
+	 * Handle L1 changing L2's ASID12 similarly, as KVM only uses one ASID
+	 * for L2 in hardware (per vCPU), so it must start fresh when L1 changes
+	 * ASID12 to emulate different ASIDs correctly.  Additionally, the MMU
+	 * context is not tagged by the ASID, so the shadow NPTs cannot be
+	 * reused across different L2 ASIDs.
+	 *
 	 * If L1 requested a full TLB flush for all ASIDs (including its own),
 	 * L1's own ASID is also flushed on nested VM-Exit, before running L1.
 	 *
 	 * TLB_CONTROL_FLUSH_ASID and TLB_CONTROL_FLUSH_ASID_LOCAL are handled
 	 * equally for simplicity.
 	 */
-	if (svm->nested.ctl.tlb_ctl != TLB_CONTROL_DO_NOTHING) {
+	if (new_asid || (svm->nested.ctl.tlb_ctl != TLB_CONTROL_DO_NOTHING)) {
 		if (nested_npt_enabled(svm))
 			kvm_make_request(KVM_REQ_MMU_SYNC_ALL_ROOTS, vcpu);
 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
@@ -1237,6 +1247,13 @@ int nested_svm_vmrun(struct kvm_vcpu *vcpu)
 		svm->vmcb->control.exit_info_1  = 0;
 		svm->vmcb->control.exit_info_2  = 0;
 
+		/*
+		 * Force a flush+sync on the next nested VMRUN. Otherwise,
+		 * pending MMU syncs due to a changed ASID are lost, as
+		 * last_asid was already updated.
+		 */
+		svm->nested.last_asid = 0;
+
 		nested_svm_vmexit(svm);
 	}
 
@@ -1899,7 +1916,7 @@ void nested_svm_update_tsc_ratio_msr(struct kvm_vcpu *vcpu)
 	svm_write_tsc_multiplier(vcpu);
 }
 
-/* Inverse operation of nested_copy_vmcb_control_to_cache(). asid is copied too. */
+/* Inverse operation of nested_copy_vmcb_control_to_cache() */
 static void nested_copy_vmcb_cache_to_control(struct vmcb_control_area *dst,
 					      struct vmcb_ctrl_area_cached *from)
 {
arch/x86/kvm/svm/svm.h +2 -0
index ed67c18e2b900..15c4aa3b02c2d 100644
@@ -244,6 +244,8 @@ struct svm_nested_state {
 	 * on its side.
 	 */
 	bool force_msr_bitmap_recalc;
+
+	u32 last_asid;
 };
 
 struct vcpu_sev_es_state {
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#67 lore raw

Re: [PATCH v3 22/27] KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12

Quoted 62 lines · Yosry Ahmed

KVM uses a single ASID for L2 guests per-vCPU. Hence, when L1 changes L2's ASID in vmcb12 (e.g. due to switching to a different L2 vCPU or simply to avoid flushing an existing ASID), KVM needs to flush the L2 ASID to correctly emulate different ASIDs as different TLB domains.

Additionally, the nested NPT needs to be resync'd, as the MMU context is not tagged by ASID, and KVM cannot reuse nested NPT entries across different L2 ASIDs.

Essentially, L1 switching L2's ASID is treated exactly the same as L1 flushing L2's ASID, which is consistent with the APM:

Software may effectively flush the guest's TLB entries by allocating a new ASID for the guest and not reusing the old ASID until the entire TLB has been flushed at least once.

This is similar to nVMX's handling of last_vpid, except that when L1 changes VPID12, KVM does *not* need to resync the nested EPT, because VMX VPIDs, unlike SVM ASIDs, do not tag guest-physical translations (i.e. nGPA to GPA translations).

Reset last_asid when nested VMRUN fails to force a flush and sync on the next nested VMRUN. The TLB flush request survives the failure, but the request to sync the nested NPT does not, as it ends up being serviced in L1's MMU context after the synthesized VM-Exit.

Drop the commentary about vmcb12's ASID being copied around only for the consistency checks, as they no longer apply, and opportunistically fix whitespace alignment.

This is currently functionally a noop, as a full flush and sync is triggered on every nested transition, but is a step toward eliminating that.

---
 arch/x86/kvm/svm/nested.c | 29 +++++++++++++++++++++++------
 arch/x86/kvm/svm/svm.h    |  2 ++
 2 files changed, 25 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/nested.c +2 -4
index e04cc4f7669ea..8e4686b0d603a 100644
@@ -556,10 +556,8 @@ void __nested_copy_vmcb_control_to_cache(struct kvm_vcpu *vcpu,
        to->nested_cr3          = from->nested_cr3;
        to->pause_filter_count  = from->pause_filter_count;
        to->pause_filter_thresh = from->pause_filter_thresh;
-
-       /* Copy asid here because nested_vmcb_check_controls() will check it */
-       to->asid           = from->asid;
-       to->clean = from->clean;
+       to->asid                = from->asid;
+       to->clean               = from->clean;
 
 #ifdef CONFIG_KVM_HYPERV
        /* Hyper-V extensions (Enlightened VMCB) */
@@ -691,23 +689,35 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {

arch/x86/kvm/svm/nested.c static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm, · line 700

Quoted 10 lines
arch/x86/kvm/svm/nested.c +5 -0
        struct vcpu_svm *svm = to_svm(vcpu);
+       bool new_asid = false;
 
        /* Handle pending Hyper-V TLB flush requests */
        kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
+       if (svm->nested.ctl.asid != svm->nested.last_asid) {
+               svm->nested.last_asid = svm->nested.ctl.asid;
+               new_asid = true;
+       }

To make sure we don't miss a flush after restore, do we need to clear last_asid in svm_set_nested_state()?

#68 lore raw

Re: [PATCH v3 22/27] KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12

Quoted 70 lines · Jim Mattson
Quoted 68 lines · Yosry Ahmed

KVM uses a single ASID for L2 guests per-vCPU. Hence, when L1 changes L2's ASID in vmcb12 (e.g. due to switching to a different L2 vCPU or simply to avoid flushing an existing ASID), KVM needs to flush the L2 ASID to correctly emulate different ASIDs as different TLB domains.

Additionally, the nested NPT needs to be resync'd, as the MMU context is not tagged by ASID, and KVM cannot reuse nested NPT entries across different L2 ASIDs.

Essentially, L1 switching L2's ASID is treated exactly the same as L1 flushing L2's ASID, which is consistent with the APM:

Software may effectively flush the guest's TLB entries by allocating a new ASID for the guest and not reusing the old ASID until the entire TLB has been flushed at least once.

This is similar to nVMX's handling of last_vpid, except that when L1 changes VPID12, KVM does *not* need to resync the nested EPT, because VMX VPIDs, unlike SVM ASIDs, do not tag guest-physical translations (i.e. nGPA to GPA translations).

Reset last_asid when nested VMRUN fails to force a flush and sync on the next nested VMRUN. The TLB flush request survives the failure, but the request to sync the nested NPT does not, as it ends up being serviced in L1's MMU context after the synthesized VM-Exit.

Drop the commentary about vmcb12's ASID being copied around only for the consistency checks, as they no longer apply, and opportunistically fix whitespace alignment.

This is currently functionally a noop, as a full flush and sync is triggered on every nested transition, but is a step toward eliminating that.

---
 arch/x86/kvm/svm/nested.c | 29 +++++++++++++++++++++++------
 arch/x86/kvm/svm/svm.h    |  2 ++
 2 files changed, 25 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/nested.c +3 -4
index e04cc4f7669ea..8e4686b0d603a 100644
@@ -556,10 +556,8 @@ void __nested_copy_vmcb_control_to_cache(struct kvm_vcpu *vcpu,
        to->nested_cr3          = from->nested_cr3;
        to->pause_filter_count  = from->pause_filter_count;
        to->pause_filter_thresh = from->pause_filter_thresh;
-
-       /* Copy asid here because nested_vmcb_check_controls() will check it */
-       to->asid           = from->asid;
-       to->clean = from->clean;
+       to->asid                = from->asid;
+       to->clean               = from->clean;
 
 #ifdef CONFIG_KVM_HYPERV
        /* Hyper-V extensions (Enlightened VMCB) */
@@ -691,23 +689,35 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
        struct vcpu_svm *svm = to_svm(vcpu);
+       bool new_asid = false;
 
        /* Handle pending Hyper-V TLB flush requests */
        kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
Quoted 7 lines

arch/x86/kvm/svm/nested.c static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm, · line 700

Quoted 4 lines
arch/x86/kvm/svm/nested.c +4 -0
+       if (svm->nested.ctl.asid != svm->nested.last_asid) {
+               svm->nested.last_asid = svm->nested.ctl.asid;
+               new_asid = true;
+       }

To make sure we don't miss a flush after restore, do we need to clear last_asid in svm_set_nested_state()?

In [1], we set svm->nested.vmcb02.cpu = -1 in svm_allocate_nested(), which should be called when EFER.SVME is set on restore, and should force a TLB flush on the first vCPU run. That being said, if EFER.SVME was already set (not a fresh vCPU), we won't necessarily flush the TLB. KVM_SET_SREGS will _probably_ flush the TLB, but I don't think it's guaranteed.

But wouldn't this also affect non-nested? Are we guaranteed to flush L1's ASID after restore?

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

#69 lore raw

Re: [PATCH v3 22/27] KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12

Quoted 80 lines · Yosry Ahmed
Quoted 70 lines · Jim Mattson
Quoted 68 lines · Yosry Ahmed

KVM uses a single ASID for L2 guests per-vCPU. Hence, when L1 changes L2's ASID in vmcb12 (e.g. due to switching to a different L2 vCPU or simply to avoid flushing an existing ASID), KVM needs to flush the L2 ASID to correctly emulate different ASIDs as different TLB domains.

Additionally, the nested NPT needs to be resync'd, as the MMU context is not tagged by ASID, and KVM cannot reuse nested NPT entries across different L2 ASIDs.

Essentially, L1 switching L2's ASID is treated exactly the same as L1 flushing L2's ASID, which is consistent with the APM:

Software may effectively flush the guest's TLB entries by allocating a new ASID for the guest and not reusing the old ASID until the entire TLB has been flushed at least once.

This is similar to nVMX's handling of last_vpid, except that when L1 changes VPID12, KVM does *not* need to resync the nested EPT, because VMX VPIDs, unlike SVM ASIDs, do not tag guest-physical translations (i.e. nGPA to GPA translations).

Reset last_asid when nested VMRUN fails to force a flush and sync on the next nested VMRUN. The TLB flush request survives the failure, but the request to sync the nested NPT does not, as it ends up being serviced in L1's MMU context after the synthesized VM-Exit.

Drop the commentary about vmcb12's ASID being copied around only for the consistency checks, as they no longer apply, and opportunistically fix whitespace alignment.

This is currently functionally a noop, as a full flush and sync is triggered on every nested transition, but is a step toward eliminating that.

---
 arch/x86/kvm/svm/nested.c | 29 +++++++++++++++++++++++------
 arch/x86/kvm/svm/svm.h    |  2 ++
 2 files changed, 25 insertions(+), 6 deletions(-)
arch/x86/kvm/svm/nested.c +3 -4
index e04cc4f7669ea..8e4686b0d603a 100644
@@ -556,10 +556,8 @@ void __nested_copy_vmcb_control_to_cache(struct kvm_vcpu *vcpu,
        to->nested_cr3          = from->nested_cr3;
        to->pause_filter_count  = from->pause_filter_count;
        to->pause_filter_thresh = from->pause_filter_thresh;
-
-       /* Copy asid here because nested_vmcb_check_controls() will check it */
-       to->asid           = from->asid;
-       to->clean = from->clean;
+       to->asid                = from->asid;
+       to->clean               = from->clean;
 
 #ifdef CONFIG_KVM_HYPERV
        /* Hyper-V extensions (Enlightened VMCB) */
@@ -691,23 +689,35 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
        struct vcpu_svm *svm = to_svm(vcpu);
+       bool new_asid = false;
 
        /* Handle pending Hyper-V TLB flush requests */
        kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
Quoted 7 lines

arch/x86/kvm/svm/nested.c static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm, · line 700

Quoted 4 lines
arch/x86/kvm/svm/nested.c +4 -0
+       if (svm->nested.ctl.asid != svm->nested.last_asid) {
+               svm->nested.last_asid = svm->nested.ctl.asid;
+               new_asid = true;
+       }

To make sure we don't miss a flush after restore, do we need to clear last_asid in svm_set_nested_state()?

Quoted 6 lines

In [1], we set svm->nested.vmcb02.cpu = -1 in svm_allocate_nested(), which should be called when EFER.SVME is set on restore, and should force a TLB flush on the first vCPU run. That being said, if EFER.SVME was already set (not a fresh vCPU), we won't necessarily flush the TLB. KVM_SET_SREGS will _probably_ flush the TLB, but I don't think it's guaranteed.

I'm pretty sure that restoring nested state on an existing vCPU with the same asid12 and no TLB_CONTROL skips the flush.

Quoted 2 lines

But wouldn't this also affect non-nested? Are we guaranteed to flush L1's ASID after restore?

That may be a bug too.

#70 lore raw

Re: [PATCH v3 22/27] KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12

Quoted 24 lines
Quoted 17 lines
Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/svm/nested.c +1 -0
@@ -691,23 +689,35 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
        struct vcpu_svm *svm = to_svm(vcpu);
+       bool new_asid = false;
 
        /* Handle pending Hyper-V TLB flush requests */
        kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
Quoted 7 lines

arch/x86/kvm/svm/nested.c static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm, · line 700

Quoted 4 lines
arch/x86/kvm/svm/nested.c +4 -0
+       if (svm->nested.ctl.asid != svm->nested.last_asid) {
+               svm->nested.last_asid = svm->nested.ctl.asid;
+               new_asid = true;
+       }

To make sure we don't miss a flush after restore, do we need to clear last_asid in svm_set_nested_state()?

Quoted 6 lines

In [1], we set svm->nested.vmcb02.cpu = -1 in svm_allocate_nested(), which should be called when EFER.SVME is set on restore, and should force a TLB flush on the first vCPU run. That being said, if EFER.SVME was already set (not a fresh vCPU), we won't necessarily flush the TLB. KVM_SET_SREGS will _probably_ flush the TLB, but I don't think it's guaranteed.

Quoted 2 lines

I'm pretty sure that restoring nested state on an existing vCPU with the same asid12 and no TLB_CONTROL skips the flush.

I can clear last_asid in svm_set_nested_state() to make sure we don't break this.

Quoted 5 lines
Quoted 3 lines

But wouldn't this also affect non-nested? Are we guaranteed to flush L1's ASID after restore?

That may be a bug too.

It's tricky. KVM_SET_SREGS will only flush (with 64-bit vCPUs) if CR0/CR3/CR4/EFER are changed apparently. But it's not just the TLB flush, the entire MMU context wouldn't be reset?

I am not sure if there is a practical use case for restoring on an existing vCPU tho.

#71 lore raw

Re: [PATCH v3 22/27] KVM: nSVM: Flush the TLB if L1 changes L2's ASID in vmcb12

Quoted 35 lines · Yosry Ahmed
Quoted 25 lines
Quoted 18 lines
Quoted 10 lines
Quoted 10 lines
arch/x86/kvm/svm/nested.c +1 -0
@@ -691,23 +689,35 @@ static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm,
 static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 {
        struct vcpu_svm *svm = to_svm(vcpu);
+       bool new_asid = false;
 
        /* Handle pending Hyper-V TLB flush requests */
        kvm_hv_nested_transtion_tlb_flush(vcpu, npt_enabled);
 
Quoted 7 lines

arch/x86/kvm/svm/nested.c static void nested_save_pending_event_to_vmcb12(struct vcpu_svm *svm, · line 700

Quoted 4 lines
arch/x86/kvm/svm/nested.c +4 -0
+       if (svm->nested.ctl.asid != svm->nested.last_asid) {
+               svm->nested.last_asid = svm->nested.ctl.asid;
+               new_asid = true;
+       }

To make sure we don't miss a flush after restore, do we need to clear last_asid in svm_set_nested_state()?

Quoted 6 lines

In [1], we set svm->nested.vmcb02.cpu = -1 in svm_allocate_nested(), which should be called when EFER.SVME is set on restore, and should force a TLB flush on the first vCPU run. That being said, if EFER.SVME was already set (not a fresh vCPU), we won't necessarily flush the TLB. KVM_SET_SREGS will _probably_ flush the TLB, but I don't think it's guaranteed.

Quoted 2 lines

I'm pretty sure that restoring nested state on an existing vCPU with the same asid12 and no TLB_CONTROL skips the flush.

I can clear last_asid in svm_set_nested_state() to make sure we don't break this.

Quoted 4 lines
Quoted 3 lines

But wouldn't this also affect non-nested? Are we guaranteed to flush L1's ASID after restore?

Quoted 8 lines
Quoted 1 line

That may be a bug too.

It's tricky. KVM_SET_SREGS will only flush (with 64-bit vCPUs) if CR0/CR3/CR4/EFER are changed apparently. But it's not just the TLB flush, the entire MMU context wouldn't be reset?

I am not sure if there is a practical use case for restoring on an existing vCPU tho.

KVM APIs make me want to kill myself.

#72 lore raw

PATCH v3 23/27 KVM: nSVM: Do not reset TLB_CONTROL in vmcb02 on nested VM-Enter

In reply to Yosry Ahmed

Stop clearing TLB_CONTROL when preparing the control area of vmcb02, as this potentially undoes pending TLB flushes for L2 (e.g. through KVM_REQ_TLB_FLUSH while L1 is running), and remove the associated TODO comment.

This is currently harmless, because nested_svm_entry_tlb_flush() always requests KVM_REQ_TLB_FLUSH_CURRENT on nested VM-Enter, which sets TLB_CONTROL again before L2 is actually run. However, always flushing will soon go away with proper TLB handling for L2, at which point always clearing TLB_CONTROL would be a bug.

Clearing TLB_CONTROL on nested VM-Enter was probably done because TLB_CONTROL is not cleared by the CPU on VM-Exit. However, KVM always clears TLB_CONTROL in the active VMCB after a successful VMRUN. Hence, at nested VM-Enter, TLB_CONTROL in vmcb02 can only be non-zero if a TLB flush is queued for L2 while L1 is running (i.e. KVM_REQ_TLB_FLUSH), and that should never be ignored.

---
 arch/x86/kvm/svm/nested.c | 10 +---------
 1 file changed, 1 insertion(+), 9 deletions(-)
arch/x86/kvm/svm/nested.c +1 -9
index 8e4686b0d603a..738ec1f2ec869 100644
@@ -723,12 +723,7 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
 	}
 
-	/*
-	 * TODO: optimize unconditional TLB flush/MMU sync.  A partial list of
-	 * things to fix before this can be conditional:
-	 *
-	 *  - Don't crush a pending TLB flush in vmcb02 on nested VMRUN
-	 */
+	/* TODO: optimize unconditional TLB flush/MMU sync */
 	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
 }
@@ -975,9 +970,6 @@ static void nested_vmcb02_prepare_control(struct vcpu_svm *svm)
 
 	vmcb02->control.asid = svm->nested.asid02;
 
-	/* Overwritten later if necessary.  */
-	vmcb_clr_flush_asid(vmcb02);
-
 	/* Use vmcb01 MMU and format if guest does not use nNPT */
 	if (nested_npt_enabled(svm)) {
 		vmcb02->control.misc_ctl &= ~SVM_MISC_ENABLE_GMET;
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 23/27
#73 lore raw

Re: [PATCH v3 23/27] KVM: nSVM: Do not reset TLB_CONTROL in vmcb02 on nested VM-Enter

Quoted 12 lines · Yosry Ahmed

Stop clearing TLB_CONTROL when preparing the control area of vmcb02, as this potentially undoes pending TLB flushes for L2 (e.g. through KVM_REQ_TLB_FLUSH while L1 is running), and remove the associated TODO comment.

This is currently harmless, because nested_svm_entry_tlb_flush() always requests KVM_REQ_TLB_FLUSH_CURRENT on nested VM-Enter, which sets TLB_CONTROL again before L2 is actually run. However, always flushing will soon go away with proper TLB handling for L2, at which point always clearing TLB_CONTROL would be a bug.

Quoted 5 lines

Clearing TLB_CONTROL on nested VM-Enter was probably done because TLB_CONTROL is not cleared by the CPU on VM-Exit. However, KVM always clears TLB_CONTROL in the active VMCB after a successful VMRUN. Hence, at nested VM-Enter, TLB_CONTROL in vmcb02 can only be non-zero if a TLB flush is queued for L2 while L1 is running (i.e. KVM_REQ_TLB_FLUSH), and

Nit: s/i.e./e.g./

Quoted 3 lines

that should never be ignored.

#74 lore raw

Re: [PATCH v3 23/27] KVM: nSVM: Do not reset TLB_CONTROL in vmcb02 on nested VM-Enter

Quoted 14 lines · Jim Mattson
Quoted 12 lines · Yosry Ahmed

Stop clearing TLB_CONTROL when preparing the control area of vmcb02, as this potentially undoes pending TLB flushes for L2 (e.g. through KVM_REQ_TLB_FLUSH while L1 is running), and remove the associated TODO comment.

This is currently harmless, because nested_svm_entry_tlb_flush() always requests KVM_REQ_TLB_FLUSH_CURRENT on nested VM-Enter, which sets TLB_CONTROL again before L2 is actually run. However, always flushing will soon go away with proper TLB handling for L2, at which point always clearing TLB_CONTROL would be a bug.

Quoted 7 lines
Quoted 5 lines

Clearing TLB_CONTROL on nested VM-Enter was probably done because TLB_CONTROL is not cleared by the CPU on VM-Exit. However, KVM always clears TLB_CONTROL in the active VMCB after a successful VMRUN. Hence, at nested VM-Enter, TLB_CONTROL in vmcb02 can only be non-zero if a TLB flush is queued for L2 while L1 is running (i.e. KVM_REQ_TLB_FLUSH), and

Nit: s/i.e./e.g./

Ack.

Quoted 5 lines
Quoted 4 lines

that should never be ignored.

#75 lore raw

PATCH v3 24/27 KVM: nSVM: Flush L2's ASID when emulating INVLPGA

In reply to Yosry Ahmed

KVM currently handles INVLPGA in the same way as INVLPG, flushing L1's own ASID. This is currently correct because L1 and L2 share an ASID, but it doesn't work once they have separate ASIDs.

If L1 is flushing a different L2 ASID than the one KVM is tracking, do nothing, as KVM will flush L2's ASID in hardware (and sync the MMU if needed) when L1 switches to the target ASID.

If L1 is flushing the tracked L2 ASID, flush the L2 ASID in hardware using INVLPGA if running on the same CPU as L2. If not, fallback to a VMCB-based ASID flush. Note that if L2 then runs on a different CPU KVM will flush the ASID anyway.

If NPT is disabled, also free L2's roots, as they may have stale translations for the flushed address. Do not try to sync the mappings for the flushed address as it involves walking L2's shadow page tables with L1's MMU context. This is similar to INVVPID handling in with nVMX.

Note: If L1 is flushing its own ASID, it remains handled the same way as INVLPG. Additionally, if INVLPGA is executed by L2 (and not intercepted by L1), also handle it like INVLPG. Technically, L2 could be flushing an untracked ASID, in which case KVM doesn't need to do anything. However, kvm_mmu_free_guest_mode_roots() does not handle being invoked in guest mode, so using kvm_mmu_invlpg() in guest mode side-steps this, and should not happen with a well-behaved L1 anyway.

---
 arch/x86/kvm/svm/svm.c | 48 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 46 insertions(+), 2 deletions(-)
arch/x86/kvm/svm/svm.c +46 -2
index 8f2542357e78d..436d13f106369 100644
@@ -2468,17 +2468,61 @@ static int clgi_interception(struct kvm_vcpu *vcpu)
 
 static int invlpga_interception(struct kvm_vcpu *vcpu)
 {
+	struct vcpu_svm *svm = to_svm(vcpu);
 	/* FIXME: Handle an address size prefix. */
 	gva_t gva = kvm_rax_read(vcpu);
 	u32 asid = kvm_ecx_read(vcpu);
+	int cpu;
 
 	if (nested_svm_check_permissions(vcpu))
 		return 1;
 
 	trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
 
-	/* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
-	kvm_mmu_invlpg(vcpu, gva);
+	/*
+	 * INVLPG on a non-canonical address is a NOP according to the SDM,
+	 * assume the same behavior from INVLPGA since the APM doesn't specify.
+	 */
+	if (is_noncanonical_invlpg_address(gva, vcpu))
+		return kvm_skip_emulated_instruction(vcpu);
+
+	/*
+	 * If L1 is flushing its own ASID, handle it like INVLPG. Do the same if
+	 * this is an unintercepted INVLPGA from L2, as
+	 * kvm_mmu_free_guest_mode_roots() does not handle being in guest mode.
+	 */
+	if (!asid || is_guest_mode(vcpu)) {
+		kvm_mmu_invlpg(vcpu, gva);
+		return kvm_skip_emulated_instruction(vcpu);
+	}
+
+	/*
+	 * Do nothing if L1 is flushing a different L2 ASID than the one KVM is
+	 * currently tracking.  KVM tracks a single L2 ASID, and performs a TLB
+	 * flush (and MMU resync if needed) when L1 switches ASIDs anyway.
+	 */
+	if (asid != svm->nested.last_asid)
+		return kvm_skip_emulated_instruction(vcpu);
+
+	/*
+	 * Use INVLPGA to flush L2's ASID in hardware if running on the same
+	 * CPU, otherwise fallback to a full ASID flush.
+	 */
+	cpu = get_cpu();
+	if (cpu == svm->nested.vmcb02.cpu)
+		invlpga(gva, svm->nested.asid02);
+	else
+		vmcb_set_flush_asid(svm->nested.vmcb02.ptr);
+	put_cpu();
+
+	/*
+	 * If NPT is disabled, free L2's shadow roots as they may have stale
+	 * translations for the flushed address. Do not sync the mappings for
+	 * the flushed address, as it involves walking L2 shadow page tables
+	 * with L1's MMU context.
+	 */
+	if (!npt_enabled)
+		kvm_mmu_free_guest_mode_roots(vcpu->kvm, &vcpu->arch.root_mmu);
 
 	return kvm_skip_emulated_instruction(vcpu);
 }
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#76 lore raw

Re: [PATCH v3 24/27] KVM: nSVM: Flush L2's ASID when emulating INVLPGA

Quoted 14 lines · Yosry Ahmed

KVM currently handles INVLPGA in the same way as INVLPG, flushing L1's own ASID. This is currently correct because L1 and L2 share an ASID, but it doesn't work once they have separate ASIDs.

If L1 is flushing a different L2 ASID than the one KVM is tracking, do nothing, as KVM will flush L2's ASID in hardware (and sync the MMU if needed) when L1 switches to the target ASID.

If L1 is flushing the tracked L2 ASID, flush the L2 ASID in hardware using INVLPGA if running on the same CPU as L2. If not, fallback to a VMCB-based ASID flush. Note that if L2 then runs on a different CPU KVM will flush the ASID anyway.

Quoted 4 lines

If NPT is disabled, also free L2's roots, as they may have stale translations for the flushed address. Do not try to sync the mappings for the flushed address as it involves walking L2's shadow page tables with L1's MMU context. This is similar to INVVPID handling in with nVMX.

Nit: s/in with/with/

Quoted 31 lines

Note: If L1 is flushing its own ASID, it remains handled the same way as INVLPG. Additionally, if INVLPGA is executed by L2 (and not intercepted by L1), also handle it like INVLPG. Technically, L2 could be flushing an untracked ASID, in which case KVM doesn't need to do anything. However, kvm_mmu_free_guest_mode_roots() does not handle being invoked in guest mode, so using kvm_mmu_invlpg() in guest mode side-steps this, and should not happen with a well-behaved L1 anyway.

---
 arch/x86/kvm/svm/svm.c | 48 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 46 insertions(+), 2 deletions(-)
arch/x86/kvm/svm/svm.c +2 -0
index 8f2542357e78d..436d13f106369 100644
@@ -2468,17 +2468,61 @@ static int clgi_interception(struct kvm_vcpu *vcpu)
 
 static int invlpga_interception(struct kvm_vcpu *vcpu)
 {
+       struct vcpu_svm *svm = to_svm(vcpu);
        /* FIXME: Handle an address size prefix. */
        gva_t gva = kvm_rax_read(vcpu);
        u32 asid = kvm_ecx_read(vcpu);
+       int cpu;
 
        if (nested_svm_check_permissions(vcpu))
                return 1;
 

arch/x86/kvm/svm/svm.c static int clgi_interception(struct kvm_vcpu *vcpu) · line 2487

Quoted 10 lines
arch/x86/kvm/svm/svm.c +6 -2
        trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
 
-       /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
-       kvm_mmu_invlpg(vcpu, gva);
+       /*
+        * INVLPG on a non-canonical address is a NOP according to the SDM,
+        * assume the same behavior from INVLPGA since the APM doesn't specify.
+        */
+       if (is_noncanonical_invlpg_address(gva, vcpu))
+               return kvm_skip_emulated_instruction(vcpu);

If L1 is in 32-bit mode with junk in RAX[63:32] (e.g. bits left over from long mode), the full 64-bit value may not be canonical. Should the kvm_rax_read(vcpu) above be kvm_register_read(vcpu, VCPU_REGS_RAX)?

#77 lore raw

Re: [PATCH v3 24/27] KVM: nSVM: Flush L2's ASID when emulating INVLPGA

Quoted 56 lines · Jim Mattson
Quoted 14 lines · Yosry Ahmed

KVM currently handles INVLPGA in the same way as INVLPG, flushing L1's own ASID. This is currently correct because L1 and L2 share an ASID, but it doesn't work once they have separate ASIDs.

If L1 is flushing a different L2 ASID than the one KVM is tracking, do nothing, as KVM will flush L2's ASID in hardware (and sync the MMU if needed) when L1 switches to the target ASID.

If L1 is flushing the tracked L2 ASID, flush the L2 ASID in hardware using INVLPGA if running on the same CPU as L2. If not, fallback to a VMCB-based ASID flush. Note that if L2 then runs on a different CPU KVM will flush the ASID anyway.

Quoted 4 lines

If NPT is disabled, also free L2's roots, as they may have stale translations for the flushed address. Do not try to sync the mappings for the flushed address as it involves walking L2's shadow page tables with L1's MMU context. This is similar to INVVPID handling in with nVMX.

Nit: s/in with/with/

Quoted 33 lines

Note: If L1 is flushing its own ASID, it remains handled the same way as INVLPG. Additionally, if INVLPGA is executed by L2 (and not intercepted by L1), also handle it like INVLPG. Technically, L2 could be flushing an untracked ASID, in which case KVM doesn't need to do anything. However, kvm_mmu_free_guest_mode_roots() does not handle being invoked in guest mode, so using kvm_mmu_invlpg() in guest mode side-steps this, and should not happen with a well-behaved L1 anyway.

---
 arch/x86/kvm/svm/svm.c | 48 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 46 insertions(+), 2 deletions(-)
arch/x86/kvm/svm/svm.c +2 -0
index 8f2542357e78d..436d13f106369 100644
@@ -2468,17 +2468,61 @@ static int clgi_interception(struct kvm_vcpu *vcpu)
 
 static int invlpga_interception(struct kvm_vcpu *vcpu)
 {
+       struct vcpu_svm *svm = to_svm(vcpu);
        /* FIXME: Handle an address size prefix. */
        gva_t gva = kvm_rax_read(vcpu);
        u32 asid = kvm_ecx_read(vcpu);
+       int cpu;
 
        if (nested_svm_check_permissions(vcpu))
                return 1;
 
        trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
 
Quoted 13 lines

arch/x86/kvm/svm/svm.c static int clgi_interception(struct kvm_vcpu *vcpu) · line 2487

Quoted 8 lines
arch/x86/kvm/svm/svm.c +6 -2
-       /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
-       kvm_mmu_invlpg(vcpu, gva);
+       /*
+        * INVLPG on a non-canonical address is a NOP according to the SDM,
+        * assume the same behavior from INVLPGA since the APM doesn't specify.
+        */
+       if (is_noncanonical_invlpg_address(gva, vcpu))
+               return kvm_skip_emulated_instruction(vcpu);

If L1 is in 32-bit mode with junk in RAX[63:32] (e.g. bits left over from long mode), the full 64-bit value may not be canonical. Should the kvm_rax_read(vcpu) above be kvm_register_read(vcpu, VCPU_REGS_RAX)?

Doesn't kvm_rax_read() already use kvm_reg_mode_mask() as per __BUILD_KVM_GPR_ACCESSORS()?

#78 lore raw

Re: [PATCH v3 24/27] KVM: nSVM: Flush L2's ASID when emulating INVLPGA

Quoted 34 lines · Yosry Ahmed
Quoted 19 lines · Jim Mattson
Quoted 19 lines
arch/x86/kvm/svm/svm.c +2 -0
index 8f2542357e78d..436d13f106369 100644
@@ -2468,17 +2468,61 @@ static int clgi_interception(struct kvm_vcpu *vcpu)
 
 static int invlpga_interception(struct kvm_vcpu *vcpu)
 {
+       struct vcpu_svm *svm = to_svm(vcpu);
        /* FIXME: Handle an address size prefix. */
        gva_t gva = kvm_rax_read(vcpu);
        u32 asid = kvm_ecx_read(vcpu);
+       int cpu;
 
        if (nested_svm_check_permissions(vcpu))
                return 1;
 
        trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
 
Quoted 13 lines

arch/x86/kvm/svm/svm.c static int clgi_interception(struct kvm_vcpu *vcpu) · line 2487

Quoted 8 lines
arch/x86/kvm/svm/svm.c +6 -2
-       /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
-       kvm_mmu_invlpg(vcpu, gva);
+       /*
+        * INVLPG on a non-canonical address is a NOP according to the SDM,
+        * assume the same behavior from INVLPGA since the APM doesn't specify.
+        */
+       if (is_noncanonical_invlpg_address(gva, vcpu))
+               return kvm_skip_emulated_instruction(vcpu);

If L1 is in 32-bit mode with junk in RAX[63:32] (e.g. bits left over from long mode), the full 64-bit value may not be canonical. Should the kvm_rax_read(vcpu) above be kvm_register_read(vcpu, VCPU_REGS_RAX)?

Quoted 2 lines

Doesn't kvm_rax_read() already use kvm_reg_mode_mask() as per __BUILD_KVM_GPR_ACCESSORS()?

Yes, Jim's probably thinking of older kernels before fc40b1254c32 ("KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers").

#79 lore raw

Re: [PATCH v3 24/27] KVM: nSVM: Flush L2's ASID when emulating INVLPGA

Quoted 36 lines · Sean Christopherson
Quoted 34 lines · Yosry Ahmed
Quoted 32 lines · Jim Mattson
Quoted 17 lines
arch/x86/kvm/svm/svm.c +2 -0
index 8f2542357e78d..436d13f106369 100644
@@ -2468,17 +2468,61 @@ static int clgi_interception(struct kvm_vcpu *vcpu)
 
 static int invlpga_interception(struct kvm_vcpu *vcpu)
 {
+       struct vcpu_svm *svm = to_svm(vcpu);
        /* FIXME: Handle an address size prefix. */
        gva_t gva = kvm_rax_read(vcpu);
        u32 asid = kvm_ecx_read(vcpu);
+       int cpu;
 
        if (nested_svm_check_permissions(vcpu))
                return 1;
 

arch/x86/kvm/svm/svm.c static int clgi_interception(struct kvm_vcpu *vcpu) · line 2487

Quoted 10 lines
arch/x86/kvm/svm/svm.c +6 -2
        trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
 
-       /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
-       kvm_mmu_invlpg(vcpu, gva);
+       /*
+        * INVLPG on a non-canonical address is a NOP according to the SDM,
+        * assume the same behavior from INVLPGA since the APM doesn't specify.
+        */
+       if (is_noncanonical_invlpg_address(gva, vcpu))
+               return kvm_skip_emulated_instruction(vcpu);

If L1 is in 32-bit mode with junk in RAX[63:32] (e.g. bits left over from long mode), the full 64-bit value may not be canonical. Should the kvm_rax_read(vcpu) above be kvm_register_read(vcpu, VCPU_REGS_RAX)?

Quoted 5 lines
Quoted 2 lines

Doesn't kvm_rax_read() already use kvm_reg_mode_mask() as per __BUILD_KVM_GPR_ACCESSORS()?

Yes, Jim's probably thinking of older kernels before fc40b1254c32 ("KVM: x86: Add mode-aware versions of kvm_<reg>_{read,write}() helpers").

Doh! My bad.

#80 lore raw

PATCH v3 25/27 KVM: nSVM: Flush the ASID on nested transitions if shared by L1 and L2

In reply to Yosry Ahmed

If L1 and L2 use the same ASID in hardware, always flush it on nested transitions to avoid using L1 TLB entries for L2 or vice versa, since from L1's perspective they are two different TLB domains.

This is currently always the case, but KVM will start using separate ASIDs for L1 and L2 in most cases soon.

Note that KVM_REQ_TLB_FLUSH_CURRENT is required here, not KVM_REQ_TLB_FLUSH_GUEST (used for L1 TLB flush requests). This is because KVM could be switching between different NPT roots on the same ASID. While this generally requires an ASID flush in the VMCB, which is done by both KVM_REQ_TLB_FLUSH_CURRENT and KVM_REQ_TLB_FLUSH_GUEST, it also requires a hypercall to specifically flush NPT mappings when running on Hyper-V, which is only done with KVM_REQ_TLB_FLUSH_CURRENT (as KVM_REQ_TLB_FLUSH_GUEST is only meant to flush translations created by the guest).

Note that this is currently a noop as KVM requests KVM_REQ_TLB_FLUSH_CURRENT unconditionally on nested transitions, but this will soon be removed in favor of conditional flushes.

---
 arch/x86/kvm/svm/nested.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
arch/x86/kvm/svm/nested.c +10 -0
index 738ec1f2ec869..4ffc10bf9232e 100644
@@ -723,6 +723,13 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
 	}
 
+	/*
+	 * If L1 and L2 share the same ASID in hardware (when using the fallback
+	 * ASID for both, or for SEV guests), flush it on nested transitions.
+	 */
+	if (svm->asid == svm->nested.asid02)
+		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
+
 	/* TODO: optimize unconditional TLB flush/MMU sync */
 	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
@@ -738,6 +745,9 @@ static void nested_svm_exit_tlb_flush(struct kvm_vcpu *vcpu)
 	if (svm->nested.ctl.tlb_ctl == TLB_CONTROL_FLUSH_ALL_ASID)
 		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
 
+	if (svm->asid == svm->nested.asid02)
+		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
+
 	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
 }
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
Reviewed-by on v3 25/27
#81 lore raw

Re: [PATCH v3 25/27] KVM: nSVM: Flush the ASID on nested transitions if shared by L1 and L2

Quoted 18 lines · Yosry Ahmed

If L1 and L2 use the same ASID in hardware, always flush it on nested transitions to avoid using L1 TLB entries for L2 or vice versa, since from L1's perspective they are two different TLB domains.

This is currently always the case, but KVM will start using separate ASIDs for L1 and L2 in most cases soon.

Note that KVM_REQ_TLB_FLUSH_CURRENT is required here, not KVM_REQ_TLB_FLUSH_GUEST (used for L1 TLB flush requests). This is because KVM could be switching between different NPT roots on the same ASID. While this generally requires an ASID flush in the VMCB, which is done by both KVM_REQ_TLB_FLUSH_CURRENT and KVM_REQ_TLB_FLUSH_GUEST, it also requires a hypercall to specifically flush NPT mappings when running on Hyper-V, which is only done with KVM_REQ_TLB_FLUSH_CURRENT (as KVM_REQ_TLB_FLUSH_GUEST is only meant to flush translations created by the guest).

Quoted 5 lines

Note that this is currently a noop as KVM requests KVM_REQ_TLB_FLUSH_CURRENT unconditionally on nested transitions, but this will soon be removed in favor of conditional flushes.

#82 lore raw

PATCH v3 26/27 KVM: nSVM: Use different ASIDs for L1 and L2

In reply to Yosry Ahmed

Now that TLB flushes are properly handled and tracked for L1 vs L2 ASIDs, allocate a separate new ASID for L2 for each vCPU, similar to how VMX handles VPIDs. Drop the unconditional flushes and syncs on nested transitions.

L1 and L2 can now only share an ASID in two cases:
- KVM runs out of ASIDs and uses the fallback ASID for both L1 and L2.
- SEV VMs always use the same ASID for SEV-specific requirements.

WARN if the ASID is shared otherwise.

Initialize last_asid to 0, such that the L2 ASID is always flushed on first nested VM-Enter after it's allocated.

On SEV VM migration, free the L2 ASID on the destination vCPU (if nested was already initialized) before overwriting it with the SEV ASID.

On a Turin CPU, this results in 8-15% performance boost in CPUID rate microbenchmark [1] and netperf TCP_RR latency/throughput.

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

---
 arch/x86/kvm/svm/nested.c | 32 +++++++++++++++++++++++---------
 arch/x86/kvm/svm/sev.c    |  6 ++++--
 2 files changed, 27 insertions(+), 11 deletions(-)
arch/x86/kvm/svm/nested.c +23 -9
index 4ffc10bf9232e..6fe68f2ae282d 100644
@@ -711,6 +711,10 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 	 * context is not tagged by the ASID, so the shadow NPTs cannot be
 	 * reused across different L2 ASIDs.
 	 *
+	 * Note, last_asid is initialized as 0, so the first nested VM-Enter
+	 * after setting EFER.SVME will always flush the TLB to avoid using
+	 * stale entries.
+	 *
 	 * If L1 requested a full TLB flush for all ASIDs (including its own),
 	 * L1's own ASID is also flushed on nested VM-Exit, before running L1.
 	 *
@@ -727,12 +731,10 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
 	 * If L1 and L2 share the same ASID in hardware (when using the fallback
 	 * ASID for both, or for SEV guests), flush it on nested transitions.
 	 */
-	if (svm->asid == svm->nested.asid02)
+	if (svm->asid == svm->nested.asid02) {
+		WARN_ON_ONCE(svm->asid != fallback_asid && !is_sev_guest(vcpu));
 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
-
-	/* TODO: optimize unconditional TLB flush/MMU sync */
-	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
-	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
+	}
 }
 
 static void nested_svm_exit_tlb_flush(struct kvm_vcpu *vcpu)
@@ -747,9 +749,6 @@ static void nested_svm_exit_tlb_flush(struct kvm_vcpu *vcpu)
 
 	if (svm->asid == svm->nested.asid02)
 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
-
-	kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
-	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
 }
 
 /*
@@ -1566,7 +1565,20 @@ int svm_allocate_nested(struct vcpu_svm *svm)
 	svm->nested.vmcb02.ptr = page_address(vmcb02_page);
 	svm->nested.vmcb02.pa = __sme_set(page_to_pfn(vmcb02_page) << PAGE_SHIFT);
 
-	svm->nested.asid02 = svm->asid;
+	svm->nested.asid02 = allocate_asid(&svm->vcpu);
+
+	/*
+	 * KVM uses a fallback ASID when out of ASIDs, and fails vCPU creation
+	 * if there's no fallback ASID. ASID allocation must succeed here.
+	 */
+	KVM_BUG_ON(!svm->nested.asid02, svm->vcpu.kvm);
+
+	/*
+	 * Clear last_asid to ensure that the ASID is flushed on the first
+	 * nested VM-Enter. Otherwise, stale TLB entries from a previous life of
+	 * the ASID (e.g. different vCPU or even different VM) could be used.
+	 */
+	svm->nested.last_asid = 0;
 
 	return 0;
 
@@ -1583,6 +1595,8 @@ void svm_free_nested(struct vcpu_svm *svm)
 	if (WARN_ON_ONCE(svm->vmcb != svm->vmcb01.ptr))
 		svm_switch_vmcb(svm, &svm->vmcb01);
 
+	free_asid(svm->nested.asid02);
+
 	svm_vcpu_free_msrpm(svm->nested.msrpm);
 	svm->nested.msrpm = NULL;
 
arch/x86/kvm/svm/sev.c +4 -2
index b2e6acfbb081f..646108e70e21a 100644
@@ -2043,10 +2043,12 @@ static void sev_vcpu_migrate_asid(struct vcpu_svm *dst_svm,
 	dst_svm->asid = asid;
 
 	/*
-	 * If nested is already initialized on the destination vCPU, also update
-	 * the nested ASID to match the new SEV ASID.
+	 * If nested is already initialized on the destination vCPU, also free
+	 * the previous ASID (in case it was non-SEV) and update the nested ASID
+	 * to match the new SEV ASID.
 	 */
 	if (dst_svm->nested.vmcb02.ptr) {
+		free_asid(dst_svm->nested.asid02);
 		dst_svm->nested.asid02 = asid;
 		dst_svm->nested.vmcb02.ptr->control.asid = asid;
 	}
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#83 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 47 lines · Yosry Ahmed

Now that TLB flushes are properly handled and tracked for L1 vs L2 ASIDs, allocate a separate new ASID for L2 for each vCPU, similar to how VMX handles VPIDs. Drop the unconditional flushes and syncs on nested transitions.

L1 and L2 can now only share an ASID in two cases:
- KVM runs out of ASIDs and uses the fallback ASID for both L1 and L2.
- SEV VMs always use the same ASID for SEV-specific requirements.

WARN if the ASID is shared otherwise.

Initialize last_asid to 0, such that the L2 ASID is always flushed on first nested VM-Enter after it's allocated.

On SEV VM migration, free the L2 ASID on the destination vCPU (if nested was already initialized) before overwriting it with the SEV ASID.

On a Turin CPU, this results in 8-15% performance boost in CPUID rate microbenchmark [1] and netperf TCP_RR latency/throughput.

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

---
 arch/x86/kvm/svm/nested.c | 32 +++++++++++++++++++++++---------
 arch/x86/kvm/svm/sev.c    |  6 ++++--
 2 files changed, 27 insertions(+), 11 deletions(-)
arch/x86/kvm/svm/nested.c +4 -0
index 4ffc10bf9232e..6fe68f2ae282d 100644
@@ -711,6 +711,10 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
         * context is not tagged by the ASID, so the shadow NPTs cannot be
         * reused across different L2 ASIDs.
         *
+        * Note, last_asid is initialized as 0, so the first nested VM-Enter
+        * after setting EFER.SVME will always flush the TLB to avoid using
+        * stale entries.
+        *
         * If L1 requested a full TLB flush for all ASIDs (including its own),
         * L1's own ASID is also flushed on nested VM-Exit, before running L1.
         *
@@ -727,12 +731,10 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
         * If L1 and L2 share the same ASID in hardware (when using the fallback
         * ASID for both, or for SEV guests), flush it on nested transitions.

arch/x86/kvm/svm/nested.c static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu) · line 737

Quoted 10 lines
arch/x86/kvm/svm/nested.c +3 -5
         */
-       if (svm->asid == svm->nested.asid02)
+       if (svm->asid == svm->nested.asid02) {
+               WARN_ON_ONCE(svm->asid != fallback_asid && !is_sev_guest(vcpu));
                kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
-
-       /* TODO: optimize unconditional TLB flush/MMU sync */
-       kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
-       kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
+       }

Per the APM, volume 2, Section 15.16.1, "TLB Flush":

Quoted 1 line

All TLB entries belonging to all ASIDs are flushed by SMI, RSM, MTRR modifications, IORR modifications, and access to other system MSRs that affect address translation.

With two separate ASIDs and the unconditional flush removed, do we flush both ASIDs in the above instances?

Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

Nit: with this change, the following stale comment in svm_flush_tlb_asid() needs to be updated:

/*
* Flush only the current ASID even if the TLB flush was invoked via
* kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
* ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
* unconditionally does a TLB flush on both nested VM-Enter and nested
* VM-Exit (via kvm_mmu_reset_context()).
*/

#84 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 61 lines · Jim Mattson
Quoted 47 lines · Yosry Ahmed

Now that TLB flushes are properly handled and tracked for L1 vs L2 ASIDs, allocate a separate new ASID for L2 for each vCPU, similar to how VMX handles VPIDs. Drop the unconditional flushes and syncs on nested transitions.

L1 and L2 can now only share an ASID in two cases:
- KVM runs out of ASIDs and uses the fallback ASID for both L1 and L2.
- SEV VMs always use the same ASID for SEV-specific requirements.

WARN if the ASID is shared otherwise.

Initialize last_asid to 0, such that the L2 ASID is always flushed on first nested VM-Enter after it's allocated.

On SEV VM migration, free the L2 ASID on the destination vCPU (if nested was already initialized) before overwriting it with the SEV ASID.

On a Turin CPU, this results in 8-15% performance boost in CPUID rate microbenchmark [1] and netperf TCP_RR latency/throughput.

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

---
 arch/x86/kvm/svm/nested.c | 32 +++++++++++++++++++++++---------
 arch/x86/kvm/svm/sev.c    |  6 ++++--
 2 files changed, 27 insertions(+), 11 deletions(-)
arch/x86/kvm/svm/nested.c +4 -0
index 4ffc10bf9232e..6fe68f2ae282d 100644
@@ -711,6 +711,10 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
         * context is not tagged by the ASID, so the shadow NPTs cannot be
         * reused across different L2 ASIDs.
         *
+        * Note, last_asid is initialized as 0, so the first nested VM-Enter
+        * after setting EFER.SVME will always flush the TLB to avoid using
+        * stale entries.
+        *
         * If L1 requested a full TLB flush for all ASIDs (including its own),
         * L1's own ASID is also flushed on nested VM-Exit, before running L1.
         *
@@ -727,12 +731,10 @@ static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu)
         * If L1 and L2 share the same ASID in hardware (when using the fallback
         * ASID for both, or for SEV guests), flush it on nested transitions.

arch/x86/kvm/svm/nested.c static void nested_svm_entry_tlb_flush(struct kvm_vcpu *vcpu) · line 737

Quoted 10 lines
arch/x86/kvm/svm/nested.c +3 -5
         */
-       if (svm->asid == svm->nested.asid02)
+       if (svm->asid == svm->nested.asid02) {
+               WARN_ON_ONCE(svm->asid != fallback_asid && !is_sev_guest(vcpu));
                kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
-
-       /* TODO: optimize unconditional TLB flush/MMU sync */
-       kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
-       kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
+       }

Per the APM, volume 2, Section 15.16.1, "TLB Flush":

Quoted 4 lines
Quoted 1 line

All TLB entries belonging to all ASIDs are flushed by SMI, RSM, MTRR modifications, IORR modifications, and access to other system MSRs that affect address translation.

With two separate ASIDs and the unconditional flush removed, do we flush both ASIDs in the above instances?

SMI and RSM, yeah I think so. kvm_smm_changed() -> kvm_mmu_reset_context() deletes all roots, and kvm_mmu_load() will flush the current ASID when a new root is loaded.

MTRR writes seem to do nothing beyond store the value, probably since 0a7b73559b39 ("KVM: x86: Remove VMX support for virtualizing guest MTRR memtypes"). It is documented as an errata but I maybe KVM should still flush the TLB? If that's a real bug, it's separate from this series tho. We just need to make sure if we fix it, we should flush both ASIDs. We can probably just reset the MMU context here too?

I can't find anything related to IORR in KVM.

For MSRs, I think the relevant ones are EFER and PAT:

- For EFER, a change to KVM_MMU_EFER_ROLE_BITS resets the MMU similar to SMI/RSM, so covers both ASIDs. Clearing EFER.SVME frees L2's ASID and re-allocating an ASID will flush it by clearing last_asid.

- For PAT, I am not sure if that falls under "system MSRs that affect address translation", but KVM isn't flushing for L1 today on PAT writes anyway, so I hope not?

Quoted 5 lines

Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

I am honestly not sure. It seems like we should be flushing the context that issued the PV flush. But I also suppose (aside from Hyper-V) all L2 PV calls should go to L1, not L0, so should we always flush L1's context here?

It would be a pre-existing bug, but this series would be adding it to SVM as well. Adding David here since his name appears all over the git log for that code, so hopefully he'll tell us for sure.

Quoted 5 lines

Nit: with this change, the following stale comment in svm_flush_tlb_asid() needs to be updated:

Quoted 7 lines

/*
* Flush only the current ASID even if the TLB flush was invoked via
* kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
* ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
* unconditionally does a TLB flush on both nested VM-Enter and nested
* VM-Exit (via kvm_mmu_reset_context()).
*/

Will fix.

Thanks!

#85 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 4 lines · Yosry Ahmed
Quoted 2 lines · Jim Mattson
Quoted 1 line · Yosry Ahmed

[ ... ]

Quoted 10 lines
Quoted 6 lines

Per the APM, volume 2, Section 15.16.1, "TLB Flush":

Quoted 1 line

All TLB entries belonging to all ASIDs are flushed by SMI, RSM, MTRR modifications, IORR modifications, and access to other system MSRs that affect address translation.

With two separate ASIDs and the unconditional flush removed, do we flush both ASIDs in the above instances?

SMI and RSM, yeah I think so. kvm_smm_changed() -> kvm_mmu_reset_context() deletes all roots, and kvm_mmu_load() will flush the current ASID when a new root is loaded.

Okay. Is this mechanism obvious to those who are versed in the ways of the KVM MMU?

Quoted 6 lines

MTRR writes seem to do nothing beyond store the value, probably since 0a7b73559b39 ("KVM: x86: Remove VMX support for virtualizing guest MTRR memtypes"). It is documented as an errata but I maybe KVM should still flush the TLB? If that's a real bug, it's separate from this series tho. We just need to make sure if we fix it, we should flush both ASIDs. We can probably just reset the MMU context here too?

Probably. Admittedly, it's orthogonal to this series.

Quoted 1 line

I can't find anything related to IORR in KVM.

Me neither. :)

Quoted 5 lines

For MSRs, I think the relevant ones are EFER and PAT:

- For EFER, a change to KVM_MMU_EFER_ROLE_BITS resets the MMU similar to SMI/RSM, so covers both ASIDs. Clearing EFER.SVME frees L2's ASID and re-allocating an ASID will flush it by clearing last_asid.

Okay.

Quoted 3 lines

- For PAT, I am not sure if that falls under "system MSRs that affect address translation", but KVM isn't flushing for L1 today on PAT writes anyway, so I hope not?

Maybe not. Intel, at least, puts the burden of flushing TLBs on software. In volume 3 of the SDM, section 14.12.4, "Programming the PAT":

Quoted 16 lines

The operating system (OS) is responsible for ensuring that changes to a PAT entry occur in a manner that maintains the consistency of the processor caches and translation lookaside buffers (TLB). It requires the OS to invalidate all affected TLB entries (including global entries) and all entries in all paging-tructure caches.

Quoted 5 lines

Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

Quoted 8 lines

I am honestly not sure. It seems like we should be flushing the context that issued the PV flush. But I also suppose (aside from Hyper-V) all L2 PV calls should go to L1, not L0, so should we always flush L1's context here?

It would be a pre-existing bug, but this series would be adding it to SVM as well. Adding David here since his name appears all over the git log for that code, so hopefully he'll tell us for sure.

It's just happenstance that the PV TLB flush mechanism works with nSVM today, but I don't think we should feel free to break it.

#86 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 14 lines · Jim Mattson
Quoted 4 lines · Yosry Ahmed
Quoted 2 lines · Jim Mattson
Quoted 1 line · Yosry Ahmed

[ ... ]

Quoted 7 lines
Quoted 6 lines

Per the APM, volume 2, Section 15.16.1, "TLB Flush":

Quoted 1 line

All TLB entries belonging to all ASIDs are flushed by SMI, RSM, MTRR modifications, IORR modifications, and access to other system MSRs that affect address translation.

With two separate ASIDs and the unconditional flush removed, do we flush both ASIDs in the above instances?

Quoted 6 lines
Quoted 3 lines

SMI and RSM, yeah I think so. kvm_smm_changed() -> kvm_mmu_reset_context() deletes all roots, and kvm_mmu_load() will flush the current ASID when a new root is loaded.

Okay. Is this mechanism obvious to those who are versed in the ways of the KVM MMU?

I don't consider myself versed in the ways of the KVM MMU, it took me a few minutes to track this done, so I think it's okay.

Quoted 9 lines
Quoted 7 lines

MTRR writes seem to do nothing beyond store the value, probably since 0a7b73559b39 ("KVM: x86: Remove VMX support for virtualizing guest MTRR memtypes"). It is documented as an errata but I maybe KVM should still flush the TLB? If that's a real bug, it's separate from this series tho. We just need to make sure if we fix it, we should flush both ASIDs. We can probably just reset the MMU context here too?

Probably. Admittedly, it's orthogonal to this series.

Agreed.

Quoted 13 lines
Quoted 2 lines

I can't find anything related to IORR in KVM.

Me neither. :)

Quoted 5 lines

For MSRs, I think the relevant ones are EFER and PAT:

- For EFER, a change to KVM_MMU_EFER_ROLE_BITS resets the MMU similar to SMI/RSM, so covers both ASIDs. Clearing EFER.SVME frees L2's ASID and re-allocating an ASID will flush it by clearing last_asid.

Okay.

Quoted 9 lines
Quoted 3 lines

- For PAT, I am not sure if that falls under "system MSRs that affect address translation", but KVM isn't flushing for L1 today on PAT writes anyway, so I hope not?

Maybe not. Intel, at least, puts the burden of flushing TLBs on software. In volume 3 of the SDM, section 14.12.4, "Programming the PAT":

Quoted 1 line

The operating system (OS) is responsible for ensuring that changes to a PAT entry occur in a manner that maintains the consistency of the processor caches and translation lookaside buffers (TLB). It requires the OS to invalidate all affected TLB entries (including global entries) and all entries in all paging-tructure caches.

Nice!

Quoted 20 lines
Quoted 20 lines
Quoted 6 lines

Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

I am honestly not sure. It seems like we should be flushing the context that issued the PV flush. But I also suppose (aside from Hyper-V) all L2 PV calls should go to L1, not L0, so should we always flush L1's context here?

Quoted 6 lines
Quoted 3 lines

It would be a pre-existing bug, but this series would be adding it to SVM as well. Adding David here since his name appears all over the git log for that code, so hopefully he'll tell us for sure.

It's just happenstance that the PV TLB flush mechanism works with nSVM today, but I don't think we should feel free to break it.

Nested virtualization on Intel is probably more popular than AMD at this point, so my gut feeling is that we shouldn't block on fixing this. But I agree we shouldn't feel free to break it either. Will wait for Sean or David to chime in before deciding the way forward, but if there's a fix it would be separate from this series imo anyway.

#87 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 10 lines · Yosry Ahmed
Quoted 9 lines · Jim Mattson
Quoted 4 lines · Yosry Ahmed
Quoted 2 lines · Jim Mattson
Quoted 1 line · Yosry Ahmed

[ ... ]

Quoted 2 lines
Quoted 2 lines

Per the APM, volume 2, Section 15.16.1, "TLB Flush":

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 4 lines
Quoted 1 line

All TLB entries belonging to all ASIDs are flushed by SMI, RSM, MTRR modifications, IORR modifications, and access to other system MSRs that affect address translation.

With two separate ASIDs and the unconditional flush removed, do we flush both ASIDs in the above instances?

SMI and RSM, yeah I think so. kvm_smm_changed() -> kvm_mmu_reset_context() deletes all roots, and kvm_mmu_load() will flush

s/deletes/unloads, because the roots themselves are almost always still reachable through the hashed list of shadow pages.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

the current ASID when a new root is loaded.

Okay. Is this mechanism obvious to those who are versed in the ways of the KVM MMU?

I don't consider myself versed in the ways of the KVM MMU, it took me a few minutes to track this done, so I think it's okay.

No, it's not ok, though it's also not something that needs to be addressed in this series. Historically, KVM relied on kvm_mmu_reset_context() to perform TLB flushes basically everywhere, e.g. on CR0 and CR4 writes. It was a nightmare on multiple fronts, e.g. it was suboptimal when toggling bits that needed a TLB flush but not a full MMU rebuild, and understanding whether KVM was deliberately doing TLB flushes or not was difficult, which in turn made trying to optimize any of that code very painful because it meant disentangling years of KVM code *and* pouring over the SDM and APM to make sure we got the TLB flushes right.

In short, the fact that kvm_mmu_reset_context() happens to guarantee a TLB flush of the new/current root is a side effect and an implementation detail. If a TLB flush (for the guest) is architecturally required, then KVM should emulate that exact requirement, even if it means queueing up what will be redundant flushes. That makes it easier for newcomers to follow the code, and gives us more freedom to tweak and optimize MMU context changes/resets.

Concretely:

Author: Paolo Bonzini <[email protected]>
AuthorDate: Mon Feb 14 11:50:36 2022 -0500
Commit: Paolo Bonzini <[email protected]>
CommitDate: Tue Mar 1 08:50:42 2022 -0500

KVM: x86: flush TLB separately from MMU reset

For both CR0 and CR4, disassociate the TLB flush logic from the MMU role logic. Instead of relying on kvm_mmu_reset_context() being a superset of various TLB flushes (which is not necessarily going to be the case in the future), always call it if the role changes but also set the various TLB flush requests according to what is in the manual.

For SVM, the redundant flushes are a complete non-issue. It's basically an extra memory write.

For VMX, the INVVPID isn't free, but for emulated SMM I can't imagine it's a meaningful performance issue. And FWIW, the only reason not doing KVM_REQ_TLB_FLUSH_GUEST isn't a bug is because hardware isn't allowed to cache linear mappings when EPT is in used (and INVEPT invalidates both guest-physical and combined mappings).

#88 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

In reply to Jim Mattson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

#89 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 16 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

Quoted 8 lines

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

#90 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 21 lines · Yosry Ahmed
Quoted 20 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

Quoted 6 lines
Quoted 4 lines

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Heh, probably not this calendar year.

#91 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 23 lines · Sean Christopherson
Quoted 21 lines · Yosry Ahmed
Quoted 20 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

#92 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 29 lines · Yosry Ahmed
Quoted 28 lines · Sean Christopherson
Quoted 26 lines · Yosry Ahmed
Quoted 24 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Are you implying that *you* will be re-introducing deferred actions? :P

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

Nah, though I should just fix the damn bug. It's not hard, I just don't want to do it because I don't want to reintroduce a deferred request. Untested, but I think this is all that's needed.

arch/x86/include/asm/kvm_host.h +1 -0
index 0378577d9d8b..696aae38f619 100644
@@ -879,6 +879,7 @@ struct kvm_vcpu_arch {
 
 	struct {
 		u8 preempted;
+		bool flush_tlb_pending;
 		u64 msr_val;
 		u64 last_steal;
 		struct gfn_to_hva_cache cache;
arch/x86/kvm/regs.h +5 -0
index 97c17b120a57..efa54f9f9e9a 100644
@@ -469,6 +469,11 @@ static inline void leave_guest_mode(struct kvm_vcpu *vcpu)
 		kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
 	}
 
+	if (vcpu->arch.st.flush_tlb_pending) {
+		kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
+		vcpu->arch.st.flush_tlb_pending = false;
+	}
+
 	vcpu->stat.guest_mode = 0;
 }
 
arch/x86/kvm/x86.c +6 -2
index 32563a91fba9..15eb033b8e17 100644
@@ -2117,8 +2117,12 @@ static void record_steal_time(struct kvm_vcpu *vcpu)
 
 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
 				       st_preempted & KVM_VCPU_FLUSH_TLB);
-		if (st_preempted & KVM_VCPU_FLUSH_TLB)
-			kvm_vcpu_flush_tlb_guest(vcpu);
+		if (st_preempted & KVM_VCPU_FLUSH_TLB) {
+			if (!is_guest_mode(vcpu))
+				kvm_vcpu_flush_tlb_guest(vcpu);
+			else
+				vcpu->arch.st.flush_tlb_pending = true;
+		}
 
 		if (!user_access_begin(st, sizeof(*st)))
 			goto dirty;
#93 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 33 lines · Sean Christopherson
Quoted 31 lines · Yosry Ahmed
Quoted 30 lines · Sean Christopherson
Quoted 27 lines · Yosry Ahmed
Quoted 16 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

Quoted 8 lines

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

Nah, though I should just fix the damn bug. It's not hard, I just don't want to do it because I don't want to reintroduce a deferred request. Untested, but I think this is all that's needed.

Makes sense to the untrained eye, although I do wonder sometimes if requests more generally need a way to key off guest mode. I am sure you don't want to open this can of worms :)

Quoted 48 lines
arch/x86/include/asm/kvm_host.h +1 -0
index 0378577d9d8b..696aae38f619 100644
@@ -879,6 +879,7 @@ struct kvm_vcpu_arch {
 
        struct {
                u8 preempted;
+               bool flush_tlb_pending;
                u64 msr_val;
                u64 last_steal;
                struct gfn_to_hva_cache cache;
arch/x86/kvm/regs.h +5 -0
index 97c17b120a57..efa54f9f9e9a 100644
@@ -469,6 +469,11 @@ static inline void leave_guest_mode(struct kvm_vcpu *vcpu)
                kvm_make_request(KVM_REQ_LOAD_EOI_EXITMAP, vcpu);
        }
 
+       if (vcpu->arch.st.flush_tlb_pending) {
+               kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
+               vcpu->arch.st.flush_tlb_pending = false;
+       }
+
        vcpu->stat.guest_mode = 0;
 }
 
arch/x86/kvm/x86.c +6 -2
index 32563a91fba9..15eb033b8e17 100644
@@ -2117,8 +2117,12 @@ static void record_steal_time(struct kvm_vcpu *vcpu)
 
                trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
                                       st_preempted & KVM_VCPU_FLUSH_TLB);
-               if (st_preempted & KVM_VCPU_FLUSH_TLB)
-                       kvm_vcpu_flush_tlb_guest(vcpu);
+               if (st_preempted & KVM_VCPU_FLUSH_TLB) {
+                       if (!is_guest_mode(vcpu))
+                               kvm_vcpu_flush_tlb_guest(vcpu);
+                       else
+                               vcpu->arch.st.flush_tlb_pending = true;
+               }
 
                if (!user_access_begin(st, sizeof(*st)))
                        goto dirty;
#94 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 39 lines · Yosry Ahmed
Quoted 38 lines · Sean Christopherson
Quoted 35 lines · Yosry Ahmed
Quoted 23 lines · Sean Christopherson
Quoted 21 lines · Yosry Ahmed
Quoted 20 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

Quoted 7 lines
Quoted 3 lines

Nah, though I should just fix the damn bug. It's not hard, I just don't want to do it because I don't want to reintroduce a deferred request. Untested, but I think this is all that's needed.

Makes sense to the untrained eye, although I do wonder sometimes if requests more generally need a way to key off guest mode. I am sure you don't want to open this can of worms :)

It's not so much a can of worms as it is infeasible to come up with a generic scheme that would add value. The hardest part in all of this is identifying when an action/request *always* needs to be serviced in the context of L1, e.g. this code has been around for ages and it wasn't until Jimshiko came along that anyone noticed there's a bug.

The actual servicing of the request in L1 is straightforward and vendor specific for the vast majority of cases. E.g. guard(vmx_vmcs01) is essentially what you're asking for, but it's obviously VMX specific beause SVM can simply grab the pointer to vmcb01. In other words, there isn't a general need to defer requests or have a framework for servicing requests while L2 is active.

This one is special because of legacy shadow paging, and specifically the need to synchronizing the MMU. In theory, we could temporarily switch to L1's MMU, a la vmcs01, but it's entirely possible L1's MMU doesn't even "exist", e.g. because the host state that will be loaded from the VMCS on nested VM-Exit is different than the pre-VM-Enter state (which is possible on Intel). Even if the MMU context was known, switching MMUs at this point in the KVM_RUN flow is terrifying.

So, while I detest the deferred approach, I also think it's absolutely the right thing to do for a fix that needs to go to stable@, and probably the least awful fix long term as well. But it's very much a one-off snowflake, not something we should generally encourage.

#95 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 68 lines · Sean Christopherson
Quoted 39 lines · Yosry Ahmed
Quoted 38 lines · Sean Christopherson
Quoted 35 lines · Yosry Ahmed
Quoted 23 lines · Sean Christopherson
Quoted 21 lines · Yosry Ahmed
Quoted 20 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

Quoted 7 lines
Quoted 3 lines

Nah, though I should just fix the damn bug. It's not hard, I just don't want to do it because I don't want to reintroduce a deferred request. Untested, but I think this is all that's needed.

Makes sense to the untrained eye, although I do wonder sometimes if requests more generally need a way to key off guest mode. I am sure you don't want to open this can of worms :)

It's not so much a can of worms as it is infeasible to come up with a generic scheme that would add value. The hardest part in all of this is identifying when an action/request *always* needs to be serviced in the context of L1, e.g. this code has been around for ages and it wasn't until Jimshiko came along that anyone noticed there's a bug.

The actual servicing of the request in L1 is straightforward and vendor specific for the vast majority of cases. E.g. guard(vmx_vmcs01) is essentially what you're asking for, but it's obviously VMX specific beause SVM can simply grab the pointer to vmcb01. In other words, there isn't a general need to defer requests or have a framework for servicing requests while L2 is active.

This one is special because of legacy shadow paging, and specifically the need to synchronizing the MMU. In theory, we could temporarily switch to L1's MMU, a la vmcs01, but it's entirely possible L1's MMU doesn't even "exist", e.g. because the host state that will be loaded from the VMCS on nested VM-Exit is different than the pre-VM-Enter state (which is possible on Intel). Even if the MMU context was known, switching MMUs at this point in the KVM_RUN flow is terrifying.

Quoted 4 lines

So, while I detest the deferred approach, I also think it's absolutely the right thing to do for a fix that needs to go to stable@, and probably the least awful fix long term as well. But it's very much a one-off snowflake, not something we should generally encourage.

The other example I thought about is kvm_service_local_tlb_flush_requests(), AFAICT this only exists because we don't have a way to specify a request for L1/L2. But yeah, I agree if these are the exceptions rather than the rule.

In my head, there was also a request we clear for exceptions on nested VM-Exit, but looking at the code again, it's not a request, we clear the exception and interrupt queues. I think this is the right thing to do architecturally anyway though?

#96 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

Quoted 74 lines · Yosry Ahmed
Quoted 68 lines · Sean Christopherson
Quoted 39 lines · Yosry Ahmed
Quoted 38 lines · Sean Christopherson
Quoted 35 lines · Yosry Ahmed
Quoted 23 lines · Sean Christopherson
Quoted 21 lines · Yosry Ahmed
Quoted 20 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

Quoted 7 lines
Quoted 3 lines

Nah, though I should just fix the damn bug. It's not hard, I just don't want to do it because I don't want to reintroduce a deferred request. Untested, but I think this is all that's needed.

Makes sense to the untrained eye, although I do wonder sometimes if requests more generally need a way to key off guest mode. I am sure you don't want to open this can of worms :)

It's not so much a can of worms as it is infeasible to come up with a generic scheme that would add value. The hardest part in all of this is identifying when an action/request *always* needs to be serviced in the context of L1, e.g. this code has been around for ages and it wasn't until Jimshiko came along that anyone noticed there's a bug.

The actual servicing of the request in L1 is straightforward and vendor specific for the vast majority of cases. E.g. guard(vmx_vmcs01) is essentially what you're asking for, but it's obviously VMX specific beause SVM can simply grab the pointer to vmcb01. In other words, there isn't a general need to defer requests or have a framework for servicing requests while L2 is active.

This one is special because of legacy shadow paging, and specifically the need to synchronizing the MMU. In theory, we could temporarily switch to L1's MMU, a la vmcs01, but it's entirely possible L1's MMU doesn't even "exist", e.g. because the host state that will be loaded from the VMCS on nested VM-Exit is different than the pre-VM-Enter state (which is possible on Intel). Even if the MMU context was known, switching MMUs at this point in the KVM_RUN flow is terrifying.

Quoted 4 lines

So, while I detest the deferred approach, I also think it's absolutely the right thing to do for a fix that needs to go to stable@, and probably the least awful fix long term as well. But it's very much a one-off snowflake, not something we should generally encourage.

Quoted 4 lines

The other example I thought about is kvm_service_local_tlb_flush_requests(), AFAICT this only exists because we don't have a way to specify a request for L1/L2. But yeah, I agree if these are the exceptions rather than the rule.

Yes and no. Doing the "obvious" thing by tracking L1 vs. L2 requests would be subtly wrong. E.g. if L2 triggers a flush with virtual ASID=1, then KVM must service the flush in exactly that context. If KVM shoved the request into e.g. l2_requests and serviced those at the next entry to L2, then KVM could process the TLB flush using the wrong virtual ASID.

So while I get where you're coming from, I think the current approach of using a unified requests queue and then servicing the requests that are "local" to L2 on nested VM-Exit is the "right" approach.

Quoted 4 lines

In my head, there was also a request we clear for exceptions on nested VM-Exit, but looking at the code again, it's not a request, we clear the exception and interrupt queues. I think this is the right thing to do architecturally anyway though?

Yep. If an event is supposed to be preserved, then it needs to be saved into the exit fields of the VMC{B,S}. KVM's software model should always be reset.

#97 lore raw

Re: [PATCH v3 26/27] KVM: nSVM: Use different ASIDs for L1 and L2

In reply to Sean Christopherson
Quoted 32 lines · Sean Christopherson
Quoted 31 lines · Yosry Ahmed
Quoted 30 lines · Sean Christopherson
Quoted 27 lines · Yosry Ahmed
Quoted 16 lines · Sean Christopherson
Quoted 5 lines · Jim Mattson

On Mon, Oct 12, 2026 at 4:37 PM Yosry Ahmed <[email protected]> wrote:
Moreover, does this change the semantics of PV TLB flush? In record_steal_time(), we have:

if (st_preempted & KVM_VCPU_FLUSH_TLB)

Quoted 8 lines
        kvm_vcpu_flush_tlb_guest(vcpu);

IIUC, an idle vCPU that wakes into L2 will flush only L2's ASID. In the past, with a shared ASID, L1's ASID was always flushed on emulated VM-exit anyway. Now, L1's ASID will be unaffected. Though I can't find any real documentation on PV TLB flush, it *seems* like the remote vCPU would want L1's ASID to be flushed. OTOH, this change makes nSVM behave just like nVMX.

Quoted 8 lines

That's a bug that absolutely needs to be fixed, probably relatively urgently. We should also document that passing through the steal_time shared information to L2 to utilize PV TLB flushes for L2 is explicitly not supported.

I hate to re-introduce deferred actions for L2 => L1 things, but that seems like the only sane way to handle this, because handling the !tdp_enabled case, where KVM needs to sync the current root, requires knowing what MMU is going to be in use when L1 regains control. Yuck.

Are you implying that *you* will be re-introducing deferred actions? :P

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Heh, probably not this calendar year.

Are you opposed to this series landing before that is fixed, keeping in mind that it will expose nSVM to the pre-existing bug?

Nah, though I should just fix the damn bug. It's not hard, I just don't want to do it because I don't want to reintroduce a deferred request. Untested, but I think this is all that's needed.

Early warning, so that you don't post a new version of the series and then have to respin again. I'm planning on posting a fix that plumbs an @l1_pv_flush flag around instead of deferring the fix. I realized that KVM synchronizes *all* MMUs for the !tdp_enabled case, which means that all flushing immediately is overall less risky than deferring the flush (and obviously I was looking for any excuse to not re-introduce deferred actions).

I peeked at the rest of this series, and AFAICT it won't throw too big of a wrench in things.

---
KVM: x86: Always target L1 when handling steal-time PV TLB flushes

Explicitly target L1 when handling steal-time based PV TLB flushes, as KVM's undocumented ABI for its PV features is that they are scoped to L1, e.g. KVM hypercalls from L2 are routed to L1 or rejected with a #UD.

Route a flag through all the flush_tlb_guest() paths to basically ignore is_guest_mode() as appropriate. Note! KVM synchronizes all MMUs, past and present, when servicing a guest TLB flush, i.e. there is no need to switch from targeting L2 to targeting L1 for that specific flow.

Alternatively, KVM could defer PV TLB flushes until L1 is active, but the correctness of waiting to synchronize MMUs when TDP is disabled is dubious, as KVM has historically synchronized *all* MMUs for the vCPU. And from the guest's perspective (other vCPUs), KVM has communicated the the flush has already occurred. And in general, KVM has moved away from deferred L2=>L1 actions, precisely because of similar edge cases.

Fixes 2b4a5a5d5688 ("KVM: nVMX: Flush current VPID (L1 vs. L2) for KVM_REQ_TLB_FLUSH_GUEST")
Cc Yosry Ahmed <[email protected]>
arch/x86/include/asm/kvm_host.h +1 -1
index 0378577d9d8b..51bb66d1618a 100644
@@ -1598,7 +1598,7 @@ struct kvm_x86_ops {
 	 * Flush any TLB entries created by the guest.  Like tlb_flush_gva(),
 	 * does not need to flush GPA->HPA mappings.
 	 */
-	void (*flush_tlb_guest)(struct kvm_vcpu *vcpu);
+	void (*flush_tlb_guest)(struct kvm_vcpu *vcpu, bool l1_pv_flush);
 
 	bool (*vcpu_needs_initialization)(struct kvm_vcpu *vcpu);
 	enum exit_fastpath_completion (*vcpu_run)(struct kvm_vcpu *vcpu,
arch/x86/kvm/hyperv.h +5 -3
index 622a6553e9ac..3ece27d34398 100644
@@ -312,14 +312,16 @@ static inline struct kvm_vcpu_hv_tlb_flush_fifo *kvm_hv_get_tlb_flush_fifo(struc
 	return &hv_vcpu->tlb_flush_fifo[i];
 }
 
-static inline void kvm_hv_vcpu_purge_flush_tlb(struct kvm_vcpu *vcpu)
+static inline void kvm_hv_vcpu_purge_flush_tlb(struct kvm_vcpu *vcpu,
+					       bool l1_pv_flush)
 {
 	struct kvm_vcpu_hv_tlb_flush_fifo *tlb_flush_fifo;
 
 	if (!kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu))
 		return;
 
-	tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(vcpu, is_guest_mode(vcpu));
+	tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(vcpu, !l1_pv_flush &&
+							 is_guest_mode(vcpu));
 	if (!tlb_flush_fifo)
 		return;
 
@@ -396,7 +398,7 @@ static inline int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
 {
 	return HV_STATUS_ACCESS_DENIED;
 }
-static inline void kvm_hv_vcpu_purge_flush_tlb(struct kvm_vcpu *vcpu) {}
+static inline void kvm_hv_vcpu_purge_flush_tlb(struct kvm_vcpu *vcpu, bool l1_pv_flush) {}
 static inline bool kvm_hv_synic_has_vector(struct kvm_vcpu *vcpu, int vector)
 {
 	return false;
arch/x86/kvm/svm/svm.c +11 -11
index 581bc3a23c95..f045dc010027 100644
@@ -4304,7 +4304,7 @@ static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
 	svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
 }
 
-static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
+static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu, bool l1_pv_flush)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
 
@@ -4313,14 +4313,14 @@ static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
 	 * A TLB flush for the current ASID flushes both "host" and "guest" TLB
 	 * entries, and thus is a superset of Hyper-V's fine grained flushing.
 	 */
-	kvm_hv_vcpu_purge_flush_tlb(vcpu);
+	kvm_hv_vcpu_purge_flush_tlb(vcpu, l1_pv_flush);
 
 	/*
 	 * Flush only the current ASID even if the TLB flush was invoked via
-	 * kvm_flush_remote_tlbs().  Although flushing remote TLBs requires all
-	 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
-	 * unconditionally does a TLB flush on both nested VM-Enter and nested
-	 * VM-Exit (via kvm_mmu_reset_context()).
+	 * kvm_flush_remote_tlbs() or is a PV TLB flush targeting L1.  Although
+	 * flushing remote TLBs requires all ASIDs to be flushed, KVM uses a
+	 * single ASID for L1 and L2, and unconditionally does a TLB flush on
+	 * both nested VM-Enter and nested VM-Exit (via kvm_mmu_reset_context()).
 	 */
 	if (cpu_feature_enabled(X86_FEATURE_FLUSHBYASID))
 		svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
@@ -4341,7 +4341,7 @@ static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
 	if (svm_hv_is_enlightened_tlb_enabled(vcpu) && VALID_PAGE(root_tdp))
 		hyperv_flush_guest_mapping(root_tdp);
 
-	svm_flush_tlb_asid(vcpu);
+	svm_flush_tlb_asid(vcpu, false);
 }
 
 static void svm_flush_tlb_all(struct kvm_vcpu *vcpu)
@@ -4356,14 +4356,14 @@ static void svm_flush_tlb_all(struct kvm_vcpu *vcpu)
 	if (WARN_ON_ONCE(svm_hv_is_enlightened_tlb_enabled(vcpu)))
 		hv_flush_remote_tlbs(vcpu->kvm);
 
-	svm_flush_tlb_asid(vcpu);
+	svm_flush_tlb_asid(vcpu, false);
 }
 
-static void svm_flush_tlb_guest(struct kvm_vcpu *vcpu)
+static void svm_flush_tlb_guest(struct kvm_vcpu *vcpu, bool l1_pv_flush)
 {
 	kvm_register_mark_dirty(vcpu, VCPU_REG_ERAPS);
 
-	svm_flush_tlb_asid(vcpu);
+	svm_flush_tlb_asid(vcpu, l1_pv_flush);
 }
 
 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
@@ -4381,7 +4381,7 @@ static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
 		return;
 	}
 
-	svm_flush_tlb_guest(vcpu);
+	svm_flush_tlb_guest(vcpu, false);
 }
 
 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
arch/x86/kvm/vmx/main.c +2 -2
index d75170a6199e..c2b5c04cd2b8 100644
@@ -547,12 +547,12 @@ static void vt_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
 	vmx_flush_tlb_gva(vcpu, addr);
 }
 
-static void vt_flush_tlb_guest(struct kvm_vcpu *vcpu)
+static void vt_flush_tlb_guest(struct kvm_vcpu *vcpu, bool l1_pv_flush)
 {
 	if (is_td_vcpu(vcpu))
 		return;
 
-	vmx_flush_tlb_guest(vcpu);
+	vmx_flush_tlb_guest(vcpu, l1_pv_flush);
 }
 
 static void vt_inject_nmi(struct kvm_vcpu *vcpu)
arch/x86/kvm/vmx/vmx.c +5 -2
index b341af4c6057..e6a61514e797 100644
@@ -3398,7 +3398,7 @@ void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
 	vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr);
 }
 
-void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
+void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu, bool l1_pv_flush)
 {
 	/*
 	 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a
@@ -3407,7 +3407,10 @@ void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
 	 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
 	 * i.e. no explicit INVVPID is necessary.
 	 */
-	vpid_sync_context(vmx_get_current_vpid(vcpu));
+	if (l1_pv_flush)
+		vpid_sync_context(to_vmx(vcpu)->vpid);
+	else
+		vpid_sync_context(vmx_get_current_vpid(vcpu));
 }
 
 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
arch/x86/kvm/vmx/x86_ops.h +1 -1
index cd72684d075d..67e5dd728267 100644
@@ -82,7 +82,7 @@ bool vmx_get_if_flag(struct kvm_vcpu *vcpu);
 void vmx_flush_tlb_all(struct kvm_vcpu *vcpu);
 void vmx_flush_tlb_current(struct kvm_vcpu *vcpu);
 void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr);
-void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu);
+void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu, bool l1_pv_flush);
 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask);
 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu);
 void vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall);
arch/x86/kvm/x86.c +6 -6
index 26e7beaff8a0..3bbd15b64e99 100644
@@ -2009,7 +2009,7 @@ static void kvm_vcpu_flush_tlb_all(struct kvm_vcpu *vcpu)
 	kvm_clear_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
 }
 
-static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
+static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu, bool l1_pv_flush)
 {
 	++vcpu->stat.tlb_flush;
 
@@ -2024,13 +2024,13 @@ static void kvm_vcpu_flush_tlb_guest(struct kvm_vcpu *vcpu)
 		kvm_mmu_sync_prev_roots(vcpu);
 	}
 
-	kvm_x86_call(flush_tlb_guest)(vcpu);
+	kvm_x86_call(flush_tlb_guest)(vcpu, l1_pv_flush);
 
 	/*
 	 * Flushing all "guest" TLB is always a superset of Hyper-V's fine
 	 * grained flushing.
 	 */
-	kvm_hv_vcpu_purge_flush_tlb(vcpu);
+	kvm_hv_vcpu_purge_flush_tlb(vcpu, l1_pv_flush);
 }
 
 
@@ -2052,7 +2052,7 @@ void kvm_service_local_tlb_flush_requests(struct kvm_vcpu *vcpu)
 		kvm_vcpu_flush_tlb_current(vcpu);
 
 	if (kvm_check_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu))
-		kvm_vcpu_flush_tlb_guest(vcpu);
+		kvm_vcpu_flush_tlb_guest(vcpu, false);
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);
 
@@ -2118,7 +2118,7 @@ static void record_steal_time(struct kvm_vcpu *vcpu)
 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
 				       st_preempted & KVM_VCPU_FLUSH_TLB);
 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
-			kvm_vcpu_flush_tlb_guest(vcpu);
+			kvm_vcpu_flush_tlb_guest(vcpu, true);
 
 		if (!user_access_begin(st, sizeof(*st)))
 			goto dirty;
@@ -8193,7 +8193,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 #ifdef CONFIG_KVM_HYPERV
 		if (kvm_check_request(KVM_REQ_HV_TLB_FLUSH, vcpu) &&
 		    kvm_hv_vcpu_flush_tlb(vcpu))
-			kvm_vcpu_flush_tlb_guest(vcpu);
+			kvm_vcpu_flush_tlb_guest(vcpu, false);
 #endif
 
 		if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
#98 lore raw

PATCH v3 27/27 KVM: selftests: Add a test for nested TLB flushes

In reply to Yosry Ahmed

Add a test that exercises most common scenarios for TLB flushes. The test is split into two testing scenarios:
1. Guest-triggered TLB flushes
2. KVM-triggered TLB flushes

For (1), the test runs an L1 guest that keeps switching an L2 PTE (or TDP PTE) between two GPAs, flushes the TLB, and runs L2 to check that accessing that address accesses the correct page. A missed TLB flush causes L2 to access the wrong GPA through a stale TLB entry. The test exercises multiple ways for L1 to flush the TLB, including changing L2's ASID/VPID, flushing L2's entire ASID/VPID/EPTP, or flushing an individual L2 GVA (using INVLPGA/INVVPID) when L1 does not enable TDP.

On AMD, the test also checks that an ASID flush (or an ASID change) flushes shadow NPT mappings for all nCR3 roots, not just the current one, by using multiple nested NPT trees.

For (2), the test creates a memslot with 2 pages, and keeps moving the base GPA of the memslot between a TEST_GPA and TEST_GPA - PAGE_SIZE, essentially resulting in the TEST_GPA being switched between two underlying HPAs. KVM should flush the TLB for both L1 and L2 contexts when updating a GPA -> HPA mapping.

The test runs an L1 guest that verifies access to page 1, triggers the memslot move, and checks that both L1 and L2 now (correctly) access page 2. This verifies that a TLB flush in L1's context flushes the TLB for both L1 and L2. After that, the test does the opposite and triggers the memslot move from L2, to double check that a TLB flush in L2's context flushes the TLB for both L1 and L2.

The test runs various test cases with TDP on/off in L1, and actually catches multiple injected bugs (in SVM), including:
- Missing the TLB flush on nested VM-Enter if ASID12 changes.
- Missing the TLB flush on nested VM-Enter if L1 uses TLB_CONTROL_FLUSH_ASID.
- Missing the nested NPT resync on nested VM-Enter if L1 uses TLB_CONTROL_FLUSH_ASID with nested NPT enabled.
- Missing the TLB flush when emulating INVLPGA.
- Missing flushing both L1 and L2 ASIDs when handling KVM_REQ_TLB_FLUSH.

Assisted-by LLM
---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../selftests/kvm/include/x86/processor.h     |   1 +
 tools/testing/selftests/kvm/include/x86/svm.h |   5 +
 tools/testing/selftests/kvm/include/x86/vmx.h |  21 +
 .../testing/selftests/kvm/lib/x86/processor.c |  36 ++
 .../selftests/kvm/x86/nested_tlb_flush_test.c | 526 ++++++++++++++++++
 6 files changed, 590 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/nested_tlb_flush_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index be5eb2dd85aa2..5347c56786b08 100644
@@ -122,6 +122,7 @@ TEST_GEN_PROGS_x86 += x86/svm_nested_shutdown_test
 TEST_GEN_PROGS_x86 += x86/svm_nested_soft_inject_test
 TEST_GEN_PROGS_x86 += x86/svm_nested_vmcb12_gpa
 TEST_GEN_PROGS_x86 += x86/svm_nested_pat_test
+TEST_GEN_PROGS_x86 += x86/nested_tlb_flush_test
 TEST_GEN_PROGS_x86 += x86/svm_lbr_nested_state
 TEST_GEN_PROGS_x86 += x86/svm_pmu_host_guest_test
 TEST_GEN_PROGS_x86 += x86/tsc_scaling_sync
tools/testing/selftests/kvm/include/x86/processor.h +1 -0
index ffec2291b1e1f..62d255aee5a34 100644
@@ -1617,6 +1617,7 @@ void tdp_map(struct kvm_vm *vm, gpa_t l2_gpa, gpa_t gpa, u64 size);
 void tdp_identity_map_default_memslots(struct kvm_vm *vm);
 void tdp_identity_map_1g(struct kvm_vm *vm,  u64 addr, u64 size);
 u64 *tdp_get_pte(struct kvm_vm *vm, u64 l2_gpa);
+gpa_t tdp_copy_page_tables(struct kvm_vm *vm);
 
 /*
  * Basic CPU control in CR0
tools/testing/selftests/kvm/include/x86/svm.h +5 -0
index c8539166270ea..d2a6bf8503f78 100644
@@ -316,4 +316,9 @@ struct __attribute__ ((__packed__)) vmcb {
 
 #define SVM_CR0_SELECTIVE_MASK (X86_CR0_TS | X86_CR0_MP)
 
+static inline void invlpga(unsigned long addr, u32 asid)
+{
+	asm volatile("invlpga %0, %1" : : "a"(addr), "c"(asid) : "memory");
+}
+
 #endif /* SELFTEST_KVM_SVM_H */
tools/testing/selftests/kvm/include/x86/vmx.h +21 -0
index 8fd97434eee5c..4f2a0e3ac5ba1 100644
@@ -518,4 +518,25 @@ static inline bool kvm_cpu_has_vmx_virtualize_apic_accesses(void)
 void vm_enable_ept(struct kvm_vm *vm);
 void prepare_virtualize_apic_accesses(struct vmx_pages *vmx, struct kvm_vm *vm);
 
+static inline void invvpid(unsigned long ext, u16 vpid, gva_t gva)
+{
+	struct {
+		u64 vpid : 16;
+		u64 rsvd : 48;
+		u64 gva;
+	} operand = { vpid, 0, gva };
+
+	asm volatile("invvpid %0, %1" : : "m"(operand), "r"(ext) : "memory");
+}
+
+static inline void invept(unsigned long ext, u64 eptp)
+{
+	struct {
+		u64 eptp;
+		u64 rsvd;
+	} operand = { eptp, 0 };
+
+	asm volatile("invept %0, %1" : : "m"(operand), "r"(ext) : "memory");
+}
+
 #endif /* SELFTEST_KVM_VMX_H */
tools/testing/selftests/kvm/lib/x86/processor.c +36 -0
index 8374afd08bafe..57ecf8b381b5a 100644
@@ -554,6 +554,42 @@ void tdp_identity_map_1g(struct kvm_vm *vm, u64 addr, u64 size)
 	__tdp_map(vm, addr, addr, size, PG_LEVEL_1G);
 }
 
+static gpa_t __virt_copy_page_tables(struct kvm_vm *vm, struct kvm_mmu *mmu,
+				     gpa_t table_gpa, int level)
+{
+	gpa_t copy_gpa = vm_alloc_page_table(vm);
+	u64 *copy = addr_gpa2hva(vm, copy_gpa);
+	gpa_t pa;
+	int i;
+
+	memcpy(copy, addr_gpa2hva(vm, table_gpa), vm->page_size);
+	if (level == PG_LEVEL_4K)
+		return copy_gpa;
+
+	for (i = 0; i < vm->page_size / sizeof(u64); i++) {
+		if (!is_present_pte(mmu, &copy[i]) || is_huge_pte(mmu, &copy[i]))
+			continue;
+
+		/* Clear only the address bits, preserving C/S bits and flags */
+		pa = vm_untag_gpa(vm, PTE_GET_PA(copy[i]));
+		copy[i] &= ~pa;
+		copy[i] |= __virt_copy_page_tables(vm, mmu, pa, level - 1);
+	}
+	return copy_gpa;
+}
+
+/*
+ * Deep copy all levels of the TDP page tables, such that no page table pages
+ * are shared with the original.  Returns the GPA of the new root.
+ */
+gpa_t tdp_copy_page_tables(struct kvm_vm *vm)
+{
+	struct kvm_mmu *mmu = &vm->stage2_mmu;
+
+	TEST_ASSERT(mmu->pgd_created, "TDP page tables not created");
+	return __virt_copy_page_tables(vm, mmu, mmu->pgd, mmu->pgtable_levels);
+}
+
 /*
  * Set Unusable Segment
  *
tools/testing/selftests/kvm/x86/nested_tlb_flush_test.c new file +526 -0

526 lines not on this page · raw message

Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#99 lore raw
In reply to Yosry Ahmed
Quoted 10 lines · Yosry Ahmed

This series optimizes TLB flushes for nested SVM by using and maintaining a separate ASID for L2 for each vCPU (similar to VMX's handling of VPIDs), rather than sharing the same ASID and flushing everything on every nested transition.

The series also drops the dynamic ASID allocation scheme and uses a static ASID per vCPU (or two if using nested), bringing it closer to how VMX handles VPIDs. Modern CPUs (Rome, Milan, Genoa, Turin) advertise 32K ASIDs, so there is no need for dynamic allocation.

I'm not convinced that this is the right direction. It's almost always better to do things locally when possible. Why not keep the per-CPU generational allocation, but allocate two ASIDs per vCPU—one for each VMCB? This would eliminate the need for a fallback ASID and remove any possible concerns about contention for a global bitmap. Moreover, it would be much simpler to implement.

#100 lore raw
Quoted 13 lines · Jim Mattson
Quoted 10 lines · Yosry Ahmed

This series optimizes TLB flushes for nested SVM by using and maintaining a separate ASID for L2 for each vCPU (similar to VMX's handling of VPIDs), rather than sharing the same ASID and flushing everything on every nested transition.

The series also drops the dynamic ASID allocation scheme and uses a static ASID per vCPU (or two if using nested), bringing it closer to how VMX handles VPIDs. Modern CPUs (Rome, Milan, Genoa, Turin) advertise 32K ASIDs, so there is no need for dynamic allocation.

Quoted 4 lines

I'm not convinced that this is the right direction. It's almost always better to do things locally when possible. Why not keep the per-CPU generational allocation, but allocate two ASIDs per vCPU—one for each VMCB?

This is what a much older version of this series did:
https://lore.kernel.org/lkml/[email protected]/

Then we moved on to per-VM fixed ASIDs to align with SEV, but the tracking of "which vCPU used this ASID last" was annoying, so we settled on per-vCPU fixed ASIDs, similar to VPIDs, with the caveat of not being able to disable ASID (Hence the fallback ASID thing).

Other than alignment, dynamic allocation of ASIDs means that we need to handle the possibility of ASID reuse, which imo introduces more complexity than the fallback ASID logic, patch 10 lists three very recent fixups that we need to handle corner cases with dynamic ASID allocations:
https://lore.kernel.org/kvm/[email protected]/

There is a 4th one that was sent after patch 10.

Also, the dynamic ASID allocations give the VMs more noisy neighbor power, I think the ASID is reallocated on INIT, so a VM can trigger running out of ASIDs on a pCPU and flushing the ASIDs of all other VMs. Yes, we can handle this in INIT, but the problem is completely side-stepped by using static ASIDs.

Quoted 2 lines

This would eliminate the need for a fallback ASID and remove any possible concerns about contention for a global bitmap.

The fallback ASID logic is annoying, yes, but it's only in a few places. I don't think there's a risk of real contention in most practical use cases, we can run 32k vCPUs per pCPU before we run into issues. I think we will hit other scalability limits before the fallback ASID becomes a problem.

Quoted 1 line

Moreover, it would be much simpler to implement.

The delta is smaller and simpler, yes. But I think the static ASIDs code ends up being simpler to reason about.

#101 lore raw
Quoted 51 lines · Yosry Ahmed
Quoted 13 lines · Jim Mattson
Quoted 10 lines · Yosry Ahmed

This series optimizes TLB flushes for nested SVM by using and maintaining a separate ASID for L2 for each vCPU (similar to VMX's handling of VPIDs), rather than sharing the same ASID and flushing everything on every nested transition.

The series also drops the dynamic ASID allocation scheme and uses a static ASID per vCPU (or two if using nested), bringing it closer to how VMX handles VPIDs. Modern CPUs (Rome, Milan, Genoa, Turin) advertise 32K ASIDs, so there is no need for dynamic allocation.

Quoted 4 lines

I'm not convinced that this is the right direction. It's almost always better to do things locally when possible. Why not keep the per-CPU generational allocation, but allocate two ASIDs per vCPU—one for each VMCB?

This is what a much older version of this series did:
https://lore.kernel.org/lkml/[email protected]/

Then we moved on to per-VM fixed ASIDs to align with SEV, but the tracking of "which vCPU used this ASID last" was annoying, so we settled on per-vCPU fixed ASIDs, similar to VPIDs, with the caveat of not being able to disable ASID (Hence the fallback ASID thing).

Other than alignment, dynamic allocation of ASIDs means that we need to handle the possibility of ASID reuse, which imo introduces more complexity than the fallback ASID logic, patch 10 lists three very recent fixups that we need to handle corner cases with dynamic ASID allocations:
https://lore.kernel.org/kvm/[email protected]/

There is a 4th one that was sent after patch 10.

Also, the dynamic ASID allocations give the VMs more noisy neighbor power, I think the ASID is reallocated on INIT, so a VM can trigger running out of ASIDs on a pCPU and flushing the ASIDs of all other VMs. Yes, we can handle this in INIT, but the problem is completely side-stepped by using static ASIDs.

Quoted 2 lines

This would eliminate the need for a fallback ASID and remove any possible concerns about contention for a global bitmap.

The fallback ASID logic is annoying, yes, but it's only in a few places. I don't think there's a risk of real contention in most practical use cases, we can run 32k vCPUs per pCPU before we run into issues. I think we will hit other scalability limits before the fallback ASID becomes a problem.

Quoted 4 lines
Quoted 1 line

Moreover, it would be much simpler to implement.

The delta is smaller and simpler, yes. But I think the static ASIDs code ends up being simpler to reason about.

+1. The per-pCPU tracking might require less code, but OMG is it hard to reason about. I also hate having completely different schemes for VMX vs. SVM, it makes it extra difficult to reason about TLB stuff when looking at KVM x86 as a whole.

The other big argument for per-vCPU ASIDs is that it will allow us to elide TLB flushes on task migration[*], which might not be a major performance win for bare metal, but it can be a significant win when running nested.

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