Fixes for various (mostly x86) KVM vulnerabilities
Subsystems (10)
Paolo Bonzini
maintainercover Fixes for various (mostly x86) KVM vulnerabilities
Loongarch:
- Flush TLBs *before* dropping mmu_lock
RISC-V:
- Flush TLBs *before* dropping mmu_lock
x86:
- Flush TLB *before* dropping mmu_lock, and flush them entirely
- Flush TLBs if child SPTE is zapped when splitting a huge SPTE
- Pin kvm->mm prior to borrowing mm when setting event channel
- Disable hypervisor (VMX Preemption) timer if TSC deadline wraps
- Reset local APIC timer metadata on RESET, INIT, and KVM_SET_LAPIC
- Ensure guest FPU is resident in hardware when updating actual XFD MSR
- Ensure pCPU is valid before sending IPI to deliver posted IRQ
Generic:
- Invalidate all GFN=>PFN caches when VM and/or its process is dying
Paolo
Kyle Zeng (3):
RISC-V: KVM: Flush TLBs *before* dropping mmu_lock, e.g. when yielding
LoongArch: KVM: Flush TLBs *before* dropping mmu_lock
KVM: x86/mmu: Flush all TLB entries, not a precise range, when
yielding
Sean Christopherson (14):
KVM: x86/mmu: Flush TLBs if child SPTE is zapped when splitting a huge
SPTE
KVM: x86/mmu: Propagate the return from kvm_zap_all_rmap_sptes() out
of __rmap_add()
KVM: x86: Disable hypervisor (VMX Preemption) timer if TSC deadline
wraps
KVM: x86: Reset local APIC timer metadata on RESET, INIT, and
KVM_SET_LAPIC
KVM: x86/mmu: Flush TLBs in kvm_unmap_gfn_range() if the unmap may
block/yield
KVM: x86/xen: Pin kvm->mm prior to borrowing mm when setting event
channel
KVM: Fold kvm_flush_shadow_all() into kvm_mmu_notifier_release()
KVM: WARN if there are in-flight memslot updates when a VM's process
exits
KVM: Set mn_active_invalidate_count when the VM's mm is released
KVM: Invalidate all GFN=>PFN caches when VM and/or its process is
dying
x86/fpu: Bail early from guest XFD update if XFD isn't supported x86/fpu: Clear XSTATE_BV[i] in guest XSAVE state if guest FPU isn't
in-use
x86/fpu: Ensure guest FPU is resident in hardware when updating actual
XFD MSR
KVM: VMX: Ensure pCPU is valid before sending IPI to deliver posted
IRQ
arch/loongarch/kvm/mmu.c | 12 +++---- arch/riscv/kvm/gstage.c | 9 ++++- arch/riscv/kvm/mmu.c | 2 +- arch/x86/kernel/fpu/core.c | 37 ++++++++++++++------- arch/x86/kvm/lapic.c | 67 ++++++++++++++++++++++++++------------ arch/x86/kvm/mmu/mmu.c | 49 ++++++++++++++++++++++------ arch/x86/kvm/vmx/common.h | 5 +-- arch/x86/kvm/vmx/tdx.c | 4 +-- arch/x86/kvm/x86.c | 2 +- arch/x86/kvm/xen.c | 7 +++- virt/kvm/kvm_main.c | 61 +++++++++++++++++++++------------- virt/kvm/kvm_mm.h | 2 ++ virt/kvm/pfncache.c | 12 +++++++ 13 files changed, 190 insertions(+), 79 deletions(-)
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 1/17 KVM: x86/mmu: Flush TLBs if child SPTE is zapped when splitting a huge SPTE
From: Sean Christopherson <[email protected]>
Queue a TLB flush when eagerly splitting a huge SPTE and adding a child SPTE to the rmap fails due to hitting the recycle threshold. If adding to the rmap fails, __rmap_add() zaps the entire list of rmaps, including the recently-added child SPTE. Eliding the flush in that case is unsafe as the huge SPTE is still PRESENT, after the TLB flush performed by __rmap_add(), i.e. can be (re)cached by running vCPUs.
Push the TLB flush out from __rmap_add() to its two callers by returning a bool to indicate that a TLB flush is needed. Return "TLB flush needed" instead of success/failuire so that a feature cleanup can simply return the result of kvm_zap_all_rmap_sptes() (which *should* always be true; if there isn't at least one rmap entry, then things have really gone sideways).
--- arch/x86/kvm/mmu/mmu.c | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-)
arch/x86/kvm/mmu/mmu.c +16 -5
@@ -1736,7 +1736,7 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)#define RMAP_RECYCLE_THRESHOLD 1000 -static void __rmap_add (struct kvm *kvm, +static bool __rmap_add (struct kvm *kvm,struct kvm_mmu_memory_cache *cache,const struct kvm_memory_slot *slot,u64 *spte,gfn_t gfn,unsigned int access)
@@ -1756,8 +1756,9 @@ static void __rmap_add(struct kvm *kvm, kvm->stat.max_mmu_rmap_size = rmap_count;if (rmap_count >RMAP_RECYCLE_THRESHOLD ) {kvm_zap_all_rmap_sptes (kvm, rmap_head); -kvm_flush_remote_tlbs_gfn (kvm, gfn, sp->role.level); +return true; } +return false; } static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
@@ -1765,7 +1766,9 @@ static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot, {struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache; -__rmap_add (vcpu->kvm, cache, slot, spte, gfn, access); +if (__rmap_add (vcpu->kvm, cache, slot, spte, gfn, access)) +kvm_flush_remote_tlbs_gfn (vcpu->kvm, gfn, +sptep_to_sp (spte)->role.level); } static bool kvm_rmap_age_gfn_range(struct kvm *kvm,
@@ -7372,7 +7375,7 @@ static void shadow_mmu_split_huge_page(struct kvm *kvm,* * However, if a given SPTE points to a lower level page table, * that lower level page table may only be partially populated. -* Installing such SPTEs would effectively unmap a potion of the +* Installing such SPTEs would effectively unmap a portion of the * huge page. Unmapping guest memory always requires a TLB flush * since a subsequent operation on the unmapped regions would * fail to detect the need to flush.
@@ -7384,7 +7387,15 @@ static void shadow_mmu_split_huge_page(struct kvm *kvm, spte =make_small_spte (kvm, huge_spte, sp->role, index);mmu_spte_set (sptep, spte); -__rmap_add (kvm, cache, slot, sptep, gfn, sp->role.access); + +/* +* Queue a TLB flush if adding the SPTE to the rmap zapped the +* child SPTE that was just added. In that case, replacing the +* huge SPTE with a shadow page will effectively unmap guest +* memory (see above), as the huge SPTE is still PRESENT and +* can be (re)cached in the TLB before it is replaced. +*/ + flush |=__rmap_add (kvm, cache, slot, sptep, gfn, sp->role.access); }__link_shadow_page (kvm, cache, huge_sptep, sp, flush);
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 2/17 KVM: x86/mmu: Propagate the return from kvm_zap_all_rmap_sptes() out of __rmap_add()
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
When recycling all rmaps, propagate the result of kvm_zap_all_rmap_sptes() out of __rmap_add() instead of unconditionally returning "true", to make it more obvious why a TLB flush is required. Barring a KVM bug elsewhere that corrupts the rmaps (mmu_lock is held for write), it's impossible for kvm_zap_all_rmap_sptes() to return "false". And if rmaps are corrupted, KVM has far bigger problems then potentially leaving behind stale TLB entries.
Assuming there are no egregious, fatals bug elsewhere in KVM, no functional change intended.
--- arch/x86/kvm/mmu/mmu.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
arch/x86/kvm/mmu/mmu.c +3 -4
@@ -1754,10 +1754,9 @@ static bool __rmap_add(struct kvm *kvm,if (rmap_count > kvm->stat.max_mmu_rmap_size) kvm->stat.max_mmu_rmap_size = rmap_count; -if (rmap_count >RMAP_RECYCLE_THRESHOLD ) { -kvm_zap_all_rmap_sptes (kvm, rmap_head); -return true; - } +if (rmap_count >RMAP_RECYCLE_THRESHOLD ) +return kvm_zap_all_rmap_sptes (kvm, rmap_head); +return false; }
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 3/17 KVM: x86: Disable hypervisor (VMX Preemption) timer if TSC deadline wraps
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Disable the VMX Preemption Timer, by configuring the deadline to be '0', if converting from a one-shot/periodic expiry to a deadline would wrap the TSC, i.e. would result in a deadline that's far in the past, even though the expiry is firmly in the future. Architecturally, delivering the APIC timer IRQ way too early is obviously wrong, but the bigger problem is what can happen if the APIC timer is in periodic mode.
If the guest sets its TSC to a large value, but not _too_ large, puts it APIC timer into periodic mode, and then programs the maximal period, then KVM will compute a TSC deadline that is far "earlier" than the current TSC, but with plenty of headroom for guest TSC to continue counting without the TSC itself wrapping. Even though the VMX side of things detects that the timer has already expired, KVM leaves the hypervisor timer armed so that it can compute the new deadline/expiry from the VM-Exit handler. On the VMX side of things, KVM handles the "deadline in the past" by forcing the VMX Preemption Timer to '0', which generates an immediate VM-Exit.
All of that would be "fine", except that KVM handles VMX Preemption Timer exits in its fastpath, will recompute the same in-the-past deadline, and constantly re-enter the guest with a timer value of '0'. Architecturally, the SDM states that such behavior can trigger a VM-Exit *without* fetching any instructions in the guest.
It is possible for the VMX-preemption timer to expire during VM entry (e.g., if the value in the VMX-preemption timer-value field is zero). If this happens (and if the VM entry was not to the wait-for-SIPI state), a VM exit occurs with its normal priority after any event injection and before execution of any instruction following VM entry.
Empirically, on bare metal, if the timer expires "during" VM-Entry, the CPU may or may not recognize IRQs (it's not clear exactly what conditions lead to IRQs being recognized or not). In the worst case scenario, the host can experience hard lockups if the tight entry<=>exit loop never opens a window for host IRQs to be recognized.
The problem is especially noticeable when running as a KVM guest, as KVM *never* opens a window for host (L1) IRQs, even with non-zero (but small) VMX Preemption Timer values, as KVM-as-L0 starts the timer fairly early in the nested VM-Enter flow and so the timer always expires before the nested VM-Enter gets to the point where it checks for L1 IRQs.
Opportunistically read TSC and ktime in close succession when computing the target expiration and the TSC deadline, to minimize the divergence between the two (though in practice, reading the values even a few hundred cycles apart is a complete non-issue.
--- arch/x86/kvm/lapic.c | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-)
arch/x86/kvm/lapic.c +24 -13
@@ -2127,6 +2127,26 @@ static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict) (u64 )apic->divide_count; } +static u64 ns_to_tsc_deadline (struct kvm_lapic *apic,s64 delta) +{ +u64 tsc_now =rdtsc (); +u64 deadline; + +/* +* Disable the hypervisor timer, which is deadline-based, if converting +* the one-shot/periodic expiry to a TSC deadline wraps the TSC, i.e. +* results in a deadline far in the past, even though the expiry itself +* is in the future. Alternatively, KVM could track the deadline as a +* 128 bit value, but in practice the deadline will only wrap if the +* guest is doing weird things with TSC (which is writable via MSR). +*/ +if (check_add_overflow (kvm_read_l1_tsc (apic->vcpu, tsc_now), +nsec_to_cycles (apic->vcpu, delta), &deadline)) +return 0 ; + +return deadline; +} +static void update_target_expiration (struct kvm_lapic *apic,uint32_t old_divisor) {ktime_t now, remaining;
@@ -2145,19 +2165,14 @@ static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_diviso ns_remaining_new =mul_u64_u32_div (ns_remaining_old, apic->divide_count, old_divisor); - apic->lapic_timer.tscdeadline += -nsec_to_cycles (apic->vcpu, ns_remaining_new) - -nsec_to_cycles (apic->vcpu, ns_remaining_old); apic->lapic_timer.target_expiration =ktime_add_ns (now, ns_remaining_new); + apic->lapic_timer.tscdeadline =ns_to_tsc_deadline (apic, ns_remaining_new); }static bool set_target_expiration (struct kvm_lapic *apic,u32 count_reg) { -ktime_t now; -u64 tscl =rdtsc ();s64 deadline; - now =ktime_get (); apic->lapic_timer.period =tmict_to_ns (apic,kvm_lapic_get_reg (apic,APIC_TMICT ));
@@ -2194,10 +2209,8 @@ static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg) } } - apic->lapic_timer.tscdeadline =kvm_read_l1_tsc (apic->vcpu, tscl) + -nsec_to_cycles (apic->vcpu, deadline); - apic->lapic_timer.target_expiration =ktime_add_ns (now, deadline); - + apic->lapic_timer.target_expiration =ktime_add_ns (ktime_get (), deadline); + apic->lapic_timer.tscdeadline =ns_to_tsc_deadline (apic, deadline);return true; }
@@ -2205,7 +2218,6 @@ static void advance_periodic_target_expiration(struct kvm_lapic *apic) {struct kvm_timer *ktimer = &apic->lapic_timer;ktime_t now =ktime_get (); -u64 tscl =rdtsc ();ktime_t delta;/*
@@ -2236,8 +2248,7 @@ static void advance_periodic_target_expiration(struct kvm_lapic *apic)* excessively large due to it an unsigned value. */ delta =ktime_sub (ktimer->target_expiration, now); - ktimer->tscdeadline =kvm_read_l1_tsc (apic->vcpu, tscl) + -nsec_to_cycles (apic->vcpu, delta); + ktimer->tscdeadline =ns_to_tsc_deadline (apic,ktime_to_ns (delta)); }static void start_sw_period (struct kvm_lapic *apic)
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 4/17 KVM: x86: Reset local APIC timer metadata on RESET, INIT, and KVM_SET_LAPIC
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Reset all of the local APIC timer's metadata that's tied to the current state of the timer on INIT (and RESET) and KVM_SET_LAPIC, *except* for the TSC deadline when doing KVM_SET_LAPIC, as kvm_timer.tscdeadline subtly holds/tracks the value of MSR_IA32_TSC_DEADLINE and isn't computed by __start_apic_timer(). In particular, leaving the target expiration as-is allows a misbehaving guest to induce a divide error by overflowing a u64.
After INIT (or RESET), the divide count register is '0', which translates to an actual divisor of '2'. The other divisors are 1, 4, 8, 16, 32, 64, and 128, so the guest can scale the target_expiration from 2x-64x after every INIT (or cut it in half, but that's uninteresting). After enough multiplications, things go kablooie. E.g. setting the target_expiration to -1u (TMICT is a 32-bit value) and then scaling by 64x via a divisor of 128 generates a #DE after 6 rounds of INIT:
Oops: divide error: 0000 [#1] SMP CPU: 0 UID: 1000 PID: 604 Comm: div_error Not tainted 7.3.0-rc7-e86da2bfcc430-sink-all #7307 PREEMPTLAZY Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 0.0.0 02/06/2015 RIP: 0010:kvm_lapic_reg_write+0x364/0x7d0 [kvm] <TASK> kvm_set_msr_common+0x649/0x1540 [kvm] vmx_set_msr+0xdb5/0x13a0 [kvm_intel] __kvm_set_msr+0xc4/0x2a0 [kvm] kvm_set_msr_ignored_check+0x1d/0x140 [kvm] __kvm_emulate_wrmsr+0x36/0x170 [kvm] vt_handle_exit+0x1e/0x50 [kvm_intel] kvm_arch_vcpu_ioctl_run+0x972/0x21c0 [kvm] kvm_vcpu_ioctl+0x2c7/0x960 [kvm] __x64_sys_ioctl+0x90/0xd0 do_syscall_64+0x9c/0x4d0 entry_SYSCALL_64_after_hwframe+0x4b/0x53 RIP: 0033:0x421d1b </TASK> Modules linked in: kvm_intel kvm irqbypass
Opportunistically purge the target_expiration and expired_tscdeadline when the timer mode changes to/from deadline mode, even though that path should be fine (it doesn't interact with the divide count).
--- arch/x86/kvm/lapic.c | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-)
arch/x86/kvm/lapic.c +22 -8
@@ -1905,6 +1905,23 @@ static void cancel_apic_timer(struct kvm_lapic *apic)atomic_set (&apic->lapic_timer.pending,0 ); } +static void __kvm_lapic_reset_timer (struct kvm_lapic *apic) +{ +struct kvm_timer *ktimer = &apic->lapic_timer; + +cancel_apic_timer (apic); + + ktimer->period =0 ; + ktimer->target_expiration =0 ; + ktimer->expired_tscdeadline =0 ; +} + +static void kvm_lapic_reset_timer (struct kvm_lapic *apic) +{ +__kvm_lapic_reset_timer (apic); + apic->lapic_timer.tscdeadline =0 ; +} +static void apic_update_lvtt (struct kvm_lapic *apic) { u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
@@ -1913,10 +1930,8 @@ static void apic_update_lvtt(struct kvm_lapic *apic)if (apic->lapic_timer.timer_mode != timer_mode) {if (apic_lvtt_tscdeadline (apic) != (timer_mode ==APIC_LVT_TIMER_TSCDEADLINE )) { -cancel_apic_timer (apic); +kvm_lapic_reset_timer (apic);kvm_lapic_set_reg (apic,APIC_TMICT ,0 ); - apic->lapic_timer.period =0 ; - apic->lapic_timer.tscdeadline =0 ; } apic->lapic_timer.timer_mode = timer_mode;limit_periodic_timer_frequency (apic);
@@ -2999,8 +3014,7 @@ void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)if (!apic)return ; -/* Stop the timer in case it's a reset to an active apic */ -hrtimer_cancel (&apic->lapic_timer.timer); +kvm_lapic_reset_timer (apic);/* The xAPIC ID is set at RESET even if the APIC was already enabled. */ if (!init_event)
@@ -3037,7 +3051,6 @@ void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event) }kvm_apic_update_apicv (vcpu);update_divide_count (apic); -atomic_set (&apic->lapic_timer.pending,0 ); vcpu->arch.pv_eoi.msr_val =0 ;apic_update_ppr (apic);
@@ -3338,6 +3351,9 @@ int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)kvm_recalculate_apic_map (vcpu->kvm);return r; } + +__kvm_lapic_reset_timer (apic); +memcpy (vcpu->arch.apic->regs, s->regs,sizeof (*s));atomic_set_release (&apic->vcpu->kvm->arch.apic_map_dirty,DIRTY );
@@ -3345,8 +3361,6 @@ int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)kvm_apic_set_version (vcpu);apic_update_ppr (apic); -cancel_apic_timer (apic); - apic->lapic_timer.expired_tscdeadline =0 ;apic_update_lvtt (apic);apic_manage_nmi_watchdog (apic,kvm_lapic_get_reg (apic,APIC_LVT0 ));update_divide_count (apic);
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 5/17 RISC-V: KVM: Flush TLBs *before* dropping mmu_lock, e.g. when yielding
In reply to Paolo BonziniFrom: Kyle Zeng <[email protected]>
When unmapping a GPA range, flush TLBs for the processed GPA range *before* dropping mmu_lock. The ENTIRE point of holding mmu_lock is to ensure other MMU operations will either see the present stage-2 PTEs, or can rely on any references to the old PTEs being fully zapped.
E.g. if a MMU notifier invalidation event runs while the zapping task has dropped mmu_lock and yielded, then the MMU notifier task observe the missing PTE and return without issuing its own TLB flush, resulting in a use-after-free (if the to-be-invalidated page was freed or moved).
--- arch/riscv/kvm/gstage.c | 9 ++++++++- arch/riscv/kvm/mmu.c | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-)
arch/riscv/kvm/gstage.c +8 -1
@@ -449,8 +449,15 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,* If the range is too large, release the kvm->mmu_lock * to prevent starvation and lockup detector warnings. */ -if (!(gstage->flags &KVM_GSTAGE_FLAGS_LOCAL ) && may_block && addr < end) +if (!(gstage->flags &KVM_GSTAGE_FLAGS_LOCAL ) && may_block && addr < end && + (need_resched () ||rwlock_needbreak (&gstage->kvm->mmu_lock))) { +if (flush) { +kvm_flush_remote_tlbs_range (gstage->kvm, start >>PAGE_SHIFT , + (addr - start) >>PAGE_SHIFT ); + flush = false; + }cond_resched_rwlock_write (&gstage->kvm->mmu_lock); + } }return flush;
arch/riscv/kvm/mmu.c +1 -1
@@ -211,10 +211,10 @@ void kvm_arch_flush_shadow_memslot(struct kvm *kvm,write_lock (&kvm->mmu_lock); flush =kvm_riscv_gstage_unmap_range (&gstage, gpa, size, false); -write_unlock (&kvm->mmu_lock);if (flush)kvm_flush_remote_tlbs_range (kvm, gpa >>PAGE_SHIFT , size >>PAGE_SHIFT ); +write_unlock (&kvm->mmu_lock); }static void mmu_split_memory_region (struct kvm *kvm,int slot)
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 05/17] RISC-V: KVM: Flush TLBs *before* dropping mmu_lock, e.g. when yielding
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] kvm/riscv: kvm_riscv_gstage_unmap_range() does not advance start after flush --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] kvm/riscv: kvm_riscv_gstage_unmap_range() does not advance start after flush
--
commit ccd2570d983889b3cd09f172411aa813f45757db
Author: Kyle Zeng <[email protected]>
RISC-V: KVM: Flush TLBs *before* dropping mmu_lock, e.g. when yielding
This commit flushes remote TLBs before dropping mmu_lock when yielding in kvm_riscv_gstage_unmap_range(), and moves the remote TLB flush inside mmu_lock in kvm_arch_flush_shadow_memslot().
Quoted 8 lines
arch/riscv/kvm/gstage.c +0
-0@@ -449,8 +449,15 @@ bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage,* If the range is too large, release the kvm->mmu_lock * to prevent starvation and lockup detector warnings. */
arch/riscv/kvm/gstage.c bool kvm_riscv_gstage_unmap_range(struct kvm_gstage *gstage, · line 460
Quoted 10 lines
arch/riscv/kvm/gstage.c +8
-1-if (!(gstage->flags &KVM_GSTAGE_FLAGS_LOCAL ) && may_block && addr < end) +if (!(gstage->flags &KVM_GSTAGE_FLAGS_LOCAL ) && may_block && addr < end && + (need_resched () ||rwlock_needbreak (&gstage->kvm->mmu_lock))) { +if (flush) { +kvm_flush_remote_tlbs_range (gstage->kvm, start >>PAGE_SHIFT , + (addr - start) >>PAGE_SHIFT ); + flush = false; + }cond_resched_rwlock_write (&gstage->kvm->mmu_lock); + }
[Severity: Medium]
Should start be advanced to addr after flushing here?
When kvm_unmap_gfn_range() yields multiple times over a large range, leaving start unchanged re-flushes the cumulative [start, addr) range on each yield.
In kvm_riscv_local_hfence_gvma_vmid_gpa(), that repeats per-page flushes for already-invalidated pages and, once (addr - start) exceeds PTRS_PER_PTE pages (2 MiB on RV64), permanently falls back to kvm_riscv_local_hfence_gvma_vmid_all() on every subsequent yield.
mmu_split_huge_pages() advances last_flush_gfn after each pre-yield flush to avoid this.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Paolo Bonzini
maintainerPATCH 6/17 LoongArch: KVM: Flush TLBs *before* dropping mmu_lock
In reply to Paolo BonziniFrom: Kyle Zeng <[email protected]>
When flushing/unmapping stage-2 mappings in response to a memslot updates (including the "flush everything" when a VM is being destroyed), flush TLBs *before* dropping mmu_lock, as KVM relies on the stage-2 mappings being completely unreachable prior to dropping mmu_lock.
E.g. if a MMU notifier invalidation event runs after mmu_lock is dropped, but before TLBs are flushed, then the MMU notifier task can observe the missing PTE and return without issuing its own TLB flush, resulting in a use-after-free (if the to-be-invalidated page was freed or moved).
--- arch/loongarch/kvm/mmu.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-)
arch/loongarch/kvm/mmu.c +5 -7
@@ -300,18 +300,16 @@ static void kvm_flush_range(struct kvm *kvm, gfn_t start_gfn, gfn_t end_gfn, intkvm_ptw_prepare (kvm, &ctx);INIT_LIST_HEAD (&ctx.list); -if (lock) { +if (lock)spin_lock (&kvm->mmu_lock); - ret =kvm_ptw_top (kvm->arch.pgd, start_gfn <<PAGE_SHIFT , - end_gfn <<PAGE_SHIFT , &ctx); -spin_unlock (&kvm->mmu_lock); - }else - ret =kvm_ptw_top (kvm->arch.pgd, start_gfn <<PAGE_SHIFT , - end_gfn <<PAGE_SHIFT , &ctx); + ret =kvm_ptw_top (kvm->arch.pgd, start_gfn <<PAGE_SHIFT , + end_gfn <<PAGE_SHIFT , &ctx);/* Flush vpid for each vCPU individually */ if (ret)kvm_flush_remote_tlbs (kvm); +if (lock) +spin_unlock (&kvm->mmu_lock);/* * free pte table page after mmu_lock
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 7/17 KVM: x86/mmu: Flush all TLB entries, not a precise range, when yielding
In reply to Paolo BonziniFrom: Kyle Zeng <[email protected]>
Flush *all* TLB entries, not just the currently visible range of GFNs, when yielding and dropping mmu_lock the shadow MMU, as a pending flush may cover a bigger range than what is currently in scope, e.g. from a different memslot or from a different page-table level. Flushing only the range of GFNs that are directly relevant to the current slot+level result in KVM failing to TLB flush entries for previously-zapped SPTEs when running on Hyper-V (the only time the range-based flushing is used).
--- arch/x86/kvm/mmu/mmu.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/mmu.c +6 -2
@@ -1664,8 +1664,12 @@ static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,if (need_resched () ||rwlock_needbreak (&kvm->mmu_lock)) {if (flush && flush_on_yield) { -kvm_flush_remote_tlbs_range (kvm, start_gfn, - iterator.gfn - start_gfn +1 ); +/* +* DO NOT do a range-based flush, as the caller +* may be zapping a range greater than what is +* visible here! +*/ +kvm_flush_remote_tlbs (kvm); flush = false; }cond_resched_rwlock_write (&kvm->mmu_lock);
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 8/17 KVM: x86/mmu: Flush TLBs in kvm_unmap_gfn_range() if the unmap may block/yield
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Immediately flush TLBs if a flush is pending after unmapping a GFN range, *before* returning to the caller, if the overall unmap operation may block, i.e. if a *future* call to kvm_unmap_gfn_range() may yield and drop mmu_lock. Because kvm_unmap_gfn_range() starts with "flush = false", KVM incorrectly loses track of the pending flush if an overall unmap operation straddles multiple memslots. KVM will still service the TLB flush before the *caller* completes, but KVM relies on its mappings being completely unreachable prior to dropping mmu_lock.
E.g. if a MMU notifier invalidation event runs after mmu_lock is dropped, but before TLBs are flushed, then the MMU notifier task can observe the missing PTE and return without issuing its own TLB flush, resulting in a use-after-free (if the to-be-invalidated page was freed or moved).
Hack a fix into x86, but leave a TODO behind to undo the hack, or at least make it less awful. By dumb luck, x86 is the only arch that conditionally yields *and* utilizes the common TLB flushing mechanism.
--- arch/x86/kvm/mmu/mmu.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
arch/x86/kvm/mmu/mmu.c +15 -0
@@ -1735,6 +1735,21 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)kvm_make_all_cpus_request (kvm,KVM_REQ_APIC_PAGE_RELOAD ); +/* +* Immediately flush TLBs if a *future* invocation of the current unmap +* operation may block, in which case the pending flush will be dropped +* due to starting with "flush = false" above. +* +* TODO: Plumb @flush around common KVM so that pending flushes can be +* processed if and only if KVM actually yields, and so that this +* code doesn't rely on may_block being constant for the entirety +* of an unmap operation. +*/ +if (flush && range->may_block) { +kvm_flush_remote_tlbs (kvm); +return false; + } +return flush; }
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 9/17 KVM: x86/xen: Pin kvm->mm prior to borrowing mm when setting event channel
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
When setting a Xen event channel from a kthread, get a reference to the VM's mm prior to borrowing the mm, and bail with -EFAULT if the mm is dead or dying. The VM's irqfds are deactivated only when the VM itself is dying, i.e. the worker can trigger event channel writes if the VM's process exits before the VM itself is destroyed.
Note, there's no need to use mmput_async(), as kvm_xen_set_evtchn() borrows an mm if and only if it's already running in a workqueue.
--- arch/x86/kvm/xen.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
arch/x86/kvm/xen.c +6 -1
@@ -1984,6 +1984,9 @@ static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)if (WARN_ON_ONCE (current->mm))return -EINVAL ; +if (!mmget_not_zero (kvm->mm)) +return -EFAULT ; +kthread_use_mm (kvm->mm); mm_borrowed = true; }
@@ -2015,8 +2018,10 @@ static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)srcu_read_unlock (&kvm->srcu, idx); }while (!rc); -if (mm_borrowed) +if (mm_borrowed) {kthread_unuse_mm (kvm->mm); +mmput (kvm->mm); + }return rc; }
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 10/17 KVM: Fold kvm_flush_shadow_all() into kvm_mmu_notifier_release()
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Fold kvm_flush_shadow_all() into kvm_mmu_notifier_release() now that all all architectures use the generic mmu_notifier, i.e. all flow through .release() when the VM and/or process is dying. This will allow setting mn_active_invalidate_count and _leaving_ it set when all SPTEs are zapped, without having to worry about hypothetical scenarios where future KVM could invoke kvm_flush_shadow_all() prior to the VM/process dying.
No functional change intended.
--- virt/kvm/kvm_main.c | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-)
virt/kvm/kvm_main.c +2 -7
@@ -346,12 +346,6 @@ void kvm_flush_remote_tlbs_memslot(struct kvm *kvm,kvm_flush_remote_tlbs_range (kvm, memslot->base_gfn, memslot->npages); } -static void kvm_flush_shadow_all (struct kvm *kvm) -{ -kvm_arch_flush_shadow_all (kvm); -kvm_arch_guest_memory_reclaimed (kvm); -} -#ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE static inline void *mmu_memory_cache_alloc_obj (struct kvm_mmu_memory_cache *mc,gfp_t gfp_flags)
@@ -889,7 +883,8 @@ static void kvm_mmu_notifier_release(struct mmu_notifier *mn,int idx; idx =srcu_read_lock (&kvm->srcu); -kvm_flush_shadow_all (kvm); +kvm_arch_flush_shadow_all (kvm); +kvm_arch_guest_memory_reclaimed (kvm);srcu_read_unlock (&kvm->srcu, idx); }
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 11/17 KVM: WARN if there are in-flight memslot updates when a VM's process exits
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Move the sanity check on there being no outstanding memslot updates from VM destruction to kvm_mmu_notifier_release(), i.e. WARN if there are outstanding memslot updates when the VM is dying *or* the owning process is exiting. KVM subtly already guarantees (and relies on!) memslot updates to be mutually exclusive with the mm dying.
If KVM unregistered its mmu_notifier between .invalidate_range_start() and .invalidate_range_end(), then the invalidate count would be left elevated until the VM is destroyed, but if there were an outstanding memslot update, it would be impossible for the VM to be destroyed.
Opportunistically change the WARNs to WARN_ON_ONCE() so that a KVM bug doesn't unintentionally DoS the host due to spamming dmesg (hanging a task is bad enough).
--- virt/kvm/kvm_main.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
virt/kvm/kvm_main.c +8 -1
@@ -882,6 +882,14 @@ static void kvm_mmu_notifier_release(struct mmu_notifier *mn,struct kvm *kvm =mmu_notifier_to_kvm (mn);int idx; +/* +* No threads can be waiting in kvm_swap_active_memslots() as KVM only +* allows KVM_SET_USER_MEMORY_REGION{,2} in process context, and only +* from the process that created the VM, i.e. to @mm. If @mm is dying, +* then there can't possibly be outstanding memslot updates. +*/ +WARN_ON_ONCE (rcuwait_active (&kvm->mn_memslots_update_rcuwait)); + idx =srcu_read_lock (&kvm->srcu);kvm_arch_flush_shadow_all (kvm);kvm_arch_guest_memory_reclaimed (kvm);
@@ -1299,7 +1307,6 @@ static void kvm_destroy_vm(struct kvm *kvm)* notifier between a start() and end(), then there shouldn't be any * in-progress invalidations. */ -WARN_ON (rcuwait_active (&kvm->mn_memslots_update_rcuwait));if (kvm->mn_active_invalidate_count) kvm->mn_active_invalidate_count =0 ;else
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 12/17 KVM: Set mn_active_invalidate_count when the VM's mm is released
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Set mn_active_invalidate_count permanently (until the VM is destroyed) when the VM's mmu_notifier release() hook is called, i.e. when the VM and/or its process is dying. This will allow using gfn_to_pfn_cache_invalidate_start() more or less verbatim to invalidate all GPCs on .release(), without having to play games with the sequence count. As pointed out by Sashiko, a racing hva_to_pfn_retry() could set its GPC valid after re-acquiring gpc->lock if it's not forced to retry.
Isolate the mn_active_invalidate_count change on the off chance it causes problems. Elevating mn_active_invalidate_count should be a-ok because it's already possible for kvm_mmu_notifier_release() to run while the count is elevated *and* cause it to remain elevated, as .release() can be called between .invalidate_range_start() and .invalidate_range_end(). If that happens, the matching end() will never occur, but kvm_destroy_vm() will squash the count before freeing memslots. Note, there can't be any in-flight memslot updates when .release() runs, as KVM only does memslot updates from process context (except for the kvm_destroy_vm() case).
Adjust the sanity check on in-progress invalidations to account for an invalidate count of '1' now being the effective baseline when the VM is being destroyed.
Opportunistically tweak the comment to call out that unregistering the MMU notifier between start() and end() doesn't *guarantee* KVM should observe an in-progress invalidation, because KVM tracks those invalidations if and only if there is a relevant memslot.
Opportunistically add a TODO to call out that KVM can stop squashing the invalidate count once x86 stops abusing internal memslot updates to unmap VMAs for KVM-internal memslots[*].
--- virt/kvm/kvm_main.c | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-)
virt/kvm/kvm_main.c +28 -14
@@ -890,6 +890,16 @@ static void kvm_mmu_notifier_release(struct mmu_notifier *mn,*/ WARN_ON_ONCE (rcuwait_active (&kvm->mn_memslots_update_rcuwait)); +/* +* Elevate the invalidate count to prevent concurrent walks of the user +* page tables from fully succeeding if they race with teardown of the +* page tables. The elevated count will force lookups to always retry, +* until eventually the lookup fails outright after teardown completes. +*/ +spin_lock (&kvm->mn_invalidate_lock); + kvm->mn_active_invalidate_count++; +spin_unlock (&kvm->mn_invalidate_lock); + idx =srcu_read_lock (&kvm->srcu);kvm_arch_flush_shadow_all (kvm);kvm_arch_guest_memory_reclaimed (kvm);
@@ -1295,22 +1305,26 @@ static void kvm_destroy_vm(struct kvm *kvm) }kvm_coalesced_mmio_free (kvm);mmu_notifier_unregister (&kvm->mmu_notifier, kvm->mm); +/* -* At this point, pending calls to invalidate_range_start() -* have completed but no more MMU notifiers will run, so -* mn_active_invalidate_count may remain unbalanced. -* No threads can be waiting in kvm_swap_active_memslots() as the -* last reference on KVM has been dropped, but freeing -* memslots would deadlock without this manual intervention. -* -* If the count isn't unbalanced, i.e. KVM did NOT unregister its MMU -* notifier between a start() and end(), then there shouldn't be any -* in-progress invalidations. +* Sanity check KVM's tracking and internal use of start()+end(), e.g. +* to detect a unpaired start() or end(). KVM increments the count in +* kvm_mmu_notifier_release(), so the count must be at least 1; and +* if kvm->mmu_invalidate_in_progress is set, then KVM unregistered +* its MMU notifier between kvm_mmu_invalidate_range_start() and +* kvm_mmu_invalidate_range_end(), so kvm->mn_active_invalidate_count must +* have been elevated further by kvm_mmu_notifier_invalidate_range_start(). */ -if (kvm->mn_active_invalidate_count) - kvm->mn_active_invalidate_count =0 ; -else -WARN_ON (kvm->mmu_invalidate_in_progress); +WARN_ON_ONCE (kvm->mn_active_invalidate_count <1 + !!kvm->mmu_invalidate_in_progress); + +/* +* Squash the invalidate count so that arch code can update memslots +* as part of VM destruction. +* +* TODO: Drop this once KVM x86 no longer relies on setting internal +* memslots to munmap() the corresponding VMAs. +*/ + kvm->mn_active_invalidate_count =0 ;kvm_arch_destroy_vm (kvm);kvm_destroy_devices (kvm);for (i =0 ; i <kvm_arch_nr_memslot_as_ids (kvm); i++) {
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 13/17 KVM: Invalidate all GFN=>PFN caches when VM and/or its process is dying
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Invalidate all GPCs in kvm_flush_shadow_all(), i.e. when a VM or its owning process is dying, to ensure a GPC can't be used after the associated mm has exited, e.g. via a timer callback. Take care to invalidate the caches before notifying arch code that memory has been reclaimed, as all in-flight accesses must complete before KVM SEV performs cache maintenance on the affected memory.
BUG: KASAN: use-after-free in kvm_xen_set_evtchn_fast+0x3fe/0xfd0 [kvm] Write of size 8 at addr ffff88852702c800 by task swapper/4/0 CPU: 4 UID: 0 PID: 0 Comm: swapper/4 Not tainted 7.3.0-rc3-master-g587858367581-dirty-kasan #1 PREEMPT(lazy) Hardware name: LENOVO 21HMCTO1WW/21HMCTO1WW, BIOS N3XET48W (1.23 ) 11/01/2023 Call Trace: <IRQ> dump_stack_lvl+0x91/0xf0 print_report+0xd1/0x630 kasan_report+0xf3/0x130 kasan_check_range+0x11c/0x200 __kasan_check_write+0x14/0x30 kvm_xen_set_evtchn_fast+0x3fe/0xfd0 [kvm] xen_timer_callback+0x1eb/0x2b0 [kvm] __hrtimer_run_queues+0x43e/0x8b0 hrtimer_interrupt+0x3aa/0xa00 __sysvec_apic_timer_interrupt+0xc1/0x3a0 sysvec_apic_timer_interrupt+0x8d/0xd0 </IRQ> <TASK> asm_sysvec_apic_timer_interrupt+0x1b/0x20 The buggy address belongs to the physical page: page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x7965608db pfn:0x52702c flags: 0x17ffffc0000000(node=0|zone=2|lastcpupid=0x1fffff) raw: 0017ffffc0000000 ffffea0014864108 ffffea001c118e48 0000000000000000 raw: 00000007965608db 0000000000000000 00000000ffffffff 0000000000000000 page dumped because: kasan: bad access detected
Alternatively, invalidate_all() could reuse invalidate_start(), but that'd require tweaking invalidate_start() to special case "all", as simply in 0=>ULONG_MAX is subtly misleading/wrong. Because invalidate_start() takes an exclusive @end, using ULONG_MAX wouldn't strictly guarantee that all GPCs are invalidated. That's somewhat of a moot point since GPCs only ever deal with user addresses and CONFIG_HAVE_KVM_PFNCACHE is only selected by x86, which guarantees ULONG_MAX is a kernel address. But getting the logic "right" the first time is easy enough.
Reusing invalidate_start() would also be suboptimal, as it requires taking the per-GPC lock twice. That's extremely unlikely to matter in practice, but again, open coding invalidate_all() isn't complex, and avoids making invalidate_start() itself (slightly) more complex.
--- virt/kvm/kvm_main.c | 1 + virt/kvm/kvm_mm.h | 2 ++ virt/kvm/pfncache.c | 12 ++++++++++++ 3 files changed, 15 insertions(+)
virt/kvm/kvm_main.c +1 -0
@@ -902,6 +902,7 @@ static void kvm_mmu_notifier_release(struct mmu_notifier *mn, idx =srcu_read_lock (&kvm->srcu);kvm_arch_flush_shadow_all (kvm); +gfn_to_pfn_cache_invalidate_all (kvm);kvm_arch_guest_memory_reclaimed (kvm);srcu_read_unlock (&kvm->srcu, idx); }
virt/kvm/kvm_mm.h +2 -0
@@ -62,12 +62,14 @@ kvm_pfn_t hva_to_pfn(struct kvm_follow_pfn *kfp);void gfn_to_pfn_cache_invalidate_start (struct kvm *kvm,unsigned long start,unsigned long end); +void gfn_to_pfn_cache_invalidate_all (struct kvm *kvm);#else static inline void gfn_to_pfn_cache_invalidate_start (struct kvm *kvm,unsigned long start,unsigned long end) { } +static inline void gfn_to_pfn_cache_invalidate_all (struct kvm *kvm) { }#endif /* HAVE_KVM_PFNCACHE */ #endif /* __KVM_MM_H__ */
virt/kvm/pfncache.c +12 -0
@@ -19,6 +19,18 @@#include "kvm_mm.h" +void gfn_to_pfn_cache_invalidate_all (struct kvm *kvm) +{ +struct gfn_to_pfn_cache *gpc; + +guard (spinlock)(&kvm->gpc_lock); + +list_for_each_entry (gpc, &kvm->gpc_list, list) { +guard (write_lock_irq)(&gpc->lock); + gpc->valid = false; + } +} +/* * MMU notifier 'invalidate_range_start' hook. */
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 13/17] KVM: Invalidate all GFN=>PFN caches when VM and/or its process is dying
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] KVM: commit message refers to removed kvm_flush_shadow_all() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] KVM: commit message refers to removed kvm_flush_shadow_all() --
commit 65fcfccc757ce92283ecf557f6135d45190e157f
Author: Sean Christopherson <[email protected]>
KVM: Invalidate all GFN=>PFN caches when VM and/or its process is dying
This commit adds gfn_to_pfn_cache_invalidate_all() and calls it from kvm_mmu_notifier_release() so all GFN=>PFN caches are invalidated when a VM or its owning process is dying.
Quoted 3 lines
Invalidate all GPCs in
kvm_flush_shadow_all(), i.e. when a VM or its owning process is dying, to ensure a GPC can't be used after the associated mm has exited, e.g. via a timer callback.
[Severity: Low]
Should this refer to kvm_mmu_notifier_release() instead of kvm_flush_shadow_all()? Earlier in this series, commit "KVM: Fold kvm_flush_shadow_all() into kvm_mmu_notifier_release()" removed kvm_flush_shadow_all(), and this patch adds the gfn_to_pfn_cache_invalidate_all() call to kvm_mmu_notifier_release().
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
Paolo Bonzini
maintainerPATCH 14/17 x86/fpu: Bail early from guest XFD update if XFD isn't supported
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
As is, KVM allows userspace to set guest XFD to 0 even if XFD isn't supported; KVM unarguably shouldn't try to update guest XFD when the kernel doesn't support XFD/XSAVE, but fixing that flaw could potentially impact KVM's uABI. Thus, ignore KVM-requested guest XFD updates if the kernel doesn't support XFD.
The current code is subtly fine and does not corrupt guest_fpu->fpstate by interpreting it as an xstate structure; xsave.header.xfeatures is modified if and only if xfd != 0, which KVM does reject. Still, it's more defensive to return early and WARN if XFD is not set to 0.
--- arch/x86/kernel/fpu/core.c | 5 +++++ 1 file changed, 5 insertions(+)
arch/x86/kernel/fpu/core.c +5 -0
@@ -334,6 +334,11 @@ void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd) {struct fpstate *fpstate = guest_fpu->fpstate; +if (!cpu_feature_enabled (X86_FEATURE_XFD )) { +WARN_ON_ONCE (xfd); +return ; + } +fpregs_lock ();/*
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 15/17 x86/fpu: Clear XSTATE_BV[i] in guest XSAVE state if guest FPU isn't in-use
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
When updating a guest FPU's XFD, manually clear affected XSTATE_BV[i] state if the FPU isn't in-use, otherwise a subsequent load of the guest's FPU may trigger an #NM due to XSTATE_BV[i] being stale with respect to the XFD value loaded in hardware.
Oops: unexpected #NM exception: 0000 [#1] SMP CPU: 63 UID: 1000 PID: 1139 Comm: guest_xfd_nm Tainted: G W Tainted: [W]=WARN Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 0.0.0 02/06/2015 RIP: 0010:restore_fpregs_from_fpstate+0x36/0xa0 Call Trace: <TASK> fpu_swap_kvm_fpstate+0x64/0x130 kvm_arch_vcpu_ioctl_run+0x334/0x21e0 [kvm] kvm_vcpu_ioctl+0x2c7/0x960 [kvm] __x64_sys_ioctl+0x90/0xd0 do_syscall_64+0x9c/0x4d0 entry_SYSCALL_64_after_hwframe+0x4b/0x53 </TASK>
Arguably, failure to ensure the FPU is loaded is a KVM bug, but addressing that issue is non-trivial due to quirks in KVM's uABI. KVM saves/restores INIT and SIPI events via MP_STATE (where valid states are RUNNING, HALTED, SHUTDOWN, WFS, etc.) instead of saving/restoring the raw INIT/SIPI events. To avoid losing pending INIT/SIPI events, KVM processes pending INIT/SIPIs when userspace is getting MP_STATE, i.e. outside of the KVM_RUN flow and thus outside of kvm_arch_vcpu_ioctl_run()'s kvm_{load,put}_guest_fpu() pair.
Combined with KVM's emulation of VMX's VM-Exit MSR load/store lists (when the vCPU is running nested), KVM will inadvertently trigger an emulated XFD write when emulating an INIT VM-Exit outside of KVM_RUN:
kvm_arch_vcpu_ioctl_get_mpstate()
-> kvm_apic_accept_events()
-> vmx_check_nested_events()
-> nested_vmx_vmexit(vcpu, EXIT_REASON_INIT_SIGNAL, 0, 0)
-> load_vmcs12_host_state()
-> nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr, vmcs12->vm_exit_msr_load_count)
-> kvm_set_msr(vcpu, MSR_IA32_XFD, 0x40000)
-> kvm_set_msr_common()
-> fpu_update_guest_xfd(&vcpu->arch.guest_fpu, 0x40000)Unconditionally doing kvm_{load,put}_guest_fpu() around INIT emulation when handling KVM_GET_MP_STATE would fix this specific variant, but the nVMX MSR load/store lists are problematic in general and can be reached by even more subtle methods outside of KVM_RUN. E.g. if userspace disables VMX entirely by stuffing MSR_IA32_FEAT_CTL via KVM_SET_MSRS or KVM_SET_ONE_REG while L2 is active, then KVM will force the vCPU out of L2 via a (non-architectural) nested VM-Exit. For now, fix the immediate, urgent issue, and temporarily defer a more complete fix for the KVM mess.
Deliberately handle the !in_use case separately in anticipation of fixing another, similar bug for the in_use=true case. If the guest FPU isn't in use, i.e. isn't associated with the current task (or *any* task), then locking the FPU regs and checking TIF_NEED_FPU_LOAD is meaningless and unnecessary, and trying to juggle TIF_NEED_FPU_LOAD vs. in_use in the same flow makes the entire mess inscrutable.
Similarly, duplicate the fpstate->xfd update as well (although this one is unfortunately more likely to be permanent). If the FPU is in-use, then XFD needs to be updated *after* locking the FPU, otherwise trying to load FPU state saved with the old XFD using new XFD will #NM if the old state contains valid data for any newly-disabled features.
--- arch/x86/kernel/fpu/core.c | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
arch/x86/kernel/fpu/core.c +17 -6
@@ -339,13 +339,24 @@ void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd)return ; } -fpregs_lock (); -/* * KVM's guest ABI is that setting XFD[i]=1 *can* immediately revert the * save state to its initial configuration. Likewise, KVM_GET_XSAVE does * the same as XSAVE and returns XSTATE_BV[i]=0 whenever XFD[i]=1. * +* If the guest's FPU state isn't in-use, i.e. if the host FPU state is +* active, then the guest FPU isn't associated with the current task and +* *can't* be resident in hardware. Update the in-memory guest fpstate +* and clear all disabled components to prevent an #NM on XRSTOR if/when +* the guest FPU is next loaded into hardware. +*/ +if (!fpstate->in_use) { + fpstate->xfd = xfd; + fpstate->regs.xsave.header.xfeatures &= ~xfd; +return ; + } + +/* * If the guest's FPU state is in hardware, just update XFD: the XSAVE * in fpu_swap_kvm_fpstate will clear XSTATE_BV[i] whenever XFD[i]=1. *
@@ -353,13 +364,13 @@ void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd)* disabled components in XSTATE_BV now, or a subsequent XRSTOR will * attempt to load disabled components and generate #NM _in the host_. */ +fpregs_lock (); + fpstate->xfd = xfd; +if (xfd &&test_thread_flag (TIF_NEED_FPU_LOAD )) fpstate->regs.xsave.header.xfeatures &= ~xfd; - fpstate->xfd = xfd; -if (fpstate->in_use) -xfd_update_state (fpstate); - +xfd_update_state (fpstate);fpregs_unlock (); }EXPORT_SYMBOL_FOR_KVM (fpu_update_guest_xfd);
Signature · 1 line
2.56.1
Paolo Bonzini
maintainerPATCH 16/17 x86/fpu: Ensure guest FPU is resident in hardware when updating actual XFD MSR
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
When updating a guest FPU's XFD, ensure the guest FPU state is resident in hardware. Failure to do so means updating XFD may effectively clobber XFD, and in the worst case scenario can lead to an #NM due to failing to update XFD. Specifically, if the guest FPU is in-use (associated with the current task) and the current task has TIF_NEED_FPU_LOAD, then lock and load the task's FPU regs.
The underlying issue is that TIF_NEED_FPU_LOAD doesn't actually mean the FPU isn't resident in hardware, it only says the FPU *might* not be resident in hardware and *may* need a reload. E.g. if the current task was tagged with TIF_NEED_FPU_LOAD by switch_fpu(), but never evicted from hardware, then KVM's call to switch_fpu_return() will elide the xfd_update_state() call (and the XRSTOR) due to the FPU being valid, and run the vCPU with a stale XFD.
E.g. on a single pCPU 'A', timeshared by two vCPUs:
vcpu0 / fpu0 vcpu1 / fpu1
TIF_NEED_FPU_LOAD = 1 <schedules out>
dirty TMM0 (XINUSE[18] == 1)
wrmsr(MSR_IA32_XFD, 0x40000) fpu_sync_guest_vmexit_xfd_state()
<schedules out>
TIF_NEED_FPU_LOAD = 1 (switch_fpu()) fpu_fpregs_owner_ctx = fpu0
fpu0->last_cpu = A
<schedules in>
fpu_update_guest_xfd(fpu1, 0)
wrmsrq(MSR_IA32_XFD, 0) fpregs_state_valid() == true
|
-> switch_fpu_return() skips
restore_fpregs_from_fpstate() and
xfd_update_state()
fpu_swap_kvm_fpstate() (exit to user)
|
-> fpu0->regs.xsave.header.xfeatures
is saved with XSTATE_BV[18] = 1
fpu_swap_kvm_fpstate() (entry from user)
|
-> restore_fpregs_from_fpstate() => #NM
Alternatively, fpu_update_guest_xfd() could skip xfd_update_state() *and* force an invalidation of the current FPU (set last_cpu = -1) to ensure the correct XFD is loaded when doing switch_fpu_return(). However, that gets all kinds of convoluted, and emulating an XFD write with TIF_NEED_FPU_LOAD=1 is very uncommon, and in all likelihood the guest FPU is going to be loaded into hardware in the near future anyways, i.e. avoiding (maybe) loading the guest FPU buys nothing but complexity.
--- arch/x86/kernel/fpu/core.c | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-)
arch/x86/kernel/fpu/core.c +10 -11
@@ -357,19 +357,18 @@ void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd) }/* -* If the guest's FPU state is in hardware, just update XFD: the XSAVE -* in fpu_swap_kvm_fpstate will clear XSTATE_BV[i] whenever XFD[i]=1. -* -* If however the guest's FPU state is NOT resident in hardware, clear -* disabled components in XSTATE_BV now, or a subsequent XRSTOR will -* attempt to load disabled components and generate #NM _in the host_. +* If the guest's FPU state is in-use, then ensure the state is resident +* in hardware and simply update XFD. The guest is responsible for +* clearing disabled components when doing its own XRSTOR operations, +* and the XSAVE in fpu_swap_kvm_fpstate() when putting the guest FPU +* will clear XSTATE_BV[i] whenever XFD[i]=1. +*/ +fpregs_lock_and_load (); +/* +* Update XFD *after* loading FPU state, otherwise XRSTOR would try to +* load XSTATE saved with the old XFD, but using the new XFD. */ -fpregs_lock (); fpstate->xfd = xfd; - -if (xfd &&test_thread_flag (TIF_NEED_FPU_LOAD )) - fpstate->regs.xsave.header.xfeatures &= ~xfd; -xfd_update_state (fpstate);fpregs_unlock (); }
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 16/17] x86/fpu: Ensure guest FPU is resident in hardware when updating actual XFD MSR
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] x86/fpu: Fixes trailer cites wrong commit for fpu_update_guest_xfd() bug --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] x86/fpu: Fixes trailer cites wrong commit for fpu_update_guest_xfd() bug
--
commit 8e958ac03ba6613579a0c2ac427b8e549024a0e8
Author: Sean Christopherson <[email protected]>
Quoted 55 lines
x86/fpu: Ensure guest FPU is resident in hardware when updating actual XFD MSR
When updating a guest FPU's XFD, ensure the guest FPU state is resident in hardware. Failure to do so means updating XFD may effectively clobber XFD, and in the worst case scenario can lead to an #NM due to failing to update XFD. Specifically, if the guest FPU is in-use (associated with the current task) and the current task has
TIF_NEED_FPU_LOAD, then lock and load the task's FPU regs.The underlying issue is that
TIF_NEED_FPU_LOADdoesn't actually mean the FPU isn't resident in hardware, it only says the FPU *might* not be resident in hardware and *may* need a reload. E.g. if the current task was tagged withTIF_NEED_FPU_LOADbyswitch_fpu(), but never evicted from hardware, then KVM's call toswitch_fpu_return()will elide thexfd_update_state()call (and the XRSTOR) due to the FPU being valid, and run the vCPU with a stale XFD.E.g. on a single pCPU 'A', timeshared by two vCPUs:
vcpu0 / fpu0 vcpu1 / fpu1
TIF_NEED_FPU_LOAD= 1 <schedules out>
dirty TMM0 (XINUSE[18] == 1)
wrmsr(MSR_IA32_XFD, 0x40000)fpu_sync_guest_vmexit_xfd_state()
<schedules out>
TIF_NEED_FPU_LOAD= 1 (switch_fpu())fpu_fpregs_owner_ctx= fpu0
fpu0->last_cpu= A<schedules in> fpu_update_guest_xfd(fpu1, 0) wrmsrq(MSR_IA32_XFD, 0)
fpregs_state_valid()== true
|
->switch_fpu_return()skips
restore_fpregs_from_fpstate()and
xfd_update_state()
fpu_swap_kvm_fpstate()(exit to user)
|
->fpu0->regs.xsave.header.xfeatures
is saved with XSTATE_BV[18] = 1
fpu_swap_kvm_fpstate()(entry from user)
|
->restore_fpregs_from_fpstate()=> #NMAlternatively,
fpu_update_guest_xfd()could skipxfd_update_state()*and* force an invalidation of the current FPU (setlast_cpu= -1) to ensure the correct XFD is loaded when doingswitch_fpu_return(). However, that gets all kinds of convoluted, and emulating an XFD write with TIF_NEED_FPU_LOAD=1 is very uncommon, and in all likelihood the guest FPU is going to be loaded into hardware in the near future anyways, i.e. avoiding (maybe) loading the guest FPU buys nothing but complexity.
Quoted 14 lines
Fixes b45f72177594 ("x86/fpu: Clear XSTATE_BV[i] in guest XSAVE state whenever XFD[i]=1")Reported-by Stefan Teodorescu <[email protected]>Suggested-by Stefan Teodorescu <[email protected]>Reported-by Chris Mason <[email protected]>Suggested-by Chris Mason <[email protected]>Cc Josef Bacik <[email protected]>Cc Paolo Bonzini <[email protected]>Cc David Woodhouse <[email protected]>Cc Jim Mattson <[email protected]>Acked-by Dave Hansen <[email protected]>Signed-off-by Sean Christopherson <[email protected]>Signed-off-by Paolo Bonzini <[email protected]>
[Severity: Low]
Should the Fixes tag cite 8eb9a48ac1e8 ("x86/fpu: Provide fpu_update_guest_xfd() for IA32_XFD emulation") instead of b45f72177594 ("x86/fpu: Clear XSTATE_BV[i] in guest XSAVE state whenever XFD[i]=1")?
The cited commit only added XSTATE_BV clearing when xfd is non-zero and TIF_NEED_FPU_LOAD is set, which is not reached in the xfd == 0 scenario above.
Calling xfd_update_state() without first loading the guest FPU into hardware dates back to the earlier commit, so citing the later one leaves older stable trees out of backport tracking.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
Paolo Bonzini
maintainerPATCH 17/17 KVM: VMX: Ensure pCPU is valid before sending IPI to deliver posted IRQ
In reply to Paolo BonziniFrom: Sean Christopherson <[email protected]>
Verify the target pCPU is valid before sending an IPI to trigger CPU=>CPU posted IRQ processing, as TDX invalidates vcpu->cpu when disassociating a pCPU from a vCPU. Ensure the relevant reads and writes are performed once, to prevent vcpu->cpu from being re-read after it's been validated.
If a TDX vCPU's task is migrated immediately after a VM-Exit, and the CPU sending the IPI is sufficiently delayed, KVM will attempt to send an IPI to pCPU '-1', generate an out-of-bounds read, and ultimately crash.
BUG: unable to handle page fault for address: ffffffff88021be8 #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page PGD 10a0815067 P4D 10a0815067 PUD 0 Oops: 0000 [#1] SMP NOPTI CPU: 0 PID: 173535 Comm: repro Tainted: G O 6.6.103-smp-1301.106.448.13 #1 Hardware name: Google Izumi/Izumi, BIOS 0.20260728.0-16 07/28/2026 RIP: 0010:memcpy+0xc/0x20 Call Trace: <TASK> ? __x2apic_send_IPI_mask+0x71/0x160 tdx_deliver_interrupt+0x75/0xe0 [kvm_intel] __apic_accept_irq+0xdf/0x240 [kvm] kvm_irq_delivery_to_apic+0x1df/0x2e0 [kvm] kvm_apic_send_ipi+0xa3/0x100 [kvm] kvm_x2apic_icr_write+0x47/0xc0 [kvm] __kvm_set_msr+0xa0/0x1c0 [kvm] kvm_set_msr_ignored_check+0x18/0xf0 [kvm] kvm_emulate_wrmsr+0x74/0x180 [kvm] tdx_handle_exit+0x238/0x13a0 [kvm_intel]
Note, using the "mask" variant to send the IPI is stupid and inefficient, and actively contributed to making the bug worse. Because TDX requires x2APIC, if KVM had used the more obvious send_IPI(), then attempting to send an IPI to '-1' would have morphed into a broadcast the IRQ to all CPUs instead of an out-of-bounds read. That wart will be fixed shortly.
Note #2, the flaw has existed since commit 705699a13994 ("KVM: nVMX: Enable nested posted interrupt processing"), but was unreachable until TDX came along and invalidated the CPU of a live vCPU.
Note #3, __kvm_vcpu_kick() and kvm_make_vcpu_request() already guard against an invalid pCPU.
Note #4, tdx_vcpu_free() checks vcpu->cpu without using READ_ONCE(), but that's a-ok since the vCPU is unreachable, i.e. vcpu->cpu can't change.
Note #5, invalidating vcpu->cpu probably means TDX is triggering a VM-wide blast of IPIs to do KVM_REQ_GLOBAL_CLOCK_UPDATE => KVM_REQ_CLOCK_UPDATE, because kvm_arch_vcpu_load() thinks the vCPU has never been loaded on any CPU. That too will be fixed in the near future.
Note #6, related to note #5, invoking kvm_x86_call(vcpu_load)(vcpu, cpu) in the middle of kvm_arch_vcpu_load() changes vcpu->cpu to -1 for TDX vCPUs, i.e. fixing that would fix #5 as well (although it's simpler to just make the request during vCPU creation).
Note #7, the only reason reading vcpu->cpu multiple times when loading a vCPU isn't completely broken is because loading a vCPU is mutually exclusive with disassociating a vCPU from a pCPU, outside of the aforementioned self-induced pain with .vcpu_load(), thanks to commit 15945e9ec195 ("KVM: TDX: Guard VM state transitions with "all" the locks").
--- arch/x86/kvm/vmx/common.h | 5 +++-- arch/x86/kvm/vmx/tdx.c | 4 ++-- arch/x86/kvm/x86.c | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-)
arch/x86/kvm/vmx/common.h +3 -2
@@ -199,9 +199,10 @@ static inline void kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,* not wait for any requested interrupts in PIR, and sending a * notification event also results in a benign, spurious event. */ +int cpu =READ_ONCE (vcpu->cpu); -if (vcpu !=kvm_get_running_vcpu ()) -__apic_send_IPI_mask (get_cpu_mask (vcpu->cpu), pi_vec); +if (cpu >=0 && vcpu !=kvm_get_running_vcpu ()) +__apic_send_IPI_mask (get_cpu_mask (cpu), pi_vec); return; }#endif
arch/x86/kvm/vmx/tdx.c +2 -2
@@ -284,7 +284,7 @@ static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)*/ smp_wmb (); - vcpu->cpu =-1 ; +WRITE_ONCE (vcpu->cpu,-1 ); }/*
@@ -412,7 +412,7 @@ static void tdx_flush_vp_on_cpu(struct kvm_vcpu *vcpu)struct tdx_flush_vp_arg arg = { .vcpu = vcpu, }; -int cpu = vcpu->cpu; +int cpu =READ_ONCE (vcpu->cpu);if (unlikely (cpu ==-1 ))return ;
arch/x86/kvm/x86.c +1 -1
@@ -2617,7 +2617,7 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)if (vcpu->cpu != cpu)kvm_make_request (KVM_REQ_MIGRATE_TIMER , vcpu); - vcpu->cpu = cpu; +WRITE_ONCE (vcpu->cpu, cpu); }kvm_make_request (KVM_REQ_STEAL_UPDATE , vcpu);
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 17/17] KVM: VMX: Ensure pCPU is valid before sending IPI to deliver posted IRQ
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] KVM: VMX: inaccurate commit notes and missed READ_ONCE() on vcpu->cpu --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] KVM: VMX: inaccurate commit notes and missed READ_ONCE() on vcpu->cpu
--
commit d094dd6a1e80f9a875e1dd76aa9eecef276dd0aa
Author: Sean Christopherson <[email protected]>
KVM: VMX: Ensure pCPU is valid before sending IPI to deliver posted IRQ
This commit validates vcpu->cpu before sending a posted-interrupt IPI in kvm_vcpu_trigger_posted_interrupt() and adds READ_ONCE()/WRITE_ONCE() annotations to vcpu->cpu accesses in tdx.c and kvm_arch_vcpu_load().
Quoted 2 lines
Note #4,
tdx_vcpu_free()checksvcpu->cpuwithout usingREAD_ONCE(), but that's a-ok since the vCPU is unreachable, i.e.vcpu->cpucan't change.
[ ... ]
Quoted 5 lines
Note #7, the only reason reading
vcpu->cpumultiple times when loading a vCPU isn't completely broken is because loading a vCPU is mutually exclusive with disassociating a vCPU from a pCPU, outside of the aforementioned self-induced pain with .vcpu_load(), thanks to commit15945e9ec195("KVM: TDX: Guard VM state transitions with "all" the locks").
[Severity: Low]
Can CPU hot-unplug still disassociate a TDX vCPU concurrently with tdx_vcpu_load() and tdx_vcpu_free(), making Notes #4 and #7 inaccurate and leaving KCSAN data races on vcpu->cpu?
Commit 15945e9ec195 ("KVM: TDX: Guard VM state transitions with "all" the locks") serializes TD state-transition ioctls, not CPU offlining. During CPUHP_AP_KVM_ONLINE, tdx_disable_virtualization_cpu() -> tdx_disassociate_vp() writes WRITE_ONCE(vcpu->cpu, -1) without vcpu->mutex or kvm->lock.
Meanwhile, another CPU can run vcpu_load() -> kvm_arch_vcpu_load() -> tdx_vcpu_load() without cpus_read_lock() (as noted in tdx_flush_vp()) and read vcpu->cpu without READ_ONCE().
Similarly, on the KVM_CREATE_VCPU error path after kvm_arch_vcpu_create(), the vCPU is still linked on per-CPU associated_tdvcpus. CPU hot-unplug can reach it via tdx_disable_virtualization_cpu() while tdx_vcpu_free() checks vcpu->cpu != -1 without READ_ONCE().
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17