AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/15 02:31 flow patch-triage
2m Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hypercall",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_write_hypercall_page",
    "record_steal_time"
  ],
  "KMSANReasoning": "The patch series addresses synchronization, locking, and deadlock issues in KVM (specifically within the gfn_to_pfn_cache implementation, x86 steal time handling, and Xen emulation). It resolves an SRCU deadlock where guest exit handling could wait on a memslot update while holding kvm-\u003esrcu, replaces inline TLB flushes in steal time recording with deferred request handling (KVM_REQ_TLB_FLUSH_GUEST), and adds a 'wait' parameter to kvm_gpc_refresh/kvm_gpc_activate.\n\nKMSAN is designed to detect uninitialized memory reads and leaks to userspace. The patch does not introduce or alter any copy_to_user/ioctl data transfers to userspace, does not leave any struct fields or local variables uninitialized, and does not alter buffer length or bounds checking logic that could expose uninitialized memory. Any concurrency, deadlock, or memory lifetime issues introduced by these changes are addressed by LOCKDEP and standard KASAN, making a dedicated KMSAN fuzzing run unnecessary.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series addresses deadlock and synchronization issues between KVM guest physical page cache (gfn_to_pfn_cache/GPC) refreshes/activations and kvm-\u003esrcu read sections during memslot updates. It refactors GPC wait/retry behavior, introduces lockdep synchronization assertions (srcu_lock_sync), updates Xen event channel delivery paths and error handling (-EAGAIN vs -EFAULT), modifies steal time TLB flush request sequencing, and adjusts lock scopes in KVM Xen emulation. All changes affect reachable virtualization code that is actively fuzzed via KVM ioctls and guest hypercalls.",
  "WorthFuzzing": true
}

1/1 2026/10/15 02:31 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit b3aac2f9a3334b2c6c1ecb22b39cbea125204fd6\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Thu Oct 15 02:31:47 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst\nindex e0430cc750c9e..b24aac070b119 100644\n--- a/Documentation/virt/kvm/api.rst\n+++ b/Documentation/virt/kvm/api.rst\n@@ -385,8 +385,9 @@ The bits in the dirty bitmap are cleared before the ioctl returns, unless\n KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is enabled.  For more information,\n see the description of the capability.\n \n-Note that the Xen shared_info page, if configured, shall always be assumed\n-to be dirty. KVM will not explicitly mark it such.\n+Note that the Xen shared_info page and vcpu_info area, if configured,\n+shall always be assumed to be dirty. KVM will not explicitly mark them\n+such.\n \n \n 4.10 KVM_RUN\ndiff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h\nindex 3af7395c2430a..6bebc4a79a334 100644\n--- a/arch/x86/include/asm/kvm_host.h\n+++ b/arch/x86/include/asm/kvm_host.h\n@@ -1108,6 +1108,10 @@ struct kvm_hv {\n #ifdef CONFIG_KVM_XEN\n /* Xen emulation context */\n struct kvm_xen {\n+\t/*\n+\t * Never taken inside a kvm-\u003esrcu read section: holders may wait\n+\t * out memslot updates (synchronize_srcu).\n+\t */\n \tstruct mutex xen_lock;\n \tu32 xen_version;\n \tbool long_mode;\ndiff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c\nindex dd3bb04878ca6..4c0fbba6e7aef 100644\n--- a/arch/x86/kvm/msrs.c\n+++ b/arch/x86/kvm/msrs.c\n@@ -1280,7 +1280,7 @@ static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,\n \t/* we verify if the enable bit is set... */\n \tif (system_time \u0026 1)\n \t\tkvm_gpc_activate(\u0026vcpu-\u003earch.pv_time, system_time \u0026 ~1ULL,\n-\t\t\t\t sizeof(struct pvclock_vcpu_time_info));\n+\t\t\t\t sizeof(struct pvclock_vcpu_time_info), false);\n \telse\n \t\tkvm_gpc_deactivate(\u0026vcpu-\u003earch.pv_time);\n \ndiff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c\nindex 79468ddfe4736..20119d07b477b 100644\n--- a/arch/x86/kvm/x86.c\n+++ b/arch/x86/kvm/x86.c\n@@ -1727,7 +1727,7 @@ static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,\n \twhile (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {\n \t\tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n \n-\t\tif (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))\n+\t\tif (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock), false))\n \t\t\treturn;\n \n \t\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n@@ -2106,8 +2106,22 @@ static void record_steal_time(struct kvm_vcpu *vcpu)\n \n \t\ttrace_kvm_pv_tlb_flush(vcpu-\u003evcpu_id,\n \t\t\t\t       st_preempted \u0026 KVM_VCPU_FLUSH_TLB);\n+\t\t/*\n+\t\t * Request the flush instead of performing it inline. With\n+\t\t * shadow paging kvm_vcpu_flush_tlb_guest() can reschedule (via\n+\t\t * mmu_sync_children()), which is why the user access above has\n+\t\t * to be closed before it. Requesting the flush is just a bit\n+\t\t * set on the running vCPU, and the request is serviced before\n+\t\t * the vCPU enters the guest; nothing requires the flush to\n+\t\t * have completed any earlier than that.\n+\t\t *\n+\t\t * Note the xchg above must remain as-is: it atomically\n+\t\t * consumes any KVM_VCPU_FLUSH_TLB the guest set, as required\n+\t\t * by commit b043138246a4 (\"x86/KVM: Make sure\n+\t\t * KVM_VCPU_FLUSH_TLB flag is not missed\").\n+\t\t */\n \t\tif (st_preempted \u0026 KVM_VCPU_FLUSH_TLB)\n-\t\t\tkvm_vcpu_flush_tlb_guest(vcpu);\n+\t\t\tkvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);\n \n \t\tif (!user_access_begin(st, sizeof(*st)))\n \t\t\tgoto dirty;\n@@ -8089,6 +8103,14 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)\n \t\t\tif (unlikely(r))\n \t\t\t\tgoto out;\n \t\t}\n+\t\t/*\n+\t\t * Process the steal time update before the TLB flush requests\n+\t\t * are serviced below; record_steal_time() requests\n+\t\t * KVM_REQ_TLB_FLUSH_GUEST on the guest's behalf rather than\n+\t\t * performing the flush itself.\n+\t\t */\n+\t\tif (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))\n+\t\t\trecord_steal_time(vcpu);\n \t\tif (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))\n \t\t\tkvm_mmu_sync_roots(vcpu);\n \t\tif (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))\n@@ -8138,8 +8160,6 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)\n \t\t\tr = 1;\n \t\t\tgoto out;\n \t\t}\n-\t\tif (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))\n-\t\t\trecord_steal_time(vcpu);\n \t\tif (kvm_check_request(KVM_REQ_PMU, vcpu))\n \t\t\tkvm_pmu_handle_event(vcpu);\n \t\tif (kvm_check_request(KVM_REQ_PMI, vcpu))\ndiff --git a/arch/x86/kvm/xen.c b/arch/x86/kvm/xen.c\nindex 6aa00f746cba3..e72c0b3d21091 100644\n--- a/arch/x86/kvm/xen.c\n+++ b/arch/x86/kvm/xen.c\n@@ -30,13 +30,14 @@\n #include \"cpuid.h\"\n #include \"trace.h\"\n \n-static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm);\n+static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,\n+\t\t\t      bool wait);\n static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data);\n-static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);\n+static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);\n \n DEFINE_STATIC_KEY_DEFERRED_FALSE(kvm_xen_enabled, HZ);\n \n-static int kvm_xen_shared_info_init(struct kvm *kvm)\n+static int kvm_xen_shared_info_init(struct kvm *kvm, bool wait)\n {\n \tstruct gfn_to_pfn_cache *gpc = \u0026kvm-\u003earch.xen.shinfo_cache;\n \tstruct pvclock_wall_clock *wc;\n@@ -44,17 +45,24 @@ static int kvm_xen_shared_info_init(struct kvm *kvm)\n \tu32 wc_version;\n \tu64 wall_nsec;\n \tint ret = 0;\n-\tint idx = srcu_read_lock(\u0026kvm-\u003esrcu);\n+\tint idx;\n \n-\tread_lock_irq(\u0026gpc-\u003elock);\n-\twhile (!kvm_gpc_check(gpc, PAGE_SIZE)) {\n+\t/*\n+\t * kvm_gpc_check() consults the memslots, so take kvm-\u003esrcu around\n+\t * each check and the write through the mapping — but not across\n+\t * the refresh, which may wait for a memslot update to complete.\n+\t */\n+\tfor (;;) {\n+\t\tidx = srcu_read_lock(\u0026kvm-\u003esrcu);\n+\t\tread_lock_irq(\u0026gpc-\u003elock);\n+\t\tif (kvm_gpc_check(gpc, PAGE_SIZE))\n+\t\t\tbreak;\n \t\tread_unlock_irq(\u0026gpc-\u003elock);\n+\t\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n \n-\t\tret = kvm_gpc_refresh(gpc, PAGE_SIZE);\n+\t\tret = kvm_gpc_refresh(gpc, PAGE_SIZE, wait);\n \t\tif (ret)\n \t\t\tgoto out;\n-\n-\t\tread_lock_irq(\u0026gpc-\u003elock);\n \t}\n \n \t/*\n@@ -98,9 +106,9 @@ static int kvm_xen_shared_info_init(struct kvm *kvm)\n \n \twc-\u003eversion = wc_version + 1;\n \tread_unlock_irq(\u0026gpc-\u003elock);\n+\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n \n out:\n-\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n \treturn ret;\n }\n \n@@ -108,13 +116,35 @@ void kvm_xen_inject_timer_irqs(struct kvm_vcpu *vcpu)\n {\n \tif (atomic_read(\u0026vcpu-\u003earch.xen.timer_pending) \u003e 0) {\n \t\tstruct kvm_xen_evtchn e;\n+\t\tint rc;\n \n \t\te.vcpu_id = vcpu-\u003evcpu_id;\n \t\te.vcpu_idx = vcpu-\u003evcpu_idx;\n \t\te.port = vcpu-\u003earch.xen.timer_virq;\n \t\te.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;\n \n-\t\tkvm_xen_set_evtchn(\u0026e, vcpu-\u003ekvm);\n+\t\trc = kvm_xen_set_evtchn(\u0026e, vcpu-\u003ekvm, false);\n+\n+\t\t/*\n+\t\t * Leave timer_pending set if the memslot is being updated\n+\t\t * (-EAGAIN); delivery is retried on the next entry pass.\n+\t\t */\n+\t\tif (rc == -EAGAIN)\n+\t\t\treturn;\n+\n+\t\t/*\n+\t\t * If the event cannot currently be delivered (-EINVAL:\n+\t\t * deactivated shared_info, or an out-of-range port), clear\n+\t\t * timer_pending — a halted vCPU would otherwise spin on\n+\t\t * kvm_cpu_has_pending_timer() — but keep timer_expires,\n+\t\t * which still reports the event as owed through\n+\t\t * KVM_XEN_VCPU_GET_ATTR; re-arming the timer with an expiry\n+\t\t * in the past fires it again.\n+\t\t */\n+\t\tif (rc == -EINVAL) {\n+\t\t\tatomic_set(\u0026vcpu-\u003earch.xen.timer_pending, 0);\n+\t\t\treturn;\n+\t\t}\n \n \t\tvcpu-\u003earch.xen.timer_expires = 0;\n \t\tatomic_set(\u0026vcpu-\u003earch.xen.timer_pending, 0);\n@@ -161,7 +191,7 @@ static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,\n \twhile (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {\n \t\tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n \n-\t\tr = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock));\n+\t\tr = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock), false);\n \t\tif (r)\n \t\t\treturn r;\n \n@@ -435,7 +465,7 @@ static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)\n \t\tif (atomic)\n \t\t\treturn;\n \n-\t\tif (kvm_gpc_refresh(gpc1, user_len1))\n+\t\tif (kvm_gpc_refresh(gpc1, user_len1, false))\n \t\t\treturn;\n \n \t\tread_lock_irqsave(\u0026gpc1-\u003elock, flags);\n@@ -488,7 +518,7 @@ static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)\n \t\t\t * 64-bit mode, the second GPC won't have been set up.\n \t\t\t */\n \t\t\tif (kvm_gpc_activate(gpc2, gpc1-\u003egpa + user_len1,\n-\t\t\t\t\t     user_len2))\n+\t\t\t\t\t     user_len2, false))\n \t\t\t\treturn;\n \n \t\t\t/*\n@@ -669,7 +699,7 @@ void kvm_xen_inject_pending_events(struct kvm_vcpu *v)\n \twhile (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {\n \t\tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n \n-\t\tif (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info)))\n+\t\tif (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info), false))\n \t\t\treturn;\n \n \t\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n@@ -705,7 +735,6 @@ void kvm_xen_inject_pending_events(struct kvm_vcpu *v)\n \t\tWRITE_ONCE(vi-\u003eevtchn_upcall_pending, 1);\n \t}\n \n-\tkvm_gpc_mark_dirty_in_slot(gpc);\n \tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n \n \t/* For the per-vCPU lapic vector, deliver it as MSI. */\n@@ -757,7 +786,7 @@ int __kvm_xen_has_interrupt(struct kvm_vcpu *v)\n \t\tif (in_atomic() || !task_is_running(current))\n \t\t\treturn 1;\n \n-\t\tif (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info))) {\n+\t\tif (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info), false)) {\n \t\t\t/*\n \t\t\t * If this failed, userspace has screwed up the\n \t\t\t * vcpu_info mapping. No interrupts for you.\n@@ -792,19 +821,15 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)\n \t\t\t * to make the call anyway.\n \t\t\t */\n \t\t\tr = kvm-\u003earch.xen.shinfo_cache.active ?\n-\t\t\t\tkvm_xen_shared_info_init(kvm) : 0;\n+\t\t\t\tkvm_xen_shared_info_init(kvm, true) : 0;\n \t\t\tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\n \t\t}\n \t\tbreak;\n \n \tcase KVM_XEN_ATTR_TYPE_SHARED_INFO:\n \tcase KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA: {\n-\t\tint idx;\n-\n \t\tmutex_lock(\u0026kvm-\u003earch.xen.xen_lock);\n \n-\t\tidx = srcu_read_lock(\u0026kvm-\u003esrcu);\n-\n \t\tif (data-\u003etype == KVM_XEN_ATTR_TYPE_SHARED_INFO) {\n \t\t\tgfn_t gfn = data-\u003eu.shared_info.gfn;\n \n@@ -813,7 +838,7 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)\n \t\t\t\tr = 0;\n \t\t\t} else {\n \t\t\t\tr = kvm_gpc_activate(\u0026kvm-\u003earch.xen.shinfo_cache,\n-\t\t\t\t\t\t     gfn_to_gpa(gfn), PAGE_SIZE);\n+\t\t\t\t\t\t     gfn_to_gpa(gfn), PAGE_SIZE, true);\n \t\t\t}\n \t\t} else {\n \t\t\tvoid __user * hva = u64_to_user_ptr(data-\u003eu.shared_info.hva);\n@@ -829,10 +854,8 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)\n \t\t\t}\n \t\t}\n \n-\t\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n-\n \t\tif (!r \u0026\u0026 kvm-\u003earch.xen.shinfo_cache.active)\n-\t\t\tr = kvm_xen_shared_info_init(kvm);\n+\t\t\tr = kvm_xen_shared_info_init(kvm, true);\n \n \t\tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\n \t\tbreak;\n@@ -937,7 +960,6 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \tint idx, r = -ENOENT;\n \n \tmutex_lock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n-\tidx = srcu_read_lock(\u0026vcpu-\u003ekvm-\u003esrcu);\n \n \tswitch (data-\u003etype) {\n \tcase KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO:\n@@ -960,7 +982,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\t\t\tbreak;\n \n \t\t\tr = kvm_gpc_activate(\u0026vcpu-\u003earch.xen.vcpu_info_cache,\n-\t\t\t\t\t     data-\u003eu.gpa, sizeof(struct vcpu_info));\n+\t\t\t\t\t     data-\u003eu.gpa, sizeof(struct vcpu_info), true);\n \t\t} else {\n \t\t\tif (data-\u003eu.hva == 0) {\n \t\t\t\tkvm_gpc_deactivate(\u0026vcpu-\u003earch.xen.vcpu_info_cache);\n@@ -990,7 +1012,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \n \t\tr = kvm_gpc_activate(\u0026vcpu-\u003earch.xen.vcpu_time_info_cache,\n \t\t\t\t     data-\u003eu.gpa,\n-\t\t\t\t     sizeof(struct pvclock_vcpu_time_info));\n+\t\t\t\t     sizeof(struct pvclock_vcpu_time_info), true);\n \t\tif (!r)\n \t\t\tkvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);\n \t\tbreak;\n@@ -1023,7 +1045,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\t/* How much fits in the (first) page? */\n \t\tsz1 = PAGE_SIZE - (data-\u003eu.gpa \u0026 ~PAGE_MASK);\n \t\tr = kvm_gpc_activate(\u0026vcpu-\u003earch.xen.runstate_cache,\n-\t\t\t\t     data-\u003eu.gpa, sz1);\n+\t\t\t\t     data-\u003eu.gpa, sz1, true);\n \t\tif (r)\n \t\t\tgoto deactivate_out;\n \n@@ -1034,12 +1056,14 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\t\tsz2 = sz - sz1;\n \t\t\tBUG_ON((data-\u003eu.gpa + sz1) \u0026 ~PAGE_MASK);\n \t\t\tr = kvm_gpc_activate(\u0026vcpu-\u003earch.xen.runstate2_cache,\n-\t\t\t\t\t     data-\u003eu.gpa + sz1, sz2);\n+\t\t\t\t\t     data-\u003eu.gpa + sz1, sz2, true);\n \t\t\tif (r)\n \t\t\t\tgoto deactivate_out;\n \t\t}\n \n+\t\tidx = srcu_read_lock(\u0026vcpu-\u003ekvm-\u003esrcu);\n \t\tkvm_xen_update_runstate_guest(vcpu, false);\n+\t\tsrcu_read_unlock(\u0026vcpu-\u003ekvm-\u003esrcu, idx);\n \t\tbreak;\n \t}\n \tcase KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT:\n@@ -1052,7 +1076,9 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\t\tbreak;\n \t\t}\n \n+\t\tidx = srcu_read_lock(\u0026vcpu-\u003ekvm-\u003esrcu);\n \t\tkvm_xen_update_runstate(vcpu, data-\u003eu.runstate.state);\n+\t\tsrcu_read_unlock(\u0026vcpu-\u003ekvm-\u003esrcu, idx);\n \t\tr = 0;\n \t\tbreak;\n \n@@ -1132,10 +1158,12 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\tvcpu-\u003earch.xen.runstate_times[RUNSTATE_offline] +=\n \t\t\tdata-\u003eu.runstate.time_offline;\n \n+\t\tidx = srcu_read_lock(\u0026vcpu-\u003ekvm-\u003esrcu);\n \t\tif (data-\u003eu.runstate.state \u003c= RUNSTATE_offline)\n \t\t\tkvm_xen_update_runstate(vcpu, data-\u003eu.runstate.state);\n \t\telse if (vcpu-\u003earch.xen.runstate_cache.active)\n \t\t\tkvm_xen_update_runstate_guest(vcpu, false);\n+\t\tsrcu_read_unlock(\u0026vcpu-\u003ekvm-\u003esrcu, idx);\n \t\tr = 0;\n \t\tbreak;\n \n@@ -1181,7 +1209,6 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\tbreak;\n \t}\n \n-\tsrcu_read_unlock(\u0026vcpu-\u003ekvm-\u003esrcu, idx);\n \tmutex_unlock(\u0026vcpu-\u003ekvm-\u003earch.xen.xen_lock);\n \treturn r;\n }\n@@ -1267,12 +1294,13 @@ int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \n \tcase KVM_XEN_VCPU_ATTR_TYPE_TIMER:\n \t\t/*\n-\t\t * Ensure a consistent snapshot of state is captured, with a\n-\t\t * timer either being pending, or the event channel delivered\n-\t\t * to the corresponding bit in the shared_info. Not still\n-\t\t * lurking in the timer_pending flag for deferred delivery.\n-\t\t * Purely as an optimisation, if the timer_expires field is\n-\t\t * zero, that means the timer isn't active (or even in the\n+\t\t * Ensure a consistent snapshot of state is captured: a timer\n+\t\t * which already fired has either been delivered to the\n+\t\t * corresponding bit in the shared_info, or is reported as\n+\t\t * still owed (expires_ns != 0, if the shared_info page was\n+\t\t * unavailable). Purely\n+\t\t * as an optimisation, if the timer_expires field is zero,\n+\t\t * that means the timer isn't active (or even in the\n \t\t * timer_pending flag) and there is no need to cancel it.\n \t\t */\n \t\tif (vcpu-\u003earch.xen.timer_expires) {\n@@ -1291,8 +1319,20 @@ int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)\n \t\t * That's fine, as the guest won't even have had a chance\n \t\t * to run and handle the interrupt. Asserting an already\n \t\t * pending event channel is idempotent.\n+\t\t *\n+\t\t * Don't re-arm if the flush above failed transiently and\n+\t\t * left the timer pending: delivery is owned by the retry\n+\t\t * on the guest entry path, and an immediate hrtimer fire\n+\t\t * would race it — the callback's timer_pending suppression\n+\t\t * check is not serialized against the entry path, so a\n+\t\t * late callback could re-assert a port the entry path had\n+\t\t * already delivered and the guest already consumed.\n+\t\t *\n+\t\t * An expiry already in the past fires immediately: the\n+\t\t * event is still owed.\n \t\t */\n-\t\tif (vcpu-\u003earch.xen.timer_expires)\n+\t\tif (vcpu-\u003earch.xen.timer_expires \u0026\u0026\n+\t\t    !atomic_read(\u0026vcpu-\u003earch.xen.timer_pending))\n \t\t\thrtimer_start_expires(\u0026vcpu-\u003earch.xen.timer,\n \t\t\t\t\t      HRTIMER_MODE_ABS_HARD);\n \n@@ -1320,7 +1360,15 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)\n \tbool lm = is_long_mode(vcpu);\n \tint r = 0;\n \n+\t/*\n+\t * The attribute ioctls wait out memslot updates while holding\n+\t * xen_lock; a memslot update waits for this vCPU's kvm-\u003esrcu\n+\t * read section to quiesce. Blocking on xen_lock inside that\n+\t * read section would close the cycle, so step out of it first.\n+\t */\n+\tkvm_vcpu_srcu_read_unlock(vcpu);\n \tmutex_lock(\u0026kvm-\u003earch.xen.xen_lock);\n+\tkvm_vcpu_srcu_read_lock(vcpu);\n \tif (kvm-\u003earch.xen.long_mode != lm) {\n \t\tkvm-\u003earch.xen.long_mode = lm;\n \n@@ -1329,7 +1377,7 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)\n \t\t * correct place.\n \t\t */\n \t\tif (kvm-\u003earch.xen.shinfo_cache.active \u0026\u0026\n-\t\t    kvm_xen_shared_info_init(kvm))\n+\t\t    kvm_xen_shared_info_init(kvm, false))\n \t\t\tr = 1;\n \t}\n \tmutex_unlock(\u0026kvm-\u003earch.xen.xen_lock);\n@@ -1775,8 +1823,21 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)\n \t\t}\n \t\tbreak;\n \tcase __HYPERVISOR_event_channel_op:\n-\t\tif (params[0] == EVTCHNOP_send)\n-\t\t\thandled = kvm_xen_hcall_evtchn_send(vcpu, params[1], \u0026r);\n+\t\tif (params[0] == EVTCHNOP_send) {\n+\t\t\tint ret = kvm_xen_hcall_evtchn_send(vcpu, params[1], \u0026r);\n+\n+\t\t\t/*\n+\t\t\t * Delivery raced a memslot update; waiting for it\n+\t\t\t * here would deadlock under vcpu_run's kvm-\u003esrcu\n+\t\t\t * read section. Leave the hypercall uncompleted —\n+\t\t\t * RIP not advanced — so the guest re-executes it.\n+\t\t\t * Each attempt cycles the srcu read section on the\n+\t\t\t * way back in, letting the update complete.\n+\t\t\t */\n+\t\t\tif (ret == -EAGAIN)\n+\t\t\t\treturn 1;\n+\t\t\thandled = !ret;\n+\t\t}\n \t\tbreak;\n \tcase __HYPERVISOR_sched_op:\n \t\thandled = kvm_xen_hcall_sched_op(vcpu, is_64bit, params[0],\n@@ -1831,6 +1892,89 @@ static void kvm_xen_check_poller(struct kvm_vcpu *vcpu, int port)\n \t}\n }\n \n+static void __kvm_xen_set_evtchn_fast(struct kvm_vcpu *vcpu, int port_word_bit,\n+\t\t\t\t      bool has_64bit_shinfo)\n+{\n+\tstruct gfn_to_pfn_cache *gpc = \u0026vcpu-\u003earch.xen.vcpu_info_cache;\n+\tunsigned long vi_pending_sel_ofs;\n+\tbool inject_upcall = false;\n+\tbool kick_vcpu = false;\n+\tunsigned long flags;\n+\tbool old;\n+\n+\tvi_pending_sel_ofs = has_64bit_shinfo ?\n+\t\toffsetof(struct vcpu_info, evtchn_pending_sel) :\n+\t\toffsetof(struct compat_vcpu_info, evtchn_pending_sel);\n+\n+\t/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */\n+\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n+\tif (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {\n+\t\t/*\n+\t\t * Could not access the vcpu_info. Set the bit in-kernel and\n+\t\t * prod the vCPU to deliver it for itself. Note that an MSI is\n+\t\t * *not* an acceptable substitute here even if the vCPU has an\n+\t\t * upcall vector: the pending bit only exists in\n+\t\t * evtchn_pending_sel so far, and the vCPU has to be forced\n+\t\t * out of the guest so that kvm_xen_inject_pending_events()\n+\t\t * can refresh the cache and propagate it to the guest.\n+\t\t */\n+\t\tif (!test_and_set_bit(port_word_bit, \u0026vcpu-\u003earch.xen.evtchn_pending_sel))\n+\t\t\tkick_vcpu = true;\n+\t\tgoto out_unlock;\n+\t}\n+\tinject_upcall = true;\n+\n+\t/*\n+\t * Explicitly use a 32-bit btsl instead of test_and_set_bit(), which\n+\t * would use btsq on x86-64. The vcpu_info is guest-controlled and only\n+\t * required to be 32-bit aligned, so a 64-bit access could generate a\n+\t * split-lock #AC.\n+\t *\n+\t * Note, this does not apply to the test_and_set_bit() on pending_bits\n+\t * in the caller: that is in the per-VM shared_info, which is page\n+\t * aligned, so the access is guaranteed to be 64-bit aligned.\n+\t */\n+\told = GEN_BINARY_RMWcc(LOCK_PREFIX \"btsl\",\n+\t\t\t       *(u32 *)(gpc-\u003ekhva + vi_pending_sel_ofs),\n+\t\t\t       c, \"Ir\", port_word_bit);\n+\tif (!old) {\n+\t\tstruct vcpu_info *vi = gpc-\u003ekhva;\n+\n+\t\t/* No need for compat handling */\n+\t\tBUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=\n+\t\t\t     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));\n+\n+\t\tWRITE_ONCE(vi-\u003eevtchn_upcall_pending, 1);\n+\t\tkick_vcpu = true;\n+\t}\n+\n+out_unlock:\n+\tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n+\n+\t/*\n+\t * Deliver the upcall or kick the vCPU only after dropping the GPC\n+\t * read lock. Both paths end up in kvm_vcpu_kick(), and the MSI\n+\t * delivery also walks the APIC map and takes APIC locks; none of\n+\t * that wants to be nested inside the GPC read lock, which a\n+\t * concurrent invalidation may be waiting to take for write.\n+\t */\n+\tif (!kick_vcpu)\n+\t\treturn;\n+\n+\t/*\n+\t * For the per-vCPU lapic vector, deliver it as MSI — but only if the\n+\t * vcpu_info was actually updated above. If it wasn't, the vCPU must\n+\t * be kicked instead (see above).\n+\t */\n+\tif (inject_upcall \u0026\u0026 vcpu-\u003earch.xen.upcall_vector) {\n+\t\tkvm_xen_inject_vcpu_vector(vcpu);\n+\t\treturn;\n+\t}\n+\n+\tkvm_make_request(KVM_REQ_UNBLOCK, vcpu);\n+\tkvm_vcpu_kick(vcpu);\n+}\n+\n /*\n  * The return value from this function is propagated to kvm_set_irq() API,\n  * so it returns:\n@@ -1845,11 +1989,10 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)\n {\n \tstruct gfn_to_pfn_cache *gpc = \u0026kvm-\u003earch.xen.shinfo_cache;\n \tbool has_64bit_shinfo = kvm_xen_has_64bit_shinfo(kvm);\n-\tunsigned long *pending_bits, *mask_bits, vi_pending_sel_ofs;\n+\tunsigned long *pending_bits, *mask_bits;\n \tstruct kvm_vcpu *vcpu;\n \tunsigned long flags;\n \tint port_word_bit;\n-\tbool kick_vcpu = false;\n \tint vcpu_idx, idx, rc;\n \n \tvcpu_idx = READ_ONCE(xe-\u003evcpu_idx);\n@@ -1871,23 +2014,19 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)\n \n \tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n \tif (!kvm_gpc_check(gpc, PAGE_SIZE))\n-\t\tgoto out_rcu;\n+\t\tgoto out_unlock;\n \n \tif (has_64bit_shinfo) {\n \t\tstruct shared_info *shinfo = gpc-\u003ekhva;\n \t\tpending_bits = (unsigned long *)\u0026shinfo-\u003eevtchn_pending;\n \t\tmask_bits = (unsigned long *)\u0026shinfo-\u003eevtchn_mask;\n \t\tport_word_bit = xe-\u003eport / 64;\n-\n-\t\tvi_pending_sel_ofs = offsetof(struct vcpu_info, evtchn_pending_sel);\n \t} else {\n \t\tstruct compat_shared_info *shinfo = gpc-\u003ekhva;\n \t\tpending_bits = (unsigned long *)\u0026shinfo-\u003eevtchn_pending;\n \t\tmask_bits = (unsigned long *)\u0026shinfo-\u003eevtchn_mask;\n \t\tport_word_bit = xe-\u003eport / 32;\n \n-\t\tvi_pending_sel_ofs = offsetof(struct compat_vcpu_info, evtchn_pending_sel);\n-\n \t\t/* test_and_set_bit() needs 64-bit alignment, but that's OK */\n \t\tBUILD_BUG_ON(offsetof(struct compat_shared_info, evtchn_pending) \u0026 7);\n \t}\n@@ -1903,71 +2042,30 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)\n \t\trc = 0; /* It was already raised */\n \t} else if (test_bit(xe-\u003eport, mask_bits)) {\n \t\trc = -ENOTCONN; /* Masked */\n-\t\tkvm_xen_check_poller(vcpu, xe-\u003eport);\n \t} else {\n-\t\tbool old;\n-\n \t\trc = 1; /* Delivered to the bitmap in shared_info. */\n-\t\t/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */\n-\t\tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n-\t\tgpc = \u0026vcpu-\u003earch.xen.vcpu_info_cache;\n-\n-\t\tread_lock_irqsave(\u0026gpc-\u003elock, flags);\n-\t\tif (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {\n-\t\t\t/*\n-\t\t\t * Could not access the vcpu_info. Set the bit in-kernel\n-\t\t\t * and prod the vCPU to deliver it for itself.\n-\t\t\t */\n-\t\t\tif (!test_and_set_bit(port_word_bit, \u0026vcpu-\u003earch.xen.evtchn_pending_sel))\n-\t\t\t\tkick_vcpu = true;\n-\t\t\tgoto out_rcu;\n-\t\t}\n-\n-\t\t/*\n-\t\t * Explicitly use a 32-bit btsl instead of test_and_set_bit(),\n-\t\t * which would use btsq on x86-64. The vcpu_info is guest-\n-\t\t * controlled and only required to be 32-bit aligned, so a\n-\t\t * 64-bit access could generate a split-lock #AC.\n-\t\t *\n-\t\t * Note, this does not apply to the test_and_set_bit() on\n-\t\t * pending_bits above: that is in the per-VM shared_info, which\n-\t\t * is page aligned, so the access is guaranteed to be 64-bit\n-\t\t * aligned.\n-\t\t */\n-\t\told = GEN_BINARY_RMWcc(LOCK_PREFIX \"btsl\",\n-\t\t\t\t       *(u32 *)(gpc-\u003ekhva + vi_pending_sel_ofs),\n-\t\t\t\t       c, \"Ir\", port_word_bit);\n-\t\tif (!old) {\n-\t\t\tstruct vcpu_info *vi = gpc-\u003ekhva;\n-\n-\t\t\t/* No need for compat handling */\n-\t\t\tBUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=\n-\t\t\t\t     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));\n-\n-\t\t\tWRITE_ONCE(vi-\u003eevtchn_upcall_pending, 1);\n-\t\t\tkick_vcpu = true;\n-\t\t}\n-\n-\t\t/* For the per-vCPU lapic vector, deliver it as MSI. */\n-\t\tif (kick_vcpu \u0026\u0026 vcpu-\u003earch.xen.upcall_vector) {\n-\t\t\tkvm_xen_inject_vcpu_vector(vcpu);\n-\t\t\tkick_vcpu = false;\n-\t\t}\n \t}\n \n- out_rcu:\n+ out_unlock:\n \tread_unlock_irqrestore(\u0026gpc-\u003elock, flags);\n-\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n \n-\tif (kick_vcpu) {\n-\t\tkvm_make_request(KVM_REQ_UNBLOCK, vcpu);\n-\t\tkvm_vcpu_kick(vcpu);\n-\t}\n+\t/*\n+\t * Both of these can kick the vCPU, so keep them outside the GPC\n+\t * read lock; an invalidation may be waiting to take it for write.\n+\t */\n+\tif (rc == -ENOTCONN)\n+\t\tkvm_xen_check_poller(vcpu, xe-\u003eport);\n+\telse if (rc == 1)\n+\t\t__kvm_xen_set_evtchn_fast(vcpu, port_word_bit,\n+\t\t\t\t\t  has_64bit_shinfo);\n+\n+\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n \n \treturn rc;\n }\n \n-static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)\n+static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,\n+\t\t\t      bool wait)\n {\n \tbool mm_borrowed = false;\n \tint rc;\n@@ -2004,16 +2102,13 @@ static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)\n \t */\n \tdo {\n \t\tstruct gfn_to_pfn_cache *gpc = \u0026kvm-\u003earch.xen.shinfo_cache;\n-\t\tint idx;\n \n \t\trc = kvm_xen_set_evtchn_fast(xe, kvm);\n \t\tif (rc != -EWOULDBLOCK)\n \t\t\tbreak;\n \n-\t\tidx = srcu_read_lock(\u0026kvm-\u003esrcu);\n-\t\trc = kvm_gpc_refresh(gpc, PAGE_SIZE);\n-\t\tsrcu_read_unlock(\u0026kvm-\u003esrcu, idx);\n-\t} while(!rc);\n+\t\trc = kvm_gpc_refresh(gpc, PAGE_SIZE, wait);\n+\t} while (!rc);\n \n \tif (mm_borrowed)\n \t\tkthread_unuse_mm(kvm-\u003emm);\n@@ -2028,7 +2123,7 @@ static int evtchn_set_fn(struct kvm_kernel_irq_routing_entry *e, struct kvm *kvm\n \tif (!level)\n \t\treturn -EINVAL;\n \n-\treturn kvm_xen_set_evtchn(\u0026e-\u003exen_evtchn, kvm);\n+\treturn kvm_xen_set_evtchn(\u0026e-\u003exen_evtchn, kvm, true);\n }\n \n /*\n@@ -2102,7 +2197,7 @@ int kvm_xen_hvm_evtchn_send(struct kvm *kvm, struct kvm_irq_routing_xen_evtchn *\n \te.vcpu_idx = -1;\n \te.priority = uxe-\u003epriority;\n \n-\tret = kvm_xen_set_evtchn(\u0026e, kvm);\n+\tret = kvm_xen_set_evtchn(\u0026e, kvm, true);\n \n \t/*\n \t * None of that 'return 1 if it actually got delivered' nonsense.\n@@ -2331,7 +2426,11 @@ static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data\n \treturn kvm_xen_eventfd_assign(kvm, data);\n }\n \n-static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)\n+/*\n+ * Returns 0 with *r set if handled, -EAGAIN if the hypercall should be\n+ * re-executed by the guest, or -ENOENT to hand it to userspace.\n+ */\n+static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)\n {\n \tstruct evtchnfd *evtchnfd;\n \tstruct evtchn_send send;\n@@ -2341,7 +2440,7 @@ static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)\n \tBUILD_BUG_ON(sizeof(send) != 4);\n \tif (kvm_read_guest_virt(vcpu, param, \u0026send, sizeof(send), \u0026e)) {\n \t\t*r = -EFAULT;\n-\t\treturn true;\n+\t\treturn 0;\n \t}\n \n \t/*\n@@ -2350,18 +2449,22 @@ static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)\n \t */\n \tevtchnfd = xa_load(\u0026vcpu-\u003ekvm-\u003earch.xen.evtchn_ports, send.port);\n \tif (!evtchnfd)\n-\t\treturn false;\n+\t\treturn -ENOENT;\n \n \tif (evtchnfd-\u003edeliver.port.port) {\n-\t\tint ret = kvm_xen_set_evtchn(\u0026evtchnfd-\u003edeliver.port, vcpu-\u003ekvm);\n+\t\tint ret = kvm_xen_set_evtchn(\u0026evtchnfd-\u003edeliver.port,\n+\t\t\t\t\t     vcpu-\u003ekvm, false);\n+\n+\t\tif (ret == -EAGAIN)\n+\t\t\treturn ret;\n \t\tif (ret \u003c 0 \u0026\u0026 ret != -ENOTCONN)\n-\t\t\treturn false;\n+\t\t\treturn -ENOENT;\n \t} else {\n \t\teventfd_signal(evtchnfd-\u003edeliver.eventfd.ctx);\n \t}\n \n \t*r = 0;\n-\treturn true;\n+\treturn 0;\n }\n \n void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)\n@@ -2375,7 +2478,7 @@ void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)\n \n \tkvm_gpc_init(\u0026vcpu-\u003earch.xen.runstate_cache, vcpu-\u003ekvm);\n \tkvm_gpc_init(\u0026vcpu-\u003earch.xen.runstate2_cache, vcpu-\u003ekvm);\n-\tkvm_gpc_init(\u0026vcpu-\u003earch.xen.vcpu_info_cache, vcpu-\u003ekvm);\n+\t__kvm_gpc_init(\u0026vcpu-\u003earch.xen.vcpu_info_cache, vcpu-\u003ekvm, true);\n \tkvm_gpc_init(\u0026vcpu-\u003earch.xen.vcpu_time_info_cache, vcpu-\u003ekvm);\n }\n \n@@ -2396,7 +2499,7 @@ void kvm_xen_init_vm(struct kvm *kvm)\n {\n \tmutex_init(\u0026kvm-\u003earch.xen.xen_lock);\n \txa_init(\u0026kvm-\u003earch.xen.evtchn_ports);\n-\tkvm_gpc_init(\u0026kvm-\u003earch.xen.shinfo_cache, kvm);\n+\t__kvm_gpc_init(\u0026kvm-\u003earch.xen.shinfo_cache, kvm, true);\n }\n \n void kvm_xen_destroy_vm(struct kvm *kvm)\ndiff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h\nindex 3dd04605f2e55..debce84f4177c 100644\n--- a/include/linux/kvm_host.h\n+++ b/include/linux/kvm_host.h\n@@ -1465,7 +1465,13 @@ int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,\n  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by\n  * the caller before init).\n  */\n-void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);\n+void __kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm,\n+\t\t    bool never_dirty);\n+\n+static inline void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)\n+{\n+\t__kvm_gpc_init(gpc, kvm, false);\n+}\n \n /**\n  * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest\n@@ -1474,16 +1480,24 @@ void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);\n  * @gpc:\t   struct gfn_to_pfn_cache object.\n  * @gpa:\t   guest physical address to map.\n  * @len:\t   sanity check; the range being access must fit a single page.\n+ * @wait:\t   wait out a concurrent memslot update instead of returning\n+ *\t\t   -EAGAIN. May not be used while this task holds any kvm-\u003esrcu\n+ *\t\t   read section, and no lock held across the wait may ever be\n+ *\t\t   taken within one: the update's synchronize_srcu() would\n+ *\t\t   deadlock against the wait. Lockdep checks both.\n  *\n  * @return:\t   0 for success.\n  *\t\t   -EINVAL for a mapping which would cross a page boundary.\n  *\t\t   -EFAULT for an untranslatable guest physical address.\n+ *\t\t   -EAGAIN if the memslot is being updated (only with\n+ *\t\t   wait == false, or on a fatal signal while waiting).\n  *\n  * This primes a gfn_to_pfn_cache and links it into the @gpc-\u003ekvm's list for\n  * invalidations to be processed.  Callers are required to use kvm_gpc_check()\n  * to ensure that the cache is valid before accessing the target page.\n  */\n-int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len);\n+int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len,\n+\t\t     bool wait);\n \n /**\n  * kvm_gpc_activate_hva - prepare a cached kernel mapping and HPA for a given HVA.\n@@ -1499,7 +1513,8 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)\n  * The semantics of this function are the same as those of kvm_gpc_activate(). It\n  * merely bypasses a layer of address translation.\n  */\n-int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva, unsigned long len);\n+int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva,\n+\t\t\t unsigned long len);\n \n /**\n  * kvm_gpc_check - check validity of a gfn_to_pfn_cache.\n@@ -1524,10 +1539,13 @@ bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);\n  *\n  * @gpc:\t   struct gfn_to_pfn_cache object.\n  * @len:\t   sanity check; the range being access must fit a single page.\n+ * @wait:\t   as kvm_gpc_activate().\n  *\n  * @return:\t   0 for success.\n  *\t\t   -EINVAL for a mapping which would cross a page boundary.\n  *\t\t   -EFAULT for an untranslatable guest physical address.\n+ *\t\t   -EAGAIN if the memslot is being updated (only with\n+ *\t\t   wait == false, or on a fatal signal while waiting).\n  *\n  * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful\n  * return from this function does not mean the page can be immediately\n@@ -1535,7 +1553,7 @@ bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);\n  * still lock and check the cache status, as this function does not return\n  * with the lock still held to permit access.\n  */\n-int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len);\n+int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait);\n \n /**\n  * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache.\n@@ -1976,7 +1994,7 @@ static inline void kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache *gpc)\n {\n \tlockdep_assert_held(\u0026gpc-\u003elock);\n \n-\tif (!gpc-\u003ememslot)\n+\tif (!gpc-\u003ememslot || gpc-\u003enever_dirty)\n \t\treturn;\n \n \tmark_page_dirty_in_slot(gpc-\u003ekvm, gpc-\u003ememslot, gpa_to_gfn(gpc-\u003egpa));\ndiff --git a/include/linux/kvm_types.h b/include/linux/kvm_types.h\nindex a568d8e6f4e82..e850adc3f47ef 100644\n--- a/include/linux/kvm_types.h\n+++ b/include/linux/kvm_types.h\n@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {\n \tkvm_pfn_t pfn;\n \tbool active;\n \tbool valid;\n+\tbool never_dirty;\n };\n \n #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE\ndiff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm\nindex 96bab7002d39e..e7e17d19d6cbb 100644\n--- a/tools/testing/selftests/kvm/Makefile.kvm\n+++ b/tools/testing/selftests/kvm/Makefile.kvm\n@@ -144,6 +144,7 @@ TEST_GEN_PROGS_x86 += x86/xss_msr_test\n TEST_GEN_PROGS_x86 += x86/debug_regs\n TEST_GEN_PROGS_x86 += x86/tsc_msrs_test\n TEST_GEN_PROGS_x86 += x86/vmx_pmu_caps_test\n+TEST_GEN_PROGS_x86 += x86/xen_evtchn_memslot_race_test\n TEST_GEN_PROGS_x86 += x86/xen_shinfo_test\n TEST_GEN_PROGS_x86 += x86/xen_vmcall_test\n TEST_GEN_PROGS_x86 += x86/sev_dbg_test\ndiff --git a/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c b/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c\nnew file mode 100644\nindex 0000000000000..2b6974d3d4645\n--- /dev/null\n+++ b/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c\n@@ -0,0 +1,178 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * xen_evtchn_memslot_race_test\n+ *\n+ * A guest EVTCHNOP_send whose delivery races a DELETE/re-CREATE of the\n+ * memslot holding the shared_info page. The delivery path runs in the\n+ * vCPU's exit-handling context, under vcpu_run's kvm-\u003esrcu read\n+ * section; if it waits there for the memslot update to complete, it\n+ * deadlocks against kvm_swap_active_memslots()'s\n+ * synchronize_srcu_expedited() waiting out that very read section.\n+ * Regression test for that deadlock: KVM must defer the delivery to\n+ * the next guest entry rather than spin in exit context.\n+ *\n+ * The guest sends events in a tight loop; a host thread deletes and\n+ * recreates the shared_info slot in a tight loop. On a broken host\n+ * this livelocks within a second or two (the test then dies by\n+ * timeout); on a fixed host every send eventually delivers and the\n+ * test completes N iterations.\n+ */\n+#include \u003cpthread.h\u003e\n+#include \u003cstdatomic.h\u003e\n+\n+#include \"test_util.h\"\n+#include \"kvm_util.h\"\n+#include \"processor.h\"\n+\n+#include \u003cstdint.h\u003e\n+\n+#define SHINFO_REGION_GPA\t0xc0000000ULL\n+#define SHINFO_REGION_SLOT\t10\n+\n+#define EVTCHN_PORT\t\t15\n+#define TEST_ITERATIONS\t\t4000\n+\n+#define EVTCHNOP_send\t\t4\n+#define __HYPERVISOR_event_channel_op\t32\n+\n+#define XEN_HYPERCALL_MSR\t0x40000000\n+\n+#define EVTCHNSTAT_ipi\t\t5\n+\n+struct evtchn_send {\n+\tuint32_t port;\n+};\n+\n+static void guest_code(void)\n+{\n+\tstruct evtchn_send s = { .port = EVTCHN_PORT };\n+\tint i;\n+\n+\tfor (i = 0; i \u003c TEST_ITERATIONS; i++) {\n+\t\t/*\n+\t\t * The delivery may legitimately fail while the shared_info\n+\t\t * slot is mid-churn (between DELETE and re-CREATE there is\n+\t\t * no slot at all, which is -EFAULT, not a transient). The\n+\t\t * failure mode under test is the vCPU never coming back at\n+\t\t * all (deadlock -\u003e timeout), not the hypercall rc.\n+\t\t */\n+\t\t__xen_hypercall(__HYPERVISOR_event_channel_op, EVTCHNOP_send, \u0026s);\n+\t\tGUEST_SYNC(i);\n+\t}\n+\n+\tGUEST_DONE();\n+}\n+\n+static atomic_bool churn_stop;\n+\n+static void *memslot_churn(void *arg)\n+{\n+\tstruct kvm_vm *vm = arg;\n+\n+\twhile (!atomic_load(\u0026churn_stop)) {\n+\t\tvm_mem_region_delete(vm, SHINFO_REGION_SLOT);\n+\t\tvm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,\n+\t\t\t\t\t    SHINFO_REGION_GPA,\n+\t\t\t\t\t    SHINFO_REGION_SLOT, 2, 0);\n+\t}\n+\treturn NULL;\n+}\n+\n+int main(int argc, char *argv[])\n+{\n+\tstruct kvm_vcpu *vcpu;\n+\tstruct kvm_vm *vm;\n+\tpthread_t thread;\n+\tstruct ucall uc;\n+\tint done = 0;\n+\tint r;\n+\n+\tint xen_caps = kvm_check_cap(KVM_CAP_XEN_HVM);\n+\n+\tTEST_REQUIRE(xen_caps \u0026 KVM_XEN_HVM_CONFIG_SHARED_INFO);\n+\tTEST_REQUIRE(xen_caps \u0026 KVM_XEN_HVM_CONFIG_EVTCHN_SEND);\n+\n+\tvm = vm_create_with_one_vcpu(\u0026vcpu, guest_code);\n+\n+\tvm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,\n+\t\t\t\t    SHINFO_REGION_GPA, SHINFO_REGION_SLOT, 2, 0);\n+\n+\tstruct kvm_xen_hvm_config hvmc = {\n+\t\t.flags = KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |\n+\t\t\t KVM_XEN_HVM_CONFIG_EVTCHN_SEND,\n+\t\t.msr = XEN_HYPERCALL_MSR,\n+\t};\n+\tvm_ioctl(vm, KVM_XEN_HVM_CONFIG, \u0026hvmc);\n+\n+\tstruct kvm_xen_hvm_attr lm = {\n+\t\t.type = KVM_XEN_ATTR_TYPE_LONG_MODE,\n+\t\t.u.long_mode = 1,\n+\t};\n+\tvm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, \u0026lm);\n+\n+\tstruct kvm_xen_hvm_attr ha = {\n+\t\t.type = KVM_XEN_ATTR_TYPE_SHARED_INFO,\n+\t\t.u.shared_info.gfn = SHINFO_REGION_GPA / PAGE_SIZE,\n+\t};\n+\tvm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, \u0026ha);\n+\n+\tstruct kvm_xen_vcpu_attr vi = {\n+\t\t.type = KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO,\n+\t\t.u.gpa = SHINFO_REGION_GPA + 0x40,\n+\t};\n+\tvcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, \u0026vi);\n+\n+\t/* Loop the port back to this vCPU as an IPI. */\n+\tstruct kvm_xen_hvm_attr evt = {\n+\t\t.type = KVM_XEN_ATTR_TYPE_EVTCHN,\n+\t\t.u.evtchn.send_port = EVTCHN_PORT,\n+\t\t.u.evtchn.type = EVTCHNSTAT_ipi,\n+\t\t.u.evtchn.flags = 0,\n+\t\t.u.evtchn.deliver.port.port = EVTCHN_PORT,\n+\t\t.u.evtchn.deliver.port.vcpu = vcpu-\u003eid,\n+\t\t.u.evtchn.deliver.port.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL,\n+\t};\n+\tvm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, \u0026evt);\n+\n+\tr = pthread_create(\u0026thread, NULL, memslot_churn, vm);\n+\tTEST_ASSERT(!r, \"pthread_create() failed: %d\", r);\n+\n+\twhile (!done) {\n+\t\tvcpu_run(vcpu);\n+\n+\t\t/*\n+\t\t * In the window where the shared_info slot is fully deleted\n+\t\t * (between the churn thread's DELETE and re-CREATE), the\n+\t\t * delivery fails with -EFAULT and the hypercall bounces to\n+\t\t * userspace as KVM_EXIT_XEN. Complete it with an error\n+\t\t * result and keep going; the failure mode under test is\n+\t\t * the vCPU never coming back (deadlock -\u003e timeout), not\n+\t\t * the hypercall rc.\n+\t\t */\n+\t\tif (vcpu-\u003erun-\u003eexit_reason == KVM_EXIT_XEN \u0026\u0026\n+\t\t    vcpu-\u003erun-\u003exen.type == KVM_EXIT_XEN_HCALL) {\n+\t\t\tvcpu-\u003erun-\u003exen.u.hcall.result = -EFAULT;\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\tTEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);\n+\n+\t\tswitch (get_ucall(vcpu, \u0026uc)) {\n+\t\tcase UCALL_SYNC:\n+\t\t\tbreak;\n+\t\tcase UCALL_DONE:\n+\t\t\tdone = 1;\n+\t\t\tbreak;\n+\t\tcase UCALL_ABORT:\n+\t\t\tREPORT_GUEST_ASSERT(uc);\n+\t\tdefault:\n+\t\t\tTEST_FAIL(\"Unexpected ucall %lu\", uc.cmd);\n+\t\t}\n+\t}\n+\n+\tatomic_store(\u0026churn_stop, true);\n+\tpthread_join(thread, NULL);\n+\n+\tkvm_vm_free(vm);\n+\treturn 0;\n+}\ndiff --git a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c\nindex aaa414c677add..3b11d0ee253f5 100644\n--- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c\n+++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c\n@@ -356,11 +356,12 @@ static void guest_code(void)\n wait_for_timer:\n \t/*\n \t * Poll for a timer wake event while the worker thread is mucking with\n-\t * the shared info.  KVM XEN drops timer IRQs if the shared info is\n-\t * invalid when the timer expires.  Arbitrarily poll 100 times before\n-\t * giving up and asking the VMM to re-arm the timer.  100 polls should\n-\t * consume enough time to beat on KVM without taking too long if the\n-\t * timer IRQ is dropped due to an invalid event channel.\n+\t * the shared info.  KVM is now supposed to retry a timer IRQ whose\n+\t * delivery hit an invalid shared info rather than drop it, but older\n+\t * kernels drop it on the floor.  Arbitrarily poll 100 times before\n+\t * giving up and asking the VMM to re-arm the timer, so the test still\n+\t * completes (and documents the VMM-side recovery protocol) on\n+\t * unfixed kernels.\n \t */\n \tfor (i = 0; i \u003c 100 \u0026\u0026 !guest_saw_irq; i++)\n \t\t__xen_hypercall(__HYPERVISOR_sched_op, SCHEDOP_poll, \u0026p);\ndiff --git a/virt/kvm/pfncache.c b/virt/kvm/pfncache.c\nindex 3659686b97c24..8498abb746ade 100644\n--- a/virt/kvm/pfncache.c\n+++ b/virt/kvm/pfncache.c\n@@ -304,7 +304,22 @@ static int __kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned l\n \t\t\tgpc-\u003euhva = gfn_to_hva_memslot(gpc-\u003ememslot, gfn);\n \n \t\t\tif (kvm_is_error_hva(gpc-\u003euhva)) {\n-\t\t\t\tret = -EFAULT;\n+\t\t\t\t/*\n+\t\t\t\t * A slot being deleted or moved is present\n+\t\t\t\t * but flagged invalid; the lookup failure is\n+\t\t\t\t * transient, resolved when the update\n+\t\t\t\t * completes (or reverts) and announced by a\n+\t\t\t\t * new memslot generation. Distinguish that\n+\t\t\t\t * from a genuinely unbacked gfn so that the\n+\t\t\t\t * caller may retry rather than report an\n+\t\t\t\t * error, as RET_PF_RETRY does for ordinary\n+\t\t\t\t * guest faults.\n+\t\t\t\t */\n+\t\t\t\tif (gpc-\u003ememslot \u0026\u0026\n+\t\t\t\t    (gpc-\u003ememslot-\u003eflags \u0026 KVM_MEMSLOT_INVALID))\n+\t\t\t\t\tret = -EAGAIN;\n+\t\t\t\telse\n+\t\t\t\t\tret = -EFAULT;\n \t\t\t\tgoto out;\n \t\t\t}\n \n@@ -363,26 +378,67 @@ static int __kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned l\n \treturn ret;\n }\n \n-int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len)\n+/*\n+ * One refresh attempt, under the caller's refresh_lock. Takes a kvm-\u003esrcu\n+ * read section for the attempt, as the memslot lookups consult the active\n+ * memslots.\n+ */\n+static int gpc_refresh_locked(struct gfn_to_pfn_cache *gpc, gpa_t gpa,\n+\t\t\t      unsigned long uhva)\n {\n-\tunsigned long uhva;\n+\tint idx, ret;\n \n-\tguard(mutex)(\u0026gpc-\u003erefresh_lock);\n+\tidx = srcu_read_lock(\u0026gpc-\u003ekvm-\u003esrcu);\n+\tret = __kvm_gpc_refresh(gpc, gpa, uhva);\n+\tsrcu_read_unlock(\u0026gpc-\u003ekvm-\u003esrcu, idx);\n \n-\tif (!kvm_gpc_is_valid_len(gpc-\u003egpa, gpc-\u003euhva, len))\n-\t\treturn -EINVAL;\n+\treturn ret;\n+}\n+\n+int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait)\n+{\n+\tunsigned long uhva;\n+\tint ret;\n \n \t/*\n-\t * If the GPA is valid then ignore the HVA, as a cache can be GPA-based\n-\t * or HVA-based, not both.  For GPA-based caches, the HVA will be\n-\t * recomputed during refresh if necessary.\n+\t * The wait completes only after a memslot update's\n+\t * synchronize_srcu(\u0026kvm-\u003esrcu), so it functions as one for lockdep:\n+\t * taking any lock held across it within a kvm-\u003esrcu read section\n+\t * is reported as the deadlock it would be.\n \t */\n-\tuhva = kvm_is_error_gpa(gpc-\u003egpa) ? gpc-\u003euhva : KVM_HVA_ERR_BAD;\n+\tif (wait)\n+\t\tsrcu_lock_sync(\u0026gpc-\u003ekvm-\u003esrcu.dep_map);\n+\n+\tfor (;;) {\n+\t\tscoped_guard(mutex, \u0026gpc-\u003erefresh_lock) {\n+\t\t\tif (!kvm_gpc_is_valid_len(gpc-\u003egpa, gpc-\u003euhva, len))\n+\t\t\t\treturn -EINVAL;\n \n-\treturn __kvm_gpc_refresh(gpc, gpc-\u003egpa, uhva);\n+\t\t\t/*\n+\t\t\t * If the GPA is valid then ignore the HVA, as a cache\n+\t\t\t * can be GPA-based or HVA-based, not both.  For\n+\t\t\t * GPA-based caches, the HVA will be recomputed during\n+\t\t\t * refresh if necessary.\n+\t\t\t */\n+\t\t\tuhva = kvm_is_error_gpa(gpc-\u003egpa) ? gpc-\u003euhva : KVM_HVA_ERR_BAD;\n+\n+\t\t\tret = gpc_refresh_locked(gpc, gpc-\u003egpa, uhva);\n+\t\t}\n+\n+\t\tif (ret != -EAGAIN || !wait || fatal_signal_pending(current))\n+\t\t\treturn ret;\n+\n+\t\t/*\n+\t\t * Wait with refresh_lock dropped: a kvm-\u003esrcu reader blocked\n+\t\t * on it must be able to proceed and quiesce, or the memslot\n+\t\t * update being waited for could never complete.\n+\t\t */\n+\t\tcond_resched();\n+\t}\n }\n \n-void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)\n+void __kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm,\n+\t\t    bool never_dirty)\n {\n \trwlock_init(\u0026gpc-\u003elock);\n \tmutex_init(\u0026gpc-\u003erefresh_lock);\n@@ -392,39 +448,55 @@ void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)\n \tgpc-\u003egpa = INVALID_GPA;\n \tgpc-\u003euhva = KVM_HVA_ERR_BAD;\n \tgpc-\u003eactive = gpc-\u003evalid = false;\n+\tgpc-\u003enever_dirty = never_dirty;\n }\n \n static int __kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long uhva,\n-\t\t\t      unsigned long len)\n+\t\t\t      unsigned long len, bool wait)\n {\n \tstruct kvm *kvm = gpc-\u003ekvm;\n \n \tif (!kvm_gpc_is_valid_len(gpa, uhva, len))\n \t\treturn -EINVAL;\n \n-\tguard(mutex)(\u0026gpc-\u003erefresh_lock);\n-\n-\tif (!gpc-\u003eactive) {\n-\t\tif (KVM_BUG_ON(gpc-\u003evalid, kvm))\n-\t\t\treturn -EIO;\n+\t/* As in kvm_gpc_refresh(): the wait is a synchronize_srcu() to lockdep. */\n+\tif (wait)\n+\t\tsrcu_lock_sync(\u0026kvm-\u003esrcu.dep_map);\n+\n+\tfor (;;) {\n+\t\tint ret;\n+\n+\t\tscoped_guard(mutex, \u0026gpc-\u003erefresh_lock) {\n+\t\t\tif (!gpc-\u003eactive) {\n+\t\t\t\tif (KVM_BUG_ON(gpc-\u003evalid, kvm))\n+\t\t\t\t\treturn -EIO;\n+\n+\t\t\t\tspin_lock(\u0026kvm-\u003egpc_lock);\n+\t\t\t\tlist_add(\u0026gpc-\u003elist, \u0026kvm-\u003egpc_list);\n+\t\t\t\tspin_unlock(\u0026kvm-\u003egpc_lock);\n+\n+\t\t\t\t/*\n+\t\t\t\t * Activate the cache after adding it to the\n+\t\t\t\t * list, a concurrent refresh must not\n+\t\t\t\t * establish a mapping until the cache is\n+\t\t\t\t * reachable by mmu_notifier events.\n+\t\t\t\t */\n+\t\t\t\twrite_lock_irq(\u0026gpc-\u003elock);\n+\t\t\t\tgpc-\u003eactive = true;\n+\t\t\t\twrite_unlock_irq(\u0026gpc-\u003elock);\n+\t\t\t}\n+\t\t\tret = gpc_refresh_locked(gpc, gpa, uhva);\n+\t\t}\n \n-\t\tspin_lock(\u0026kvm-\u003egpc_lock);\n-\t\tlist_add(\u0026gpc-\u003elist, \u0026kvm-\u003egpc_list);\n-\t\tspin_unlock(\u0026kvm-\u003egpc_lock);\n+\t\tif (ret != -EAGAIN || !wait || fatal_signal_pending(current))\n+\t\t\treturn ret;\n \n-\t\t/*\n-\t\t * Activate the cache after adding it to the list, a concurrent\n-\t\t * refresh must not establish a mapping until the cache is\n-\t\t * reachable by mmu_notifier events.\n-\t\t */\n-\t\twrite_lock_irq(\u0026gpc-\u003elock);\n-\t\tgpc-\u003eactive = true;\n-\t\twrite_unlock_irq(\u0026gpc-\u003elock);\n+\t\tcond_resched();\n \t}\n-\treturn __kvm_gpc_refresh(gpc, gpa, uhva);\n }\n \n-int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)\n+int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len,\n+\t\t     bool wait)\n {\n \t/*\n \t * Explicitly disallow INVALID_GPA so that the magic value can be used\n@@ -433,15 +505,17 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)\n \tif (WARN_ON_ONCE(kvm_is_error_gpa(gpa)))\n \t\treturn -EINVAL;\n \n-\treturn __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len);\n+\treturn __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len, wait);\n }\n \n-int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva, unsigned long len)\n+int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva,\n+\t\t\t unsigned long len)\n {\n \tif (!access_ok((void __user *)uhva, len))\n \t\treturn -EINVAL;\n \n-\treturn __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len);\n+\t/* An HVA-based cache never consults the memslots, so never waits. */\n+\treturn __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len, false);\n }\n \n void kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc)\n"
}

2/1 2026/10/15 02:31 agent patch-evaluator
2m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hypercall",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_write_hypercall_page",
    "record_steal_time"
  ],
  "Reasoning": "The patch series addresses deadlock and synchronization issues between KVM guest physical page cache (gfn_to_pfn_cache/GPC) refreshes/activations and kvm-\u003esrcu read sections during memslot updates. It refactors GPC wait/retry behavior, introduces lockdep synchronization assertions (srcu_lock_sync), updates Xen event channel delivery paths and error handling (-EAGAIN vs -EFAULT), modifies steal time TLB flush request sequencing, and adjusts lock scopes in KVM Xen emulation. All changes affect reachable virtualization code that is actively fuzzed via KVM ioctls and guest hypercalls.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit b3aac2f9a3334b2c6c1ecb22b39cbea125204fd6
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 15 02:31:47 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index e0430cc750c9e..b24aac070b119 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -385,8 +385,9 @@ The bits in the dirty bitmap are cleared before the ioctl returns, unless
 KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is enabled.  For more information,
 see the description of the capability.
 
-Note that the Xen shared_info page, if configured, shall always be assumed
-to be dirty. KVM will not explicitly mark it such.
+Note that the Xen shared_info page and vcpu_info area, if configured,
+shall always be assumed to be dirty. KVM will not explicitly mark them
+such.
 
 
 4.10 KVM_RUN
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 3af7395c2430a..6bebc4a79a334 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1108,6 +1108,10 @@ struct kvm_hv {
 #ifdef CONFIG_KVM_XEN
 /* Xen emulation context */
 struct kvm_xen {
+	/*
+	 * Never taken inside a kvm->srcu read section: holders may wait
+	 * out memslot updates (synchronize_srcu).
+	 */
 	struct mutex xen_lock;
 	u32 xen_version;
 	bool long_mode;
diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c
index dd3bb04878ca6..4c0fbba6e7aef 100644
--- a/arch/x86/kvm/msrs.c
+++ b/arch/x86/kvm/msrs.c
@@ -1280,7 +1280,7 @@ static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
 	/* we verify if the enable bit is set... */
 	if (system_time & 1)
 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
-				 sizeof(struct pvclock_vcpu_time_info));
+				 sizeof(struct pvclock_vcpu_time_info), false);
 	else
 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
 
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 79468ddfe4736..20119d07b477b 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -1727,7 +1727,7 @@ static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
 		read_unlock_irqrestore(&gpc->lock, flags);
 
-		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
+		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock), false))
 			return;
 
 		read_lock_irqsave(&gpc->lock, flags);
@@ -2106,8 +2106,22 @@ static void record_steal_time(struct kvm_vcpu *vcpu)
 
 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
 				       st_preempted & KVM_VCPU_FLUSH_TLB);
+		/*
+		 * Request the flush instead of performing it inline. With
+		 * shadow paging kvm_vcpu_flush_tlb_guest() can reschedule (via
+		 * mmu_sync_children()), which is why the user access above has
+		 * to be closed before it. Requesting the flush is just a bit
+		 * set on the running vCPU, and the request is serviced before
+		 * the vCPU enters the guest; nothing requires the flush to
+		 * have completed any earlier than that.
+		 *
+		 * Note the xchg above must remain as-is: it atomically
+		 * consumes any KVM_VCPU_FLUSH_TLB the guest set, as required
+		 * by commit b043138246a4 ("x86/KVM: Make sure
+		 * KVM_VCPU_FLUSH_TLB flag is not missed").
+		 */
 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
-			kvm_vcpu_flush_tlb_guest(vcpu);
+			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
 
 		if (!user_access_begin(st, sizeof(*st)))
 			goto dirty;
@@ -8089,6 +8103,14 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 			if (unlikely(r))
 				goto out;
 		}
+		/*
+		 * Process the steal time update before the TLB flush requests
+		 * are serviced below; record_steal_time() requests
+		 * KVM_REQ_TLB_FLUSH_GUEST on the guest's behalf rather than
+		 * performing the flush itself.
+		 */
+		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
+			record_steal_time(vcpu);
 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
 			kvm_mmu_sync_roots(vcpu);
 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
@@ -8138,8 +8160,6 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 			r = 1;
 			goto out;
 		}
-		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
-			record_steal_time(vcpu);
 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
 			kvm_pmu_handle_event(vcpu);
 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
diff --git a/arch/x86/kvm/xen.c b/arch/x86/kvm/xen.c
index 6aa00f746cba3..e72c0b3d21091 100644
--- a/arch/x86/kvm/xen.c
+++ b/arch/x86/kvm/xen.c
@@ -30,13 +30,14 @@
 #include "cpuid.h"
 #include "trace.h"
 
-static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm);
+static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,
+			      bool wait);
 static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data);
-static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);
+static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);
 
 DEFINE_STATIC_KEY_DEFERRED_FALSE(kvm_xen_enabled, HZ);
 
-static int kvm_xen_shared_info_init(struct kvm *kvm)
+static int kvm_xen_shared_info_init(struct kvm *kvm, bool wait)
 {
 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
 	struct pvclock_wall_clock *wc;
@@ -44,17 +45,24 @@ static int kvm_xen_shared_info_init(struct kvm *kvm)
 	u32 wc_version;
 	u64 wall_nsec;
 	int ret = 0;
-	int idx = srcu_read_lock(&kvm->srcu);
+	int idx;
 
-	read_lock_irq(&gpc->lock);
-	while (!kvm_gpc_check(gpc, PAGE_SIZE)) {
+	/*
+	 * kvm_gpc_check() consults the memslots, so take kvm->srcu around
+	 * each check and the write through the mapping — but not across
+	 * the refresh, which may wait for a memslot update to complete.
+	 */
+	for (;;) {
+		idx = srcu_read_lock(&kvm->srcu);
+		read_lock_irq(&gpc->lock);
+		if (kvm_gpc_check(gpc, PAGE_SIZE))
+			break;
 		read_unlock_irq(&gpc->lock);
+		srcu_read_unlock(&kvm->srcu, idx);
 
-		ret = kvm_gpc_refresh(gpc, PAGE_SIZE);
+		ret = kvm_gpc_refresh(gpc, PAGE_SIZE, wait);
 		if (ret)
 			goto out;
-
-		read_lock_irq(&gpc->lock);
 	}
 
 	/*
@@ -98,9 +106,9 @@ static int kvm_xen_shared_info_init(struct kvm *kvm)
 
 	wc->version = wc_version + 1;
 	read_unlock_irq(&gpc->lock);
+	srcu_read_unlock(&kvm->srcu, idx);
 
 out:
-	srcu_read_unlock(&kvm->srcu, idx);
 	return ret;
 }
 
@@ -108,13 +116,35 @@ void kvm_xen_inject_timer_irqs(struct kvm_vcpu *vcpu)
 {
 	if (atomic_read(&vcpu->arch.xen.timer_pending) > 0) {
 		struct kvm_xen_evtchn e;
+		int rc;
 
 		e.vcpu_id = vcpu->vcpu_id;
 		e.vcpu_idx = vcpu->vcpu_idx;
 		e.port = vcpu->arch.xen.timer_virq;
 		e.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;
 
-		kvm_xen_set_evtchn(&e, vcpu->kvm);
+		rc = kvm_xen_set_evtchn(&e, vcpu->kvm, false);
+
+		/*
+		 * Leave timer_pending set if the memslot is being updated
+		 * (-EAGAIN); delivery is retried on the next entry pass.
+		 */
+		if (rc == -EAGAIN)
+			return;
+
+		/*
+		 * If the event cannot currently be delivered (-EINVAL:
+		 * deactivated shared_info, or an out-of-range port), clear
+		 * timer_pending — a halted vCPU would otherwise spin on
+		 * kvm_cpu_has_pending_timer() — but keep timer_expires,
+		 * which still reports the event as owed through
+		 * KVM_XEN_VCPU_GET_ATTR; re-arming the timer with an expiry
+		 * in the past fires it again.
+		 */
+		if (rc == -EINVAL) {
+			atomic_set(&vcpu->arch.xen.timer_pending, 0);
+			return;
+		}
 
 		vcpu->arch.xen.timer_expires = 0;
 		atomic_set(&vcpu->arch.xen.timer_pending, 0);
@@ -161,7 +191,7 @@ static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,
 	while (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {
 		read_unlock_irqrestore(&gpc->lock, flags);
 
-		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock));
+		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock), false);
 		if (r)
 			return r;
 
@@ -435,7 +465,7 @@ static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)
 		if (atomic)
 			return;
 
-		if (kvm_gpc_refresh(gpc1, user_len1))
+		if (kvm_gpc_refresh(gpc1, user_len1, false))
 			return;
 
 		read_lock_irqsave(&gpc1->lock, flags);
@@ -488,7 +518,7 @@ static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)
 			 * 64-bit mode, the second GPC won't have been set up.
 			 */
 			if (kvm_gpc_activate(gpc2, gpc1->gpa + user_len1,
-					     user_len2))
+					     user_len2, false))
 				return;
 
 			/*
@@ -669,7 +699,7 @@ void kvm_xen_inject_pending_events(struct kvm_vcpu *v)
 	while (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
 		read_unlock_irqrestore(&gpc->lock, flags);
 
-		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info)))
+		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info), false))
 			return;
 
 		read_lock_irqsave(&gpc->lock, flags);
@@ -705,7 +735,6 @@ void kvm_xen_inject_pending_events(struct kvm_vcpu *v)
 		WRITE_ONCE(vi->evtchn_upcall_pending, 1);
 	}
 
-	kvm_gpc_mark_dirty_in_slot(gpc);
 	read_unlock_irqrestore(&gpc->lock, flags);
 
 	/* For the per-vCPU lapic vector, deliver it as MSI. */
@@ -757,7 +786,7 @@ int __kvm_xen_has_interrupt(struct kvm_vcpu *v)
 		if (in_atomic() || !task_is_running(current))
 			return 1;
 
-		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info))) {
+		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info), false)) {
 			/*
 			 * If this failed, userspace has screwed up the
 			 * vcpu_info mapping. No interrupts for you.
@@ -792,19 +821,15 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 			 * to make the call anyway.
 			 */
 			r = kvm->arch.xen.shinfo_cache.active ?
-				kvm_xen_shared_info_init(kvm) : 0;
+				kvm_xen_shared_info_init(kvm, true) : 0;
 			mutex_unlock(&kvm->arch.xen.xen_lock);
 		}
 		break;
 
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO:
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA: {
-		int idx;
-
 		mutex_lock(&kvm->arch.xen.xen_lock);
 
-		idx = srcu_read_lock(&kvm->srcu);
-
 		if (data->type == KVM_XEN_ATTR_TYPE_SHARED_INFO) {
 			gfn_t gfn = data->u.shared_info.gfn;
 
@@ -813,7 +838,7 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 				r = 0;
 			} else {
 				r = kvm_gpc_activate(&kvm->arch.xen.shinfo_cache,
-						     gfn_to_gpa(gfn), PAGE_SIZE);
+						     gfn_to_gpa(gfn), PAGE_SIZE, true);
 			}
 		} else {
 			void __user * hva = u64_to_user_ptr(data->u.shared_info.hva);
@@ -829,10 +854,8 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 			}
 		}
 
-		srcu_read_unlock(&kvm->srcu, idx);
-
 		if (!r && kvm->arch.xen.shinfo_cache.active)
-			r = kvm_xen_shared_info_init(kvm);
+			r = kvm_xen_shared_info_init(kvm, true);
 
 		mutex_unlock(&kvm->arch.xen.xen_lock);
 		break;
@@ -937,7 +960,6 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 	int idx, r = -ENOENT;
 
 	mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
-	idx = srcu_read_lock(&vcpu->kvm->srcu);
 
 	switch (data->type) {
 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO:
@@ -960,7 +982,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 				break;
 
 			r = kvm_gpc_activate(&vcpu->arch.xen.vcpu_info_cache,
-					     data->u.gpa, sizeof(struct vcpu_info));
+					     data->u.gpa, sizeof(struct vcpu_info), true);
 		} else {
 			if (data->u.hva == 0) {
 				kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
@@ -990,7 +1012,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 
 		r = kvm_gpc_activate(&vcpu->arch.xen.vcpu_time_info_cache,
 				     data->u.gpa,
-				     sizeof(struct pvclock_vcpu_time_info));
+				     sizeof(struct pvclock_vcpu_time_info), true);
 		if (!r)
 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
 		break;
@@ -1023,7 +1045,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		/* How much fits in the (first) page? */
 		sz1 = PAGE_SIZE - (data->u.gpa & ~PAGE_MASK);
 		r = kvm_gpc_activate(&vcpu->arch.xen.runstate_cache,
-				     data->u.gpa, sz1);
+				     data->u.gpa, sz1, true);
 		if (r)
 			goto deactivate_out;
 
@@ -1034,12 +1056,14 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			sz2 = sz - sz1;
 			BUG_ON((data->u.gpa + sz1) & ~PAGE_MASK);
 			r = kvm_gpc_activate(&vcpu->arch.xen.runstate2_cache,
-					     data->u.gpa + sz1, sz2);
+					     data->u.gpa + sz1, sz2, true);
 			if (r)
 				goto deactivate_out;
 		}
 
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
 		kvm_xen_update_runstate_guest(vcpu, false);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 		break;
 	}
 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT:
@@ -1052,7 +1076,9 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			break;
 		}
 
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
 		kvm_xen_update_runstate(vcpu, data->u.runstate.state);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 		r = 0;
 		break;
 
@@ -1132,10 +1158,12 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		vcpu->arch.xen.runstate_times[RUNSTATE_offline] +=
 			data->u.runstate.time_offline;
 
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
 		if (data->u.runstate.state <= RUNSTATE_offline)
 			kvm_xen_update_runstate(vcpu, data->u.runstate.state);
 		else if (vcpu->arch.xen.runstate_cache.active)
 			kvm_xen_update_runstate_guest(vcpu, false);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 		r = 0;
 		break;
 
@@ -1181,7 +1209,6 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		break;
 	}
 
-	srcu_read_unlock(&vcpu->kvm->srcu, idx);
 	mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 	return r;
 }
@@ -1267,12 +1294,13 @@ int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 
 	case KVM_XEN_VCPU_ATTR_TYPE_TIMER:
 		/*
-		 * Ensure a consistent snapshot of state is captured, with a
-		 * timer either being pending, or the event channel delivered
-		 * to the corresponding bit in the shared_info. Not still
-		 * lurking in the timer_pending flag for deferred delivery.
-		 * Purely as an optimisation, if the timer_expires field is
-		 * zero, that means the timer isn't active (or even in the
+		 * Ensure a consistent snapshot of state is captured: a timer
+		 * which already fired has either been delivered to the
+		 * corresponding bit in the shared_info, or is reported as
+		 * still owed (expires_ns != 0, if the shared_info page was
+		 * unavailable). Purely
+		 * as an optimisation, if the timer_expires field is zero,
+		 * that means the timer isn't active (or even in the
 		 * timer_pending flag) and there is no need to cancel it.
 		 */
 		if (vcpu->arch.xen.timer_expires) {
@@ -1291,8 +1319,20 @@ int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		 * That's fine, as the guest won't even have had a chance
 		 * to run and handle the interrupt. Asserting an already
 		 * pending event channel is idempotent.
+		 *
+		 * Don't re-arm if the flush above failed transiently and
+		 * left the timer pending: delivery is owned by the retry
+		 * on the guest entry path, and an immediate hrtimer fire
+		 * would race it — the callback's timer_pending suppression
+		 * check is not serialized against the entry path, so a
+		 * late callback could re-assert a port the entry path had
+		 * already delivered and the guest already consumed.
+		 *
+		 * An expiry already in the past fires immediately: the
+		 * event is still owed.
 		 */
-		if (vcpu->arch.xen.timer_expires)
+		if (vcpu->arch.xen.timer_expires &&
+		    !atomic_read(&vcpu->arch.xen.timer_pending))
 			hrtimer_start_expires(&vcpu->arch.xen.timer,
 					      HRTIMER_MODE_ABS_HARD);
 
@@ -1320,7 +1360,15 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
 	bool lm = is_long_mode(vcpu);
 	int r = 0;
 
+	/*
+	 * The attribute ioctls wait out memslot updates while holding
+	 * xen_lock; a memslot update waits for this vCPU's kvm->srcu
+	 * read section to quiesce. Blocking on xen_lock inside that
+	 * read section would close the cycle, so step out of it first.
+	 */
+	kvm_vcpu_srcu_read_unlock(vcpu);
 	mutex_lock(&kvm->arch.xen.xen_lock);
+	kvm_vcpu_srcu_read_lock(vcpu);
 	if (kvm->arch.xen.long_mode != lm) {
 		kvm->arch.xen.long_mode = lm;
 
@@ -1329,7 +1377,7 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
 		 * correct place.
 		 */
 		if (kvm->arch.xen.shinfo_cache.active &&
-		    kvm_xen_shared_info_init(kvm))
+		    kvm_xen_shared_info_init(kvm, false))
 			r = 1;
 	}
 	mutex_unlock(&kvm->arch.xen.xen_lock);
@@ -1775,8 +1823,21 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
 		}
 		break;
 	case __HYPERVISOR_event_channel_op:
-		if (params[0] == EVTCHNOP_send)
-			handled = kvm_xen_hcall_evtchn_send(vcpu, params[1], &r);
+		if (params[0] == EVTCHNOP_send) {
+			int ret = kvm_xen_hcall_evtchn_send(vcpu, params[1], &r);
+
+			/*
+			 * Delivery raced a memslot update; waiting for it
+			 * here would deadlock under vcpu_run's kvm->srcu
+			 * read section. Leave the hypercall uncompleted —
+			 * RIP not advanced — so the guest re-executes it.
+			 * Each attempt cycles the srcu read section on the
+			 * way back in, letting the update complete.
+			 */
+			if (ret == -EAGAIN)
+				return 1;
+			handled = !ret;
+		}
 		break;
 	case __HYPERVISOR_sched_op:
 		handled = kvm_xen_hcall_sched_op(vcpu, is_64bit, params[0],
@@ -1831,6 +1892,89 @@ static void kvm_xen_check_poller(struct kvm_vcpu *vcpu, int port)
 	}
 }
 
+static void __kvm_xen_set_evtchn_fast(struct kvm_vcpu *vcpu, int port_word_bit,
+				      bool has_64bit_shinfo)
+{
+	struct gfn_to_pfn_cache *gpc = &vcpu->arch.xen.vcpu_info_cache;
+	unsigned long vi_pending_sel_ofs;
+	bool inject_upcall = false;
+	bool kick_vcpu = false;
+	unsigned long flags;
+	bool old;
+
+	vi_pending_sel_ofs = has_64bit_shinfo ?
+		offsetof(struct vcpu_info, evtchn_pending_sel) :
+		offsetof(struct compat_vcpu_info, evtchn_pending_sel);
+
+	/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */
+	read_lock_irqsave(&gpc->lock, flags);
+	if (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
+		/*
+		 * Could not access the vcpu_info. Set the bit in-kernel and
+		 * prod the vCPU to deliver it for itself. Note that an MSI is
+		 * *not* an acceptable substitute here even if the vCPU has an
+		 * upcall vector: the pending bit only exists in
+		 * evtchn_pending_sel so far, and the vCPU has to be forced
+		 * out of the guest so that kvm_xen_inject_pending_events()
+		 * can refresh the cache and propagate it to the guest.
+		 */
+		if (!test_and_set_bit(port_word_bit, &vcpu->arch.xen.evtchn_pending_sel))
+			kick_vcpu = true;
+		goto out_unlock;
+	}
+	inject_upcall = true;
+
+	/*
+	 * Explicitly use a 32-bit btsl instead of test_and_set_bit(), which
+	 * would use btsq on x86-64. The vcpu_info is guest-controlled and only
+	 * required to be 32-bit aligned, so a 64-bit access could generate a
+	 * split-lock #AC.
+	 *
+	 * Note, this does not apply to the test_and_set_bit() on pending_bits
+	 * in the caller: that is in the per-VM shared_info, which is page
+	 * aligned, so the access is guaranteed to be 64-bit aligned.
+	 */
+	old = GEN_BINARY_RMWcc(LOCK_PREFIX "btsl",
+			       *(u32 *)(gpc->khva + vi_pending_sel_ofs),
+			       c, "Ir", port_word_bit);
+	if (!old) {
+		struct vcpu_info *vi = gpc->khva;
+
+		/* No need for compat handling */
+		BUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=
+			     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));
+
+		WRITE_ONCE(vi->evtchn_upcall_pending, 1);
+		kick_vcpu = true;
+	}
+
+out_unlock:
+	read_unlock_irqrestore(&gpc->lock, flags);
+
+	/*
+	 * Deliver the upcall or kick the vCPU only after dropping the GPC
+	 * read lock. Both paths end up in kvm_vcpu_kick(), and the MSI
+	 * delivery also walks the APIC map and takes APIC locks; none of
+	 * that wants to be nested inside the GPC read lock, which a
+	 * concurrent invalidation may be waiting to take for write.
+	 */
+	if (!kick_vcpu)
+		return;
+
+	/*
+	 * For the per-vCPU lapic vector, deliver it as MSI — but only if the
+	 * vcpu_info was actually updated above. If it wasn't, the vCPU must
+	 * be kicked instead (see above).
+	 */
+	if (inject_upcall && vcpu->arch.xen.upcall_vector) {
+		kvm_xen_inject_vcpu_vector(vcpu);
+		return;
+	}
+
+	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
+	kvm_vcpu_kick(vcpu);
+}
+
 /*
  * The return value from this function is propagated to kvm_set_irq() API,
  * so it returns:
@@ -1845,11 +1989,10 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 {
 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
 	bool has_64bit_shinfo = kvm_xen_has_64bit_shinfo(kvm);
-	unsigned long *pending_bits, *mask_bits, vi_pending_sel_ofs;
+	unsigned long *pending_bits, *mask_bits;
 	struct kvm_vcpu *vcpu;
 	unsigned long flags;
 	int port_word_bit;
-	bool kick_vcpu = false;
 	int vcpu_idx, idx, rc;
 
 	vcpu_idx = READ_ONCE(xe->vcpu_idx);
@@ -1871,23 +2014,19 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 
 	read_lock_irqsave(&gpc->lock, flags);
 	if (!kvm_gpc_check(gpc, PAGE_SIZE))
-		goto out_rcu;
+		goto out_unlock;
 
 	if (has_64bit_shinfo) {
 		struct shared_info *shinfo = gpc->khva;
 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
 		mask_bits = (unsigned long *)&shinfo->evtchn_mask;
 		port_word_bit = xe->port / 64;
-
-		vi_pending_sel_ofs = offsetof(struct vcpu_info, evtchn_pending_sel);
 	} else {
 		struct compat_shared_info *shinfo = gpc->khva;
 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
 		mask_bits = (unsigned long *)&shinfo->evtchn_mask;
 		port_word_bit = xe->port / 32;
 
-		vi_pending_sel_ofs = offsetof(struct compat_vcpu_info, evtchn_pending_sel);
-
 		/* test_and_set_bit() needs 64-bit alignment, but that's OK */
 		BUILD_BUG_ON(offsetof(struct compat_shared_info, evtchn_pending) & 7);
 	}
@@ -1903,71 +2042,30 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 		rc = 0; /* It was already raised */
 	} else if (test_bit(xe->port, mask_bits)) {
 		rc = -ENOTCONN; /* Masked */
-		kvm_xen_check_poller(vcpu, xe->port);
 	} else {
-		bool old;
-
 		rc = 1; /* Delivered to the bitmap in shared_info. */
-		/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */
-		read_unlock_irqrestore(&gpc->lock, flags);
-		gpc = &vcpu->arch.xen.vcpu_info_cache;
-
-		read_lock_irqsave(&gpc->lock, flags);
-		if (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
-			/*
-			 * Could not access the vcpu_info. Set the bit in-kernel
-			 * and prod the vCPU to deliver it for itself.
-			 */
-			if (!test_and_set_bit(port_word_bit, &vcpu->arch.xen.evtchn_pending_sel))
-				kick_vcpu = true;
-			goto out_rcu;
-		}
-
-		/*
-		 * Explicitly use a 32-bit btsl instead of test_and_set_bit(),
-		 * which would use btsq on x86-64. The vcpu_info is guest-
-		 * controlled and only required to be 32-bit aligned, so a
-		 * 64-bit access could generate a split-lock #AC.
-		 *
-		 * Note, this does not apply to the test_and_set_bit() on
-		 * pending_bits above: that is in the per-VM shared_info, which
-		 * is page aligned, so the access is guaranteed to be 64-bit
-		 * aligned.
-		 */
-		old = GEN_BINARY_RMWcc(LOCK_PREFIX "btsl",
-				       *(u32 *)(gpc->khva + vi_pending_sel_ofs),
-				       c, "Ir", port_word_bit);
-		if (!old) {
-			struct vcpu_info *vi = gpc->khva;
-
-			/* No need for compat handling */
-			BUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=
-				     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));
-
-			WRITE_ONCE(vi->evtchn_upcall_pending, 1);
-			kick_vcpu = true;
-		}
-
-		/* For the per-vCPU lapic vector, deliver it as MSI. */
-		if (kick_vcpu && vcpu->arch.xen.upcall_vector) {
-			kvm_xen_inject_vcpu_vector(vcpu);
-			kick_vcpu = false;
-		}
 	}
 
- out_rcu:
+ out_unlock:
 	read_unlock_irqrestore(&gpc->lock, flags);
-	srcu_read_unlock(&kvm->srcu, idx);
 
-	if (kick_vcpu) {
-		kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
-		kvm_vcpu_kick(vcpu);
-	}
+	/*
+	 * Both of these can kick the vCPU, so keep them outside the GPC
+	 * read lock; an invalidation may be waiting to take it for write.
+	 */
+	if (rc == -ENOTCONN)
+		kvm_xen_check_poller(vcpu, xe->port);
+	else if (rc == 1)
+		__kvm_xen_set_evtchn_fast(vcpu, port_word_bit,
+					  has_64bit_shinfo);
+
+	srcu_read_unlock(&kvm->srcu, idx);
 
 	return rc;
 }
 
-static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
+static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,
+			      bool wait)
 {
 	bool mm_borrowed = false;
 	int rc;
@@ -2004,16 +2102,13 @@ static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 	 */
 	do {
 		struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
-		int idx;
 
 		rc = kvm_xen_set_evtchn_fast(xe, kvm);
 		if (rc != -EWOULDBLOCK)
 			break;
 
-		idx = srcu_read_lock(&kvm->srcu);
-		rc = kvm_gpc_refresh(gpc, PAGE_SIZE);
-		srcu_read_unlock(&kvm->srcu, idx);
-	} while(!rc);
+		rc = kvm_gpc_refresh(gpc, PAGE_SIZE, wait);
+	} while (!rc);
 
 	if (mm_borrowed)
 		kthread_unuse_mm(kvm->mm);
@@ -2028,7 +2123,7 @@ static int evtchn_set_fn(struct kvm_kernel_irq_routing_entry *e, struct kvm *kvm
 	if (!level)
 		return -EINVAL;
 
-	return kvm_xen_set_evtchn(&e->xen_evtchn, kvm);
+	return kvm_xen_set_evtchn(&e->xen_evtchn, kvm, true);
 }
 
 /*
@@ -2102,7 +2197,7 @@ int kvm_xen_hvm_evtchn_send(struct kvm *kvm, struct kvm_irq_routing_xen_evtchn *
 	e.vcpu_idx = -1;
 	e.priority = uxe->priority;
 
-	ret = kvm_xen_set_evtchn(&e, kvm);
+	ret = kvm_xen_set_evtchn(&e, kvm, true);
 
 	/*
 	 * None of that 'return 1 if it actually got delivered' nonsense.
@@ -2331,7 +2426,11 @@ static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data
 	return kvm_xen_eventfd_assign(kvm, data);
 }
 
-static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
+/*
+ * Returns 0 with *r set if handled, -EAGAIN if the hypercall should be
+ * re-executed by the guest, or -ENOENT to hand it to userspace.
+ */
+static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
 {
 	struct evtchnfd *evtchnfd;
 	struct evtchn_send send;
@@ -2341,7 +2440,7 @@ static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
 	BUILD_BUG_ON(sizeof(send) != 4);
 	if (kvm_read_guest_virt(vcpu, param, &send, sizeof(send), &e)) {
 		*r = -EFAULT;
-		return true;
+		return 0;
 	}
 
 	/*
@@ -2350,18 +2449,22 @@ static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
 	 */
 	evtchnfd = xa_load(&vcpu->kvm->arch.xen.evtchn_ports, send.port);
 	if (!evtchnfd)
-		return false;
+		return -ENOENT;
 
 	if (evtchnfd->deliver.port.port) {
-		int ret = kvm_xen_set_evtchn(&evtchnfd->deliver.port, vcpu->kvm);
+		int ret = kvm_xen_set_evtchn(&evtchnfd->deliver.port,
+					     vcpu->kvm, false);
+
+		if (ret == -EAGAIN)
+			return ret;
 		if (ret < 0 && ret != -ENOTCONN)
-			return false;
+			return -ENOENT;
 	} else {
 		eventfd_signal(evtchnfd->deliver.eventfd.ctx);
 	}
 
 	*r = 0;
-	return true;
+	return 0;
 }
 
 void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)
@@ -2375,7 +2478,7 @@ void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)
 
 	kvm_gpc_init(&vcpu->arch.xen.runstate_cache, vcpu->kvm);
 	kvm_gpc_init(&vcpu->arch.xen.runstate2_cache, vcpu->kvm);
-	kvm_gpc_init(&vcpu->arch.xen.vcpu_info_cache, vcpu->kvm);
+	__kvm_gpc_init(&vcpu->arch.xen.vcpu_info_cache, vcpu->kvm, true);
 	kvm_gpc_init(&vcpu->arch.xen.vcpu_time_info_cache, vcpu->kvm);
 }
 
@@ -2396,7 +2499,7 @@ void kvm_xen_init_vm(struct kvm *kvm)
 {
 	mutex_init(&kvm->arch.xen.xen_lock);
 	xa_init(&kvm->arch.xen.evtchn_ports);
-	kvm_gpc_init(&kvm->arch.xen.shinfo_cache, kvm);
+	__kvm_gpc_init(&kvm->arch.xen.shinfo_cache, kvm, true);
 }
 
 void kvm_xen_destroy_vm(struct kvm *kvm)
diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
index 3dd04605f2e55..debce84f4177c 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -1465,7 +1465,13 @@ int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by
  * the caller before init).
  */
-void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);
+void __kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm,
+		    bool never_dirty);
+
+static inline void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)
+{
+	__kvm_gpc_init(gpc, kvm, false);
+}
 
 /**
  * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest
@@ -1474,16 +1480,24 @@ void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);
  * @gpc:	   struct gfn_to_pfn_cache object.
  * @gpa:	   guest physical address to map.
  * @len:	   sanity check; the range being access must fit a single page.
+ * @wait:	   wait out a concurrent memslot update instead of returning
+ *		   -EAGAIN. May not be used while this task holds any kvm->srcu
+ *		   read section, and no lock held across the wait may ever be
+ *		   taken within one: the update's synchronize_srcu() would
+ *		   deadlock against the wait. Lockdep checks both.
  *
  * @return:	   0 for success.
  *		   -EINVAL for a mapping which would cross a page boundary.
  *		   -EFAULT for an untranslatable guest physical address.
+ *		   -EAGAIN if the memslot is being updated (only with
+ *		   wait == false, or on a fatal signal while waiting).
  *
  * This primes a gfn_to_pfn_cache and links it into the @gpc->kvm's list for
  * invalidations to be processed.  Callers are required to use kvm_gpc_check()
  * to ensure that the cache is valid before accessing the target page.
  */
-int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len);
+int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len,
+		     bool wait);
 
 /**
  * kvm_gpc_activate_hva - prepare a cached kernel mapping and HPA for a given HVA.
@@ -1499,7 +1513,8 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
  * The semantics of this function are the same as those of kvm_gpc_activate(). It
  * merely bypasses a layer of address translation.
  */
-int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva, unsigned long len);
+int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva,
+			 unsigned long len);
 
 /**
  * kvm_gpc_check - check validity of a gfn_to_pfn_cache.
@@ -1524,10 +1539,13 @@ bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);
  *
  * @gpc:	   struct gfn_to_pfn_cache object.
  * @len:	   sanity check; the range being access must fit a single page.
+ * @wait:	   as kvm_gpc_activate().
  *
  * @return:	   0 for success.
  *		   -EINVAL for a mapping which would cross a page boundary.
  *		   -EFAULT for an untranslatable guest physical address.
+ *		   -EAGAIN if the memslot is being updated (only with
+ *		   wait == false, or on a fatal signal while waiting).
  *
  * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful
  * return from this function does not mean the page can be immediately
@@ -1535,7 +1553,7 @@ bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);
  * still lock and check the cache status, as this function does not return
  * with the lock still held to permit access.
  */
-int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len);
+int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait);
 
 /**
  * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache.
@@ -1976,7 +1994,7 @@ static inline void kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache *gpc)
 {
 	lockdep_assert_held(&gpc->lock);
 
-	if (!gpc->memslot)
+	if (!gpc->memslot || gpc->never_dirty)
 		return;
 
 	mark_page_dirty_in_slot(gpc->kvm, gpc->memslot, gpa_to_gfn(gpc->gpa));
diff --git a/include/linux/kvm_types.h b/include/linux/kvm_types.h
index a568d8e6f4e82..e850adc3f47ef 100644
--- a/include/linux/kvm_types.h
+++ b/include/linux/kvm_types.h
@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {
 	kvm_pfn_t pfn;
 	bool active;
 	bool valid;
+	bool never_dirty;
 };
 
 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 96bab7002d39e..e7e17d19d6cbb 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -144,6 +144,7 @@ TEST_GEN_PROGS_x86 += x86/xss_msr_test
 TEST_GEN_PROGS_x86 += x86/debug_regs
 TEST_GEN_PROGS_x86 += x86/tsc_msrs_test
 TEST_GEN_PROGS_x86 += x86/vmx_pmu_caps_test
+TEST_GEN_PROGS_x86 += x86/xen_evtchn_memslot_race_test
 TEST_GEN_PROGS_x86 += x86/xen_shinfo_test
 TEST_GEN_PROGS_x86 += x86/xen_vmcall_test
 TEST_GEN_PROGS_x86 += x86/sev_dbg_test
diff --git a/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c b/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c
new file mode 100644
index 0000000000000..2b6974d3d4645
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * xen_evtchn_memslot_race_test
+ *
+ * A guest EVTCHNOP_send whose delivery races a DELETE/re-CREATE of the
+ * memslot holding the shared_info page. The delivery path runs in the
+ * vCPU's exit-handling context, under vcpu_run's kvm->srcu read
+ * section; if it waits there for the memslot update to complete, it
+ * deadlocks against kvm_swap_active_memslots()'s
+ * synchronize_srcu_expedited() waiting out that very read section.
+ * Regression test for that deadlock: KVM must defer the delivery to
+ * the next guest entry rather than spin in exit context.
+ *
+ * The guest sends events in a tight loop; a host thread deletes and
+ * recreates the shared_info slot in a tight loop. On a broken host
+ * this livelocks within a second or two (the test then dies by
+ * timeout); on a fixed host every send eventually delivers and the
+ * test completes N iterations.
+ */
+#include <pthread.h>
+#include <stdatomic.h>
+
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+
+#include <stdint.h>
+
+#define SHINFO_REGION_GPA	0xc0000000ULL
+#define SHINFO_REGION_SLOT	10
+
+#define EVTCHN_PORT		15
+#define TEST_ITERATIONS		4000
+
+#define EVTCHNOP_send		4
+#define __HYPERVISOR_event_channel_op	32
+
+#define XEN_HYPERCALL_MSR	0x40000000
+
+#define EVTCHNSTAT_ipi		5
+
+struct evtchn_send {
+	uint32_t port;
+};
+
+static void guest_code(void)
+{
+	struct evtchn_send s = { .port = EVTCHN_PORT };
+	int i;
+
+	for (i = 0; i < TEST_ITERATIONS; i++) {
+		/*
+		 * The delivery may legitimately fail while the shared_info
+		 * slot is mid-churn (between DELETE and re-CREATE there is
+		 * no slot at all, which is -EFAULT, not a transient). The
+		 * failure mode under test is the vCPU never coming back at
+		 * all (deadlock -> timeout), not the hypercall rc.
+		 */
+		__xen_hypercall(__HYPERVISOR_event_channel_op, EVTCHNOP_send, &s);
+		GUEST_SYNC(i);
+	}
+
+	GUEST_DONE();
+}
+
+static atomic_bool churn_stop;
+
+static void *memslot_churn(void *arg)
+{
+	struct kvm_vm *vm = arg;
+
+	while (!atomic_load(&churn_stop)) {
+		vm_mem_region_delete(vm, SHINFO_REGION_SLOT);
+		vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
+					    SHINFO_REGION_GPA,
+					    SHINFO_REGION_SLOT, 2, 0);
+	}
+	return NULL;
+}
+
+int main(int argc, char *argv[])
+{
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	pthread_t thread;
+	struct ucall uc;
+	int done = 0;
+	int r;
+
+	int xen_caps = kvm_check_cap(KVM_CAP_XEN_HVM);
+
+	TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_SHARED_INFO);
+	TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_EVTCHN_SEND);
+
+	vm = vm_create_with_one_vcpu(&vcpu, guest_code);
+
+	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
+				    SHINFO_REGION_GPA, SHINFO_REGION_SLOT, 2, 0);
+
+	struct kvm_xen_hvm_config hvmc = {
+		.flags = KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
+			 KVM_XEN_HVM_CONFIG_EVTCHN_SEND,
+		.msr = XEN_HYPERCALL_MSR,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_CONFIG, &hvmc);
+
+	struct kvm_xen_hvm_attr lm = {
+		.type = KVM_XEN_ATTR_TYPE_LONG_MODE,
+		.u.long_mode = 1,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &lm);
+
+	struct kvm_xen_hvm_attr ha = {
+		.type = KVM_XEN_ATTR_TYPE_SHARED_INFO,
+		.u.shared_info.gfn = SHINFO_REGION_GPA / PAGE_SIZE,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &ha);
+
+	struct kvm_xen_vcpu_attr vi = {
+		.type = KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO,
+		.u.gpa = SHINFO_REGION_GPA + 0x40,
+	};
+	vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &vi);
+
+	/* Loop the port back to this vCPU as an IPI. */
+	struct kvm_xen_hvm_attr evt = {
+		.type = KVM_XEN_ATTR_TYPE_EVTCHN,
+		.u.evtchn.send_port = EVTCHN_PORT,
+		.u.evtchn.type = EVTCHNSTAT_ipi,
+		.u.evtchn.flags = 0,
+		.u.evtchn.deliver.port.port = EVTCHN_PORT,
+		.u.evtchn.deliver.port.vcpu = vcpu->id,
+		.u.evtchn.deliver.port.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &evt);
+
+	r = pthread_create(&thread, NULL, memslot_churn, vm);
+	TEST_ASSERT(!r, "pthread_create() failed: %d", r);
+
+	while (!done) {
+		vcpu_run(vcpu);
+
+		/*
+		 * In the window where the shared_info slot is fully deleted
+		 * (between the churn thread's DELETE and re-CREATE), the
+		 * delivery fails with -EFAULT and the hypercall bounces to
+		 * userspace as KVM_EXIT_XEN. Complete it with an error
+		 * result and keep going; the failure mode under test is
+		 * the vCPU never coming back (deadlock -> timeout), not
+		 * the hypercall rc.
+		 */
+		if (vcpu->run->exit_reason == KVM_EXIT_XEN &&
+		    vcpu->run->xen.type == KVM_EXIT_XEN_HCALL) {
+			vcpu->run->xen.u.hcall.result = -EFAULT;
+			continue;
+		}
+
+		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+		switch (get_ucall(vcpu, &uc)) {
+		case UCALL_SYNC:
+			break;
+		case UCALL_DONE:
+			done = 1;
+			break;
+		case UCALL_ABORT:
+			REPORT_GUEST_ASSERT(uc);
+		default:
+			TEST_FAIL("Unexpected ucall %lu", uc.cmd);
+		}
+	}
+
+	atomic_store(&churn_stop, true);
+	pthread_join(thread, NULL);
+
+	kvm_vm_free(vm);
+	return 0;
+}
diff --git a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
index aaa414c677add..3b11d0ee253f5 100644
--- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
+++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
@@ -356,11 +356,12 @@ static void guest_code(void)
 wait_for_timer:
 	/*
 	 * Poll for a timer wake event while the worker thread is mucking with
-	 * the shared info.  KVM XEN drops timer IRQs if the shared info is
-	 * invalid when the timer expires.  Arbitrarily poll 100 times before
-	 * giving up and asking the VMM to re-arm the timer.  100 polls should
-	 * consume enough time to beat on KVM without taking too long if the
-	 * timer IRQ is dropped due to an invalid event channel.
+	 * the shared info.  KVM is now supposed to retry a timer IRQ whose
+	 * delivery hit an invalid shared info rather than drop it, but older
+	 * kernels drop it on the floor.  Arbitrarily poll 100 times before
+	 * giving up and asking the VMM to re-arm the timer, so the test still
+	 * completes (and documents the VMM-side recovery protocol) on
+	 * unfixed kernels.
 	 */
 	for (i = 0; i < 100 && !guest_saw_irq; i++)
 		__xen_hypercall(__HYPERVISOR_sched_op, SCHEDOP_poll, &p);
diff --git a/virt/kvm/pfncache.c b/virt/kvm/pfncache.c
index 3659686b97c24..8498abb746ade 100644
--- a/virt/kvm/pfncache.c
+++ b/virt/kvm/pfncache.c
@@ -304,7 +304,22 @@ static int __kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned l
 			gpc->uhva = gfn_to_hva_memslot(gpc->memslot, gfn);
 
 			if (kvm_is_error_hva(gpc->uhva)) {
-				ret = -EFAULT;
+				/*
+				 * A slot being deleted or moved is present
+				 * but flagged invalid; the lookup failure is
+				 * transient, resolved when the update
+				 * completes (or reverts) and announced by a
+				 * new memslot generation. Distinguish that
+				 * from a genuinely unbacked gfn so that the
+				 * caller may retry rather than report an
+				 * error, as RET_PF_RETRY does for ordinary
+				 * guest faults.
+				 */
+				if (gpc->memslot &&
+				    (gpc->memslot->flags & KVM_MEMSLOT_INVALID))
+					ret = -EAGAIN;
+				else
+					ret = -EFAULT;
 				goto out;
 			}
 
@@ -363,26 +378,67 @@ static int __kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned l
 	return ret;
 }
 
-int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len)
+/*
+ * One refresh attempt, under the caller's refresh_lock. Takes a kvm->srcu
+ * read section for the attempt, as the memslot lookups consult the active
+ * memslots.
+ */
+static int gpc_refresh_locked(struct gfn_to_pfn_cache *gpc, gpa_t gpa,
+			      unsigned long uhva)
 {
-	unsigned long uhva;
+	int idx, ret;
 
-	guard(mutex)(&gpc->refresh_lock);
+	idx = srcu_read_lock(&gpc->kvm->srcu);
+	ret = __kvm_gpc_refresh(gpc, gpa, uhva);
+	srcu_read_unlock(&gpc->kvm->srcu, idx);
 
-	if (!kvm_gpc_is_valid_len(gpc->gpa, gpc->uhva, len))
-		return -EINVAL;
+	return ret;
+}
+
+int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait)
+{
+	unsigned long uhva;
+	int ret;
 
 	/*
-	 * If the GPA is valid then ignore the HVA, as a cache can be GPA-based
-	 * or HVA-based, not both.  For GPA-based caches, the HVA will be
-	 * recomputed during refresh if necessary.
+	 * The wait completes only after a memslot update's
+	 * synchronize_srcu(&kvm->srcu), so it functions as one for lockdep:
+	 * taking any lock held across it within a kvm->srcu read section
+	 * is reported as the deadlock it would be.
 	 */
-	uhva = kvm_is_error_gpa(gpc->gpa) ? gpc->uhva : KVM_HVA_ERR_BAD;
+	if (wait)
+		srcu_lock_sync(&gpc->kvm->srcu.dep_map);
+
+	for (;;) {
+		scoped_guard(mutex, &gpc->refresh_lock) {
+			if (!kvm_gpc_is_valid_len(gpc->gpa, gpc->uhva, len))
+				return -EINVAL;
 
-	return __kvm_gpc_refresh(gpc, gpc->gpa, uhva);
+			/*
+			 * If the GPA is valid then ignore the HVA, as a cache
+			 * can be GPA-based or HVA-based, not both.  For
+			 * GPA-based caches, the HVA will be recomputed during
+			 * refresh if necessary.
+			 */
+			uhva = kvm_is_error_gpa(gpc->gpa) ? gpc->uhva : KVM_HVA_ERR_BAD;
+
+			ret = gpc_refresh_locked(gpc, gpc->gpa, uhva);
+		}
+
+		if (ret != -EAGAIN || !wait || fatal_signal_pending(current))
+			return ret;
+
+		/*
+		 * Wait with refresh_lock dropped: a kvm->srcu reader blocked
+		 * on it must be able to proceed and quiesce, or the memslot
+		 * update being waited for could never complete.
+		 */
+		cond_resched();
+	}
 }
 
-void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)
+void __kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm,
+		    bool never_dirty)
 {
 	rwlock_init(&gpc->lock);
 	mutex_init(&gpc->refresh_lock);
@@ -392,39 +448,55 @@ void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)
 	gpc->gpa = INVALID_GPA;
 	gpc->uhva = KVM_HVA_ERR_BAD;
 	gpc->active = gpc->valid = false;
+	gpc->never_dirty = never_dirty;
 }
 
 static int __kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long uhva,
-			      unsigned long len)
+			      unsigned long len, bool wait)
 {
 	struct kvm *kvm = gpc->kvm;
 
 	if (!kvm_gpc_is_valid_len(gpa, uhva, len))
 		return -EINVAL;
 
-	guard(mutex)(&gpc->refresh_lock);
-
-	if (!gpc->active) {
-		if (KVM_BUG_ON(gpc->valid, kvm))
-			return -EIO;
+	/* As in kvm_gpc_refresh(): the wait is a synchronize_srcu() to lockdep. */
+	if (wait)
+		srcu_lock_sync(&kvm->srcu.dep_map);
+
+	for (;;) {
+		int ret;
+
+		scoped_guard(mutex, &gpc->refresh_lock) {
+			if (!gpc->active) {
+				if (KVM_BUG_ON(gpc->valid, kvm))
+					return -EIO;
+
+				spin_lock(&kvm->gpc_lock);
+				list_add(&gpc->list, &kvm->gpc_list);
+				spin_unlock(&kvm->gpc_lock);
+
+				/*
+				 * Activate the cache after adding it to the
+				 * list, a concurrent refresh must not
+				 * establish a mapping until the cache is
+				 * reachable by mmu_notifier events.
+				 */
+				write_lock_irq(&gpc->lock);
+				gpc->active = true;
+				write_unlock_irq(&gpc->lock);
+			}
+			ret = gpc_refresh_locked(gpc, gpa, uhva);
+		}
 
-		spin_lock(&kvm->gpc_lock);
-		list_add(&gpc->list, &kvm->gpc_list);
-		spin_unlock(&kvm->gpc_lock);
+		if (ret != -EAGAIN || !wait || fatal_signal_pending(current))
+			return ret;
 
-		/*
-		 * Activate the cache after adding it to the list, a concurrent
-		 * refresh must not establish a mapping until the cache is
-		 * reachable by mmu_notifier events.
-		 */
-		write_lock_irq(&gpc->lock);
-		gpc->active = true;
-		write_unlock_irq(&gpc->lock);
+		cond_resched();
 	}
-	return __kvm_gpc_refresh(gpc, gpa, uhva);
 }
 
-int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
+int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len,
+		     bool wait)
 {
 	/*
 	 * Explicitly disallow INVALID_GPA so that the magic value can be used
@@ -433,15 +505,17 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
 	if (WARN_ON_ONCE(kvm_is_error_gpa(gpa)))
 		return -EINVAL;
 
-	return __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len);
+	return __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len, wait);
 }
 
-int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva, unsigned long len)
+int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva,
+			 unsigned long len)
 {
 	if (!access_ok((void __user *)uhva, len))
 		return -EINVAL;
 
-	return __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len);
+	/* An HVA-based cache never consults the memslots, so never waits. */
+	return __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len, false);
 }
 
 void kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc)

3/2 2026/10/15 02:31 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22198
							output: 37
							thoughts: 898
						

Thoughts:
**KVM Patch Series Evaluation**

Okay, so I'm looking at this patch series applied at HEAD. My primary concern is whether this warrants fuzzing, and if so, to what extent. Let's break this down systematically.

First, I need to understand the scope of the changes. The files touched are: `Documentation/virt/kvm/api.rst`, several `arch/x86/kvm/*` files, a couple of `include/linux/*` files, some selftests, and `virt/kvm/pfncache.c`. This is all KVM territory, specifically the gfn_to_pfn cache, Xen emulation on x86, steal time/pvclock, etc.

Now, KVM is a known target for syzkaller. I know it's a heavily fuzzed in-tree hypervisor module. We have access via `/dev/kvm` and ioctls like `KVM_RUN`, `KVM_SET_USER_MEMORY_REGION`, `KVM_XEN_HVM_SET_ATTR`, `KVM_XEN_VCPU_SET_ATTR`, and Xen hypercalls. So, my initial thought is that it should be reachable in a standard QEMU environment, especially with nested virtualization enabled or when targeting KVM ioctls.

Let me quickly review the fuzzing guidelines. The core philosophy is to identify crashes, regressions, exposed latent bugs, and new assertions. Reachability is the crucial gatekeeper. If the code isn't reachable in standard virtualized environments, we shouldn't waste our time. The guidelines emphasize that we need to fuzz new or modified assertions in reachable code, refactorings of reachable data structures, and anything that touches core subsystems or reachable drivers.

Considering the patch changes, KVM is absolutely reachable, right? Syzkaller fuzzes KVM all the time. There are dedicated descriptions in `syzkaller/sys/linux/kvm.txt`, `kvm_amd.txt`, `kvm_intel.txt`, `kvm_x86.txt`. And this includes Xen emulation within KVM x86, too.

So, yes, it's worth fuzzing. I'll need to dig into the changes themselves using grep and by reading the code to determine the degree of risk. But based on this initial assessment, I'm confident that these patches are potentially introducing changes that could be worth fuzzing.



4/2 2026/10/15 02:32 tool grepper
0m Args:
{
  "Expression": "CONFIG_KVM_XEN",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Makefile=13=kvm-$(CONFIG_KVM_HYPERV) += hyperv.o\narch/x86/kvm/Makefile:14:kvm-$(CONFIG_KVM_XEN)\t+= xen.o\narch/x86/kvm/Makefile-15-kvm-$(CONFIG_KVM_SMM)\t+= smm.o\n--\narch/x86/kvm/cpuid.c=510=static int kvm_set_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid_entry2 *e2,\n--\narch/x86/kvm/cpuid.c-572-\narch/x86/kvm/cpuid.c:573:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/cpuid.c-574-\tvcpu-\u003earch.xen.cpuid = kvm_get_hypervisor_cpuid(vcpu, XEN_SIGNATURE);\n--\narch/x86/kvm/irq.c=128=int kvm_cpu_get_extint(struct kvm_vcpu *v)\n--\narch/x86/kvm/irq.c-137-\narch/x86/kvm/irq.c:138:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/irq.c-139-\tif (kvm_xen_has_interrupt(v))\n--\narch/x86/kvm/irq.c=241=int kvm_arch_set_irq_inatomic(struct kvm_kernel_irq_routing_entry *e,\n--\narch/x86/kvm/irq.c-264-\narch/x86/kvm/irq.c:265:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/irq.c-266-\tcase KVM_IRQ_ROUTING_XEN_EVTCHN:\n--\narch/x86/kvm/irq.c=296=int kvm_set_routing_entry(struct kvm *kvm,\n--\narch/x86/kvm/irq.c-345-#endif\narch/x86/kvm/irq.c:346:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/irq.c-347-\tcase KVM_IRQ_ROUTING_XEN_EVTCHN:\n--\narch/x86/kvm/irq.h=121=static inline void kvm_warn_on_lost_irq(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/irq.h-137-\t */\narch/x86/kvm/irq.h:138:\tWARN_ON_ONCE(!pic_in_kernel(vcpu-\u003ekvm) \u0026\u0026 !IS_ENABLED(CONFIG_KVM_XEN));\narch/x86/kvm/irq.h-139-}\n--\narch/x86/kvm/x86.c=1763=int kvm_guest_time_update(struct kvm_vcpu *v)\n--\narch/x86/kvm/x86.c-1867-\narch/x86/kvm/x86.c:1868:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/x86.c-1869-\t/*\n--\narch/x86/kvm/x86.c=2217=int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)\n--\narch/x86/kvm/x86.c-2312-\t\treturn KVM_GUESTDBG_VALID_MASK;\narch/x86/kvm/x86.c:2313:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/x86.c-2314-\tcase KVM_CAP_XEN_HVM:\n--\narch/x86/kvm/x86.c=3430=long kvm_arch_vcpu_ioctl(struct file *filp,\n--\narch/x86/kvm/x86.c-3827-#endif\narch/x86/kvm/x86.c:3828:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/x86.c-3829-\tcase KVM_XEN_VCPU_GET_ATTR: {\n--\narch/x86/kvm/x86.c=4388=int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)\n--\narch/x86/kvm/x86.c-4617-\t\tbreak;\narch/x86/kvm/x86.c:4618:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/x86.c-4619-\tcase KVM_XEN_HVM_CONFIG: {\n--\narch/x86/kvm/x86.c=7172=void kvm_x86_vendor_exit(void)\n--\narch/x86/kvm/x86.c-7195-\tkmem_cache_destroy(x86_emulator_cache);\narch/x86/kvm/x86.c:7196:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/x86.c-7197-\tstatic_key_deferred_flush(\u0026kvm_xen_enabled);\n--\narch/x86/kvm/xen.h-14-\narch/x86/kvm/xen.h:15:#ifdef CONFIG_KVM_XEN\narch/x86/kvm/xen.h-16-#include \u003clinux/jump_label_ratelimit.h\u003e\n"
}

5/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25185
							output: 36
							thoughts: 20
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Investigating Kconfig and KVM Xen Interaction**

Alright, let's dive in. My immediate thought is to check the `Kconfig` files and understand how `CONFIG_KVM_XEN` is defined and how the KVM options are configured relative to Xen. I want to see how the build system handles the interplay between KVM and Xen support, particularly looking at any conditional dependencies, default values, and any specific configurations that are mutually exclusive or require explicit enabling/disabling. Specifically, I'm thinking about the implications for nested virtualization scenarios, potential conflicts in device assignment or interrupt handling, or if there's any clever logic implemented to bridge the hypervisor worlds. My experience suggests that this is often where subtle but critical integration issues manifest, so understanding this configuration path thoroughly is essential. I'll probably be looking for any hints on how the kernel decides which hypervisor it's running under, and how that decision influences the KVM configuration.



6/2 2026/10/15 02:32 tool grepper
0m Args:
{
  "Expression": "config KVM_XEN",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Kconfig=194=config KVM_HYPERV\n--\narch/x86/kvm/Kconfig-207-\narch/x86/kvm/Kconfig:208:config KVM_XEN\narch/x86/kvm/Kconfig-209-\tbool \"Support for Xen hypercall interface\"\n"
}

7/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25563
							output: 39
							thoughts: 27
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Analyzing KVM's x86 Configuration Dependencies**

Alright, let's dive into the Kconfig for x86 within the kernel source. Specifically, I need to get a handle on the dependency structure, so I'm heading straight to `arch/x86/kvm/Kconfig` around line 208. It's usually the best place to start when I need to understand which options enable, disable or affect the KVM build on x86 platforms. I'm looking for the nested `depends on` statements to build a mental map of the configuration space. This should quickly highlight any architectural requirements or other kernel features that need to be in place for KVM to function correctly. I'll be looking to identify any relationships to other features, such as Intel VT-x or AMD-V, and any potential conflicts.



8/2 2026/10/15 02:32 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Kconfig",
  "FirstLine": 200,
  "LineCount": 25
}

Results:
{
  "Contents": " 200:\t\t  to expose a subset of the paravirtualized interfaces defined in the\n 201:\t\t  Hyper-V Hypervisor Top-Level Functional Specification (TLFS):\n 202:\t\t  https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/reference/tlfs\n 203:\t\t  These interfaces are required for the correct and performant functioning\n 204:\t\t  of Windows and Hyper-V guests on KVM.\n 205:\t\n 206:\t\t  If unsure, say \"Y\".\n 207:\t\n 208:\tconfig KVM_XEN\n 209:\t\tbool \"Support for Xen hypercall interface\"\n 210:\t\tdepends on KVM_X86\n 211:\t\thelp\n 212:\t\t  Provides KVM support for the hosting Xen HVM guests and\n 213:\t\t  passing Xen hypercalls to userspace.\n 214:\t\n 215:\t\t  If in doubt, say \"N\".\n 216:\t\n 217:\tconfig KVM_PROVE_MMU\n 218:\t\tbool \"Prove KVM MMU correctness\"\n 219:\t\tdepends on DEBUG_KERNEL\n 220:\t\tdepends on KVM_X86\n 221:\t\tdepends on EXPERT\n 222:\t\thelp\n 223:\t\t  Enables runtime assertions in KVM's MMU that are too costly to enable\n 224:\t\t  in anything remotely resembling a production environment, e.g. this\n"
}

9/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26227
							output: 37
							thoughts: 74
						

Thoughts:
Okay, let's dive into this KVM configuration process. I need a quick refresher on the typical KVM settings. My initial thought is to make sure the core options are enabled: `KVM` or, depending on the host CPU, `KVM_INTEL` or `KVM_AMD`, along with `KVM_X86` and potentially `KVM_XEN` if paravirtualization is desired.

To solidify my understanding of the fundamental configurations, I'm going to consult the kernel source directly. Specifically, I'll examine the `arch/x86/kvm/Kconfig` file, focusing on the initial lines - let's say lines 1 to 50 - to quickly get a sense of the essential prerequisites and available features at this level. This approach should offer a rapid and effective method to grasp the relevant KVM dependencies and options at a glance.



10/2 2026/10/15 02:32 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Kconfig",
  "FirstLine": 1,
  "LineCount": 50
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0\n   2:\t#\n   3:\t# KVM configuration\n   4:\t#\n   5:\t\n   6:\tsource \"virt/kvm/Kconfig\"\n   7:\t\n   8:\tmenuconfig VIRTUALIZATION\n   9:\t\tbool \"Virtualization\"\n  10:\t\tdefault y\n  11:\t\thelp\n  12:\t\t  Say Y here to get to see options for using your Linux host to run other\n  13:\t\t  operating systems inside virtual machines (guests).\n  14:\t\t  This option alone does not add any kernel code.\n  15:\t\n  16:\t\t  If you say N, all options in this submenu will be skipped and disabled.\n  17:\t\n  18:\tif VIRTUALIZATION\n  19:\t\n  20:\tconfig KVM_X86\n  21:\t\tdef_tristate KVM if (KVM_INTEL != n || KVM_AMD != n)\n  22:\t\tselect KVM_COMMON\n  23:\t\tselect KVM_ELIDE_TLB_FLUSH_IF_YOUNG\n  24:\t\tselect KVM_MMU_LOCKLESS_AGING\n  25:\t\tselect HAVE_KVM_IRQCHIP\n  26:\t\tselect HAVE_KVM_PFNCACHE\n  27:\t\tselect HAVE_KVM_DIRTY_RING_TSO\n  28:\t\tselect HAVE_KVM_DIRTY_RING_ACQ_REL\n  29:\t\tselect HAVE_KVM_IRQ_BYPASS\n  30:\t\tselect HAVE_KVM_IRQ_ROUTING\n  31:\t\tselect HAVE_KVM_READONLY_MEM\n  32:\t\tselect VHOST_TASK\n  33:\t\tselect KVM_ASYNC_PF\n  34:\t\tselect USER_RETURN_NOTIFIER\n  35:\t\tselect KVM_MMIO\n  36:\t\tselect SCHED_INFO\n  37:\t\tselect PERF_EVENTS\n  38:\t\tselect GUEST_PERF_EVENTS\n  39:\t\tselect PERF_GUEST_MEDIATED_PMU\n  40:\t\tselect HAVE_KVM_MSI\n  41:\t\tselect HAVE_KVM_CPU_RELAX_INTERCEPT\n  42:\t\tselect HAVE_KVM_NO_POLL\n  43:\t\tselect VIRT_XFER_TO_GUEST_WORK\n  44:\t\tselect KVM_GENERIC_DIRTYLOG_READ_PROTECT\n  45:\t\tselect KVM_VFIO\n  46:\t\tselect HAVE_KVM_PM_NOTIFIER if PM\n  47:\t\tselect KVM_GENERIC_HARDWARE_ENABLING\n  48:\t\tselect KVM_GENERIC_PRE_FAULT_MEMORY\n  49:\t\tselect KVM_WERROR if WERROR\n  50:\t\tselect KVM_GUEST_MEMFD if X86_64\n"
}

11/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27259
							output: 33
							thoughts: 16
						

Thoughts:
Here's my thought process, as if I were considering this myself:

**Kconfig Location Check**

Alright, I need to make sure I haven't missed anything obvious. Given the context, I should quickly verify that the `virt/kvm/Kconfig` file hasn't been overlooked. It's a key configuration file in the KVM virtualization context, so a simple check there could save some time and identify any missed configuration options or dependencies. It's a common area for related settings, so it's worth the quick scan. Let me go there first.



12/2 2026/10/15 02:32 tool read-file
0m Args:
{
  "File": "virt/kvm/Kconfig",
  "FirstLine": 1,
  "LineCount": 50
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0\n   2:\t# KVM common configuration items and defaults\n   3:\t\n   4:\tconfig KVM_COMMON\n   5:\t       bool\n   6:\t       select EVENTFD\n   7:\t       select INTERVAL_TREE\n   8:\t       select MMU_NOTIFIER\n   9:\t       select PREEMPT_NOTIFIERS\n  10:\t\n  11:\tconfig HAVE_KVM_PFNCACHE\n  12:\t       bool\n  13:\t\n  14:\tconfig HAVE_KVM_IRQCHIP\n  15:\t       bool\n  16:\t\n  17:\tconfig HAVE_KVM_IRQ_ROUTING\n  18:\t       bool\n  19:\t\n  20:\tconfig HAVE_KVM_DIRTY_RING\n  21:\t       bool\n  22:\t\n  23:\t# Only strongly ordered architectures can select this, as it doesn't\n  24:\t# put any explicit constraint on userspace ordering. They can also\n  25:\t# select the _ACQ_REL version.\n  26:\tconfig HAVE_KVM_DIRTY_RING_TSO\n  27:\t       bool\n  28:\t       select HAVE_KVM_DIRTY_RING\n  29:\t       depends on X86\n  30:\t\n  31:\t# Weakly ordered architectures can only select this, advertising\n  32:\t# to userspace the additional ordering requirements.\n  33:\tconfig HAVE_KVM_DIRTY_RING_ACQ_REL\n  34:\t       bool\n  35:\t       select HAVE_KVM_DIRTY_RING\n  36:\t\n  37:\t# Allow enabling both the dirty bitmap and dirty ring. Only architectures\n  38:\t# that need to dirty memory outside of a vCPU context should select this.\n  39:\tconfig NEED_KVM_DIRTY_RING_WITH_BITMAP\n  40:\t\tbool\n  41:\t\tdepends on HAVE_KVM_DIRTY_RING\n  42:\t\n  43:\tconfig KVM_MMIO\n  44:\t       bool\n  45:\t\n  46:\tconfig KVM_ASYNC_PF\n  47:\t       bool\n  48:\t\n  49:\t# Toggle to switch between direct notification and batch job\n  50:\tconfig KVM_ASYNC_PF_SYNC\n"
}

13/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28042
							output: 29
							thoughts: 43
						

Thoughts:
Okay, here's my assessment of the situation:

**Investigating the KVM PFN Cache Build Process**

Right, let's dive in. My immediate thought is, "How exactly is the `pfncache.c` file getting built within the KVM infrastructure?" This requires a quick dive. I need to understand the build dependencies and process. My next step? I'm going to look at the build configuration. I'll start with the obvious location: `virt/kvm/pfncache.c`. Then, since I know my way around the kernel source, I'll probably find that the build configuration is dictated by `virt/kvm/Makefile.kvm`. That should give me the answer. Time to trace this out and see what's going on!



14/2 2026/10/15 02:32 tool grepper
0m Args:
{
  "Expression": "pfncache",
  "PathPrefixes": [
    "virt/kvm/"
  ]
}

Results:
{
  "Output": "virt/kvm/Makefile.kvm=13=kvm-$(CONFIG_HAVE_KVM_DIRTY_RING) += $(KVM)/dirty_ring.o\nvirt/kvm/Makefile.kvm:14:kvm-$(CONFIG_HAVE_KVM_PFNCACHE) += $(KVM)/pfncache.o\nvirt/kvm/Makefile.kvm-15-kvm-$(CONFIG_KVM_GUEST_MEMFD) += $(KVM)/guest_memfd.o\n"
}

15/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28414
							output: 35
							thoughts: 88
						

Thoughts:
Here's my thought process, as I analyze this:

**Delving into KVM Configuration Dependencies**

Okay, so I see that `HAVE_KVM_PFNCACHE` is selected when `KVM_X86` is defined. That's a key dependency to keep in mind. Now, I need to understand the broader KVM configuration landscape. What are the primary KVM options? Let me see... `KVM`, `KVM_INTEL`, `KVM_AMD`, and `KVM_XEN`. Got it. Those are the potential flavors or implementations we might be dealing with.

To get a handle on the central KVM configuration, I should check `arch/x86/kvm/Kconfig`. That's the likely location for the master definition of the `KVM` symbol I'm curious about. From there, I can determine the relationships and how `KVM` is configured, which will then have further impacts on related configurations such as `HAVE_KVM_PFNCACHE`. This gives a strong foundation for understanding the interactions of these options.



16/2 2026/10/15 02:32 tool grepper
0m Args:
{
  "Expression": "config KVM\\b",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Kconfig=20=config KVM_X86\n--\narch/x86/kvm/Kconfig-51-\narch/x86/kvm/Kconfig:52:config KVM\narch/x86/kvm/Kconfig-53-\ttristate \"Kernel-based Virtual Machine (KVM) support\"\n"
}

17/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28876
							output: 39
							thoughts: 2863
						

Thoughts:
**KVM Patch Analysis: WorthFuzzing = True**

Okay, so I've got a patch here dealing with KVM, specifically the interaction with Xen and some core synchronization primitives. My initial thought is, this is definitely something I need to pay attention to. We're talking about changes to how KVM handles memory mapping (pfncache), event channels, and locking within the virtualization layer. This looks to address a pretty specific deadlock scenario involving `srcu` read sections and memslot updates, so it's probably important.

The patch touches a number of files. Starting with the documentation, which adds a note about assuming shared info pages and vcpu info areas are dirty. Then there's an addition of a `never_dirty` flag in `gfn_to_pfn_cache`, which already signals an area of special handling. We see that this flag is set in the `kvm_xen_init_vcpu()` and `kvm_xen_init_vm()` calls. This tells me that this is specific to Xen. The other functions that now have the `wait` parameter are likely to be related to synchronizing access to memory mapped by the Xen guest.

The meat of the changes seems to be in `pfncache.c` and `xen.c`. The `pfncache.c` file introduces retry logic using `EAGAIN` when a memslot is being updated, which is part of the race condition the patch aims to resolve. The `xen.c` file has a lot more changes, dealing with `evtchn` delivery, hypercalls, locking orders, and error handling. What I'm seeing here is a significant refactoring of the Xen integration in KVM to handle these races. Also a new test `xen_evtchn_memslot_race_test.c` was added, indicating that there was an actual deadlock that can be reproduced. The test itself provides a great summary of the problem - deadlocks between the memslot updates and vcpu exit handling.

Now, the important question is: is this reachable? From my perspective, as a KVM expert, the answer is a resounding yes. Syzkaller, in particular, should be able to trigger this! This touches core virtualization logic - memory management, locking, event channels. Changes in memory management often have big effects. I see modifications to synchronization, changes to error codes, the addition of retry logic with `cond_resched()`, changes to the TLB flush requests in `vcpu_enter_guest()`, and a refactoring of event channel delivery in `__kvm_xen_set_evtchn_fast()`. This seems very relevant to fuzzing. It's the kind of logic syzkaller is specifically designed to target and test. So, based on my understanding of KVM and syzkaller's capabilities, I'm confident that these changes are absolutely reachable in a standard environment, therefore `WorthFuzzing = true`.

I now need to make sure I understand the `EnableConfigs`. The patch introduces `HAVE_KVM_PFNCACHE` which is defined by `KVM_X86`. This is important, as `KVM_X86` depends on either `KVM_INTEL` or `KVM_AMD`. The `KVM_XEN` option also looks important as it relies on `KVM_X86`, so I need to make sure this is enabled.



18/2 2026/10/15 02:32 tool grepper
0m Args:
{
  "Expression": "config KVM_(INTEL|AMD)",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/Kconfig=83=config KVM_SW_PROTECTED_VM\n--\narch/x86/kvm/Kconfig-95-\narch/x86/kvm/Kconfig:96:config KVM_INTEL\narch/x86/kvm/Kconfig-97-\ttristate \"KVM for Intel (and compatible) processors support\"\n--\narch/x86/kvm/Kconfig-106-\narch/x86/kvm/Kconfig:107:config KVM_INTEL_PROVE_VE\narch/x86/kvm/Kconfig-108-        bool \"Check that guests do not receive #VE exceptions\"\n--\narch/x86/kvm/Kconfig=122=config X86_SGX_KVM\n--\narch/x86/kvm/Kconfig-133-\narch/x86/kvm/Kconfig:134:config KVM_INTEL_TDX\narch/x86/kvm/Kconfig-135-\tbool \"Intel Trust Domain Extensions (TDX) support\"\n--\narch/x86/kvm/Kconfig-145-\narch/x86/kvm/Kconfig:146:config KVM_AMD\narch/x86/kvm/Kconfig-147-\ttristate \"KVM for AMD processors support\"\n--\narch/x86/kvm/Kconfig-155-\narch/x86/kvm/Kconfig:156:config KVM_AMD_SEV\narch/x86/kvm/Kconfig-157-\tbool \"AMD Secure Encrypted Virtualization (SEV) support\"\n"
}

19/2 2026/10/15 02:32 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32942
							output: 38
							thoughts: 44
						

Thoughts:
Okay, let's dive into this.

**Investigating KVM Configuration Dependencies**

Alright, so I need to understand the dependencies of `KVM` and `KVM_INTEL` within the x86 kernel configuration. My instinct says to check out `arch/x86/kvm/Kconfig` specifically, focusing on the region roughly between lines 50 and 100. That should give me a good overview of what other configuration options need to be enabled before these KVM-related features become available. It's the most logical place to begin digging for those prerequisite dependencies. Hopefully, the Kconfig file lays them out clearly with `depends on` statements. This should be a quick way to grasp the overall architecture and how the different components fit together, enabling a more informed analysis or modification later on.



20/2 2026/10/15 02:33 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/Kconfig",
  "FirstLine": 50,
  "LineCount": 55
}

Results:
{
  "Contents": "  50:\t\tselect KVM_GUEST_MEMFD if X86_64\n  51:\t\n  52:\tconfig KVM\n  53:\t\ttristate \"Kernel-based Virtual Machine (KVM) support\"\n  54:\t\tdepends on X86_LOCAL_APIC\n  55:\t\thelp\n  56:\t\t  Support hosting fully virtualized guest machines using hardware\n  57:\t\t  virtualization extensions.  You will need a fairly recent\n  58:\t\t  processor equipped with virtualization extensions. You will also\n  59:\t\t  need to select one or more of the processor modules below.\n  60:\t\n  61:\t\t  This module provides access to the hardware capabilities through\n  62:\t\t  a character device node named /dev/kvm.\n  63:\t\n  64:\t\t  To compile this as a module, choose M here: the module\n  65:\t\t  will be called kvm.\n  66:\t\n  67:\t\t  If unsure, say N.\n  68:\t\n  69:\tconfig KVM_WERROR\n  70:\t\tbool \"Compile KVM with -Werror\"\n  71:\t\t# Disallow KVM's -Werror if KASAN is enabled, e.g. to guard against\n  72:\t\t# randomized configs from selecting KVM_WERROR=y, which doesn't play\n  73:\t\t# nice with KASAN.  KASAN builds generates warnings for the default\n  74:\t\t# FRAME_WARN, i.e. KVM_WERROR=y with KASAN=y requires special tuning.\n  75:\t\t# Building KVM with -Werror and KASAN is still doable via enabling\n  76:\t\t# the kernel-wide WERROR=y.\n  77:\t\tdepends on KVM_X86 \u0026\u0026 ((EXPERT \u0026\u0026 !KASAN) || WERROR)\n  78:\t\thelp\n  79:\t\t  Add -Werror to the build flags for KVM.\n  80:\t\n  81:\t\t  If in doubt, say \"N\".\n  82:\t\n  83:\tconfig KVM_SW_PROTECTED_VM\n  84:\t\tbool \"Enable support for KVM software-protected VMs\"\n  85:\t\tdepends on EXPERT\n  86:\t\tdepends on KVM_X86 \u0026\u0026 X86_64\n  87:\t\tselect KVM_GENERIC_MEMORY_ATTRIBUTES\n  88:\t\thelp\n  89:\t\t  Enable support for KVM software-protected VMs.  Currently, software-\n  90:\t\t  protected VMs are purely a development and testing vehicle for\n  91:\t\t  KVM_CREATE_GUEST_MEMFD.  Attempting to run a \"real\" VM workload as a\n  92:\t\t  software-protected VM will fail miserably.\n  93:\t\n  94:\t\t  If unsure, say \"N\".\n  95:\t\n  96:\tconfig KVM_INTEL\n  97:\t\ttristate \"KVM for Intel (and compatible) processors support\"\n  98:\t\tdepends on KVM \u0026\u0026 IA32_FEAT_CTL\n  99:\t\tselect X86_FRED if X86_64\n 100:\t\thelp\n 101:\t\t  Provides support for KVM on processors equipped with Intel's VT\n 102:\t\t  extensions, a.k.a. Virtual Machine Extensions (VMX).\n 103:\t\n 104:\t\t  To compile this as a module, choose M here: the module\n"
}

21/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34073
							output: 33
							thoughts: 332
						

Thoughts:
**My KVM Configuration Analysis**

Okay, so I'm looking at this patch and immediately, `KVM` comes to mind, and then its x86 variants (`KVM_X86`, `KVM_INTEL`, `KVM_AMD`), and the `KVM_XEN` option. Hold on a second, what exactly *enables* `KVM_XEN`? Let me check the Kconfig. Ah, there it is in `arch/x86/kvm/Kconfig`: it depends on `KVM_X86`, which makes perfect sense. So, we're dealing with `KVM`, `KVM_INTEL` (or `KVM_AMD`), and `KVM_XEN` as the primary players.

Now, what about the debugging options, like `PROVE_LOCKING` or `LOCKDEP`? I see that `srcu_lock_sync` call in the patch with the SRU lock. Lockdep should definitely be useful for checking the lock ordering of this new wait mechanism. But isn't `LOCKDEP` or `PROVE_LOCKING` a debug option? It's not strictly *required* to compile and reach the code, but the patch would benefit from them. But `KVM_XEN` is definitely required to reach `arch/x86/kvm/xen.c`. And of course `KVM` (and either `KVM_INTEL` or `KVM_AMD`) is fundamentally required for KVM functionality.

Generally, for KVM-related setups, `KVM` and `KVM_XEN` (along with `KVM_INTEL` or `KVM_AMD`, of course) are the most crucial configurations. Just to be thorough, I should check for any other relevant configurations. Let's see if the `pfncache.c` file has any other conditional compilation directives (`#ifdef`s) that might be involved.



22/2 2026/10/15 02:33 tool grepper
0m Args:
{
  "Expression": "#ifdef",
  "PathPrefixes": [
    "virt/kvm/pfncache.c"
  ]
}

Results:
{
  "Output": "virt/kvm/pfncache.c=99=static void *gpc_map(kvm_pfn_t pfn)\n--\nvirt/kvm/pfncache.c-103-\nvirt/kvm/pfncache.c:104:#ifdef CONFIG_HAS_IOMEM\nvirt/kvm/pfncache.c-105-\treturn memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);\n--\nvirt/kvm/pfncache.c=111=static void gpc_unmap(kvm_pfn_t pfn, void *khva)\n--\nvirt/kvm/pfncache.c-121-\nvirt/kvm/pfncache.c:122:#ifdef CONFIG_HAS_IOMEM\nvirt/kvm/pfncache.c-123-\tmemunmap(khva);\n"
}

23/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35100
							output: 41
							thoughts: 1200
						

Thoughts:
**Focusing the Fuzzer: A Targeted Approach**

Alright, let's get down to brass tacks. We're looking at guiding the fuzzer using `FocusSymbols` to ensure we're targeting the right areas for fuzzing. The goal is clear: prevent dilution of effort. We need to identify specific functions that warrant attention, avoiding the noise of ubiquitous lifecycle functions.

The instructions are straightforward: pinpoint the logic being added or altered, or the key entrypoints for the features under review. Crucially, we need to handle those static inline functions in headers properly, by finding callers in .c files that exercise them.

So, let's break down the modified functions in this patch and figure out which ones are key. I'll make notes as I go:

In `virt/kvm/pfncache.c`, we see a mix of static and non-static functions: `__kvm_gpc_refresh`, `gpc_refresh_locked`, `kvm_gpc_refresh`, `__kvm_gpc_init`, `__kvm_gpc_activate`, `kvm_gpc_activate`, and `kvm_gpc_activate_hva`.

Moving to `arch/x86/kvm/xen.c`, the list grows: `kvm_xen_shared_info_init`, `kvm_xen_inject_timer_irqs`, `kvm_xen_hcall_evtchn_send`, `kvm_xen_hypercall`, `__kvm_xen_set_evtchn_fast`, `kvm_xen_set_evtchn_fast`, `kvm_xen_set_evtchn`, `evtchn_set_fn`, `kvm_xen_hvm_evtchn_send`, `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`, and `kvm_xen_write_hypercall_page`.

We also have some functions from `arch/x86/kvm/x86.c`: `record_steal_time`, `vcpu_enter_guest` (which is a hot path - we should probably avoid that one), and `kvm_setup_guest_pvclock`.

Finally, we have `kvm_write_system_time` from `arch/x86/kvm/msrs.c`.

Now, we need to separate the wheat from the chaff. We need to identify which symbols are actual, non-inlined functions available in `vmlinux` or `kvm.o`. Let's test what functions there. Based on the previous list, here are the ones I'll check: `kvm_gpc_refresh`, `kvm_gpc_activate`, `kvm_xen_set_evtchn_fast`, `kvm_xen_hvm_evtchn_send`, `kvm_xen_inject_timer_irqs`, `kvm_xen_hypercall`, `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`, and `record_steal_time`.

Wait a minute, let's verify how `__kvm_xen_set_evtchn_fast` and `kvm_xen_set_evtchn_fast` actually work. I'll check the source to determine if `__kvm_xen_set_evtchn_fast` is static or if it's inlined. I need to make sure we're getting the right function, and not an inlined helper.



24/2 2026/10/15 02:33 tool grepper
0m Args:
{
  "Expression": "kvm_xen_set_evtchn_fast",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/irq.c=241=int kvm_arch_set_irq_inatomic(struct kvm_kernel_irq_routing_entry *e,\n--\narch/x86/kvm/irq.c-269-\narch/x86/kvm/irq.c:270:\t\treturn kvm_xen_set_evtchn_fast(\u0026e-\u003exen_evtchn, kvm);\narch/x86/kvm/irq.c-271-#endif\n--\narch/x86/kvm/xen.c=154=static enum hrtimer_restart xen_timer_callback(struct hrtimer *timer)\n--\narch/x86/kvm/xen.c-168-\narch/x86/kvm/xen.c:169:\trc = kvm_xen_set_evtchn_fast(\u0026e, vcpu-\u003ekvm);\narch/x86/kvm/xen.c-170-\tif (rc != -EWOULDBLOCK) {\n--\narch/x86/kvm/xen.c=1884=static void kvm_xen_check_poller(struct kvm_vcpu *vcpu, int port)\n--\narch/x86/kvm/xen.c-1894-\narch/x86/kvm/xen.c:1895:static void __kvm_xen_set_evtchn_fast(struct kvm_vcpu *vcpu, int port_word_bit,\narch/x86/kvm/xen.c-1896-\t\t\t\t      bool has_64bit_shinfo)\n--\narch/x86/kvm/xen.c-1987- */\narch/x86/kvm/xen.c:1988:int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)\narch/x86/kvm/xen.c-1989-{\n--\narch/x86/kvm/xen.c-2058-\telse if (rc == 1)\narch/x86/kvm/xen.c:2059:\t\t__kvm_xen_set_evtchn_fast(vcpu, port_word_bit,\narch/x86/kvm/xen.c-2060-\t\t\t\t\t  has_64bit_shinfo);\n--\narch/x86/kvm/xen.c=2067=static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,\n--\narch/x86/kvm/xen.c-2072-\narch/x86/kvm/xen.c:2073:\trc = kvm_xen_set_evtchn_fast(xe, kvm);\narch/x86/kvm/xen.c-2074-\tif (rc != -EWOULDBLOCK)\n--\narch/x86/kvm/xen.c-2105-\narch/x86/kvm/xen.c:2106:\t\trc = kvm_xen_set_evtchn_fast(xe, kvm);\narch/x86/kvm/xen.c-2107-\t\tif (rc != -EWOULDBLOCK)\n--\narch/x86/kvm/xen.h=33=void kvm_xen_destroy_vcpu(struct kvm_vcpu *vcpu);\narch/x86/kvm/xen.h:34:int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe,\narch/x86/kvm/xen.h-35-\t\t\t    struct kvm *kvm);\n"
}

25/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38107
							output: 37
							thoughts: 51
						

Thoughts:
Here's my summary, as though I'm thinking through this myself:

**Investigating Potential KVM/Xen Interaction Issues**

Okay, so `kvm_xen_set_evtchn_fast` is showing up as a non-static symbol, which is a bit of a red flag. I need to understand its relationship to the rest of the KVM/Xen interaction. Let's dig deeper. First, the question is, what about `kvm_xen_hypercall`? Is this also non-static, or is there something special about this particular function? I need to understand its scope and usage in context. It's time to check *where* `kvm_xen_hypercall` is actually called. That should give me a clearer picture of how these two functions relate and whether this potential non-static symbol issue with `kvm_xen_set_evtchn_fast` is indicative of a broader concern within the code. Let's get to tracing.



26/2 2026/10/15 02:33 tool grepper
0m Args:
{
  "Expression": "kvm_xen_hypercall",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/hyperv.c=1398=static int kvm_hv_set_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data,\n--\narch/x86/kvm/hyperv.c-1432-\t\t */\narch/x86/kvm/hyperv.c:1433:\t\tif (kvm_xen_hypercall_enabled(kvm)) {\narch/x86/kvm/hyperv.c-1434-\t\t\t/* orl $0x80000000, %eax */\n--\narch/x86/kvm/trace.h=114=TRACE_EVENT(kvm_hv_hypercall_done,\n--\narch/x86/kvm/trace.h-131- */\narch/x86/kvm/trace.h:132:TRACE_EVENT(kvm_xen_hypercall,\narch/x86/kvm/trace.h-133-\t    TP_PROTO(u8 cpl, unsigned long nr,\n--\narch/x86/kvm/x86.c=7457=int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)\narch/x86/kvm/x86.c-7458-{\narch/x86/kvm/x86.c:7459:\tif (kvm_xen_hypercall_enabled(vcpu-\u003ekvm))\narch/x86/kvm/x86.c:7460:\t\treturn kvm_xen_hypercall(vcpu);\narch/x86/kvm/x86.c-7461-\n--\narch/x86/kvm/xen.c=1355=int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)\n--\narch/x86/kvm/xen.c-1393-\t */\narch/x86/kvm/xen.c:1394:\tif (kvm_xen_hypercall_enabled(kvm)) {\narch/x86/kvm/xen.c-1395-\t\tu8 instructions[32];\n--\narch/x86/kvm/xen.c=1449=int kvm_xen_hvm_config(struct kvm *kvm, struct kvm_xen_hvm_config *xhc)\n--\narch/x86/kvm/xen.c-1495-\narch/x86/kvm/xen.c:1496:static int kvm_xen_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)\narch/x86/kvm/xen.c-1497-{\n--\narch/x86/kvm/xen.c-1501-\narch/x86/kvm/xen.c:1502:static int kvm_xen_hypercall_complete_userspace(struct kvm_vcpu *vcpu)\narch/x86/kvm/xen.c-1503-{\n--\narch/x86/kvm/xen.c-1508-\narch/x86/kvm/xen.c:1509:\treturn kvm_xen_hypercall_set_result(vcpu, run-\u003exen.u.hcall.result);\narch/x86/kvm/xen.c-1510-}\n--\narch/x86/kvm/xen.c=1756=static bool kvm_xen_hcall_set_timer_op(struct kvm_vcpu *vcpu, uint64_t timeout,\n--\narch/x86/kvm/xen.c-1770-\narch/x86/kvm/xen.c:1771:int kvm_xen_hypercall(struct kvm_vcpu *vcpu)\narch/x86/kvm/xen.c-1772-{\n--\narch/x86/kvm/xen.c-1807-\tcpl = kvm_x86_call(get_cpl)(vcpu);\narch/x86/kvm/xen.c:1808:\ttrace_kvm_xen_hypercall(cpl, input, params[0], params[1], params[2],\narch/x86/kvm/xen.c-1809-\t\t\t\tparams[3], params[4], params[5]);\n--\narch/x86/kvm/xen.c-1862-\tif (handled)\narch/x86/kvm/xen.c:1863:\t\treturn kvm_xen_hypercall_set_result(vcpu, r);\narch/x86/kvm/xen.c-1864-\n--\narch/x86/kvm/xen.c-1878-\tvcpu-\u003earch.complete_userspace_io =\narch/x86/kvm/xen.c:1879:\t\tkvm_xen_hypercall_complete_userspace;\narch/x86/kvm/xen.c-1880-\n--\narch/x86/kvm/xen.h=59=static inline bool kvm_xen_is_hypercall_page_msr(struct kvm *kvm, u32 msr)\n--\narch/x86/kvm/xen.h-66-\narch/x86/kvm/xen.h:67:static inline bool kvm_xen_hypercall_enabled(struct kvm *kvm)\narch/x86/kvm/xen.h-68-{\n--\narch/x86/kvm/xen.h=95=static inline int kvm_xen_has_pending_timer(struct kvm_vcpu *vcpu)\narch/x86/kvm/xen.h-96-{\narch/x86/kvm/xen.h:97:\tif (kvm_xen_hypercall_enabled(vcpu-\u003ekvm) \u0026\u0026 kvm_xen_timer_enabled(vcpu))\narch/x86/kvm/xen.h-98-\t\treturn atomic_read(\u0026vcpu-\u003earch.xen.timer_pending);\n--\narch/x86/kvm/xen.h=135=static inline bool kvm_xen_is_hypercall_page_msr(struct kvm *kvm, u32 msr)\n--\narch/x86/kvm/xen.h-139-\narch/x86/kvm/xen.h:140:static inline bool kvm_xen_hypercall_enabled(struct kvm *kvm)\narch/x86/kvm/xen.h-141-{\n--\narch/x86/kvm/xen.h=168=static inline bool kvm_xen_timer_enabled(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/xen.h-173-\narch/x86/kvm/xen.h:174:int kvm_xen_hypercall(struct kvm_vcpu *vcpu);\narch/x86/kvm/xen.h-175-\n"
}

27/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40230
							output: 37
							thoughts: 230
						

Thoughts:
**Analyzing KVM Hypercall and GPC Functions**

Okay, so `kvm_xen_hypercall` immediately pegs me as a dedicated entry point, likely for Xen hypercalls. This patch seems to be honing in on event channel operations, particularly EVTCHNOP_send. But `kvm_gpc_refresh` and `kvm_gpc_activate` are where I need to dig deeper. My initial question is where are these functions defined and exported.

Let's check the definitions, and where they're exported. Ah, they are found in `virt/kvm/pfncache.c`.

`int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait)` is declared and, crucially, `EXPORT_SYMBOL_GPL(kvm_gpc_refresh);` tells me it's exportable with a GPL license, as expected.

Similarly, I see `int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len, bool wait)` which is also `EXPORT_SYMBOL_GPL(kvm_gpc_activate);`. So, it's clear these two are designed to be callable from other modules. Now I need to see *how* and *why* they are exported in this context. I will check the exports in `virt/kvm/pfncache.c`.



28/2 2026/10/15 02:33 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "EXPORT_SYMBOL.*gpc",
  "PathPrefixes": [
    "virt/kvm/pfncache.c"
  ]
}

Results:
{
  "error": "no matches"
}

29/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40831
							output: 38
							thoughts: 18
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Diving Deep into `virt/kvm/pfncache.c`**

Alright, let's get into the nitty-gritty of the end of `virt/kvm/pfncache.c`. I'm focusing in on the final bits, figuring out how the PFN cache is actually managed and what the cleanup looks like. Thinking about potential race conditions and locking strategies is critical here, especially when dealing with virtual memory and potential contention. I'm looking for where the actual cache entries get freed and any associated bookkeeping. I'm also really trying to see how the cache interacts with the overall KVM memory management. Is there a clean disconnect or is it tightly coupled? Understanding how the PFN cache is integrated into the larger KVM architecture is crucial for assessing its efficiency and potential bottlenecks.



30/2 2026/10/15 02:33 tool read-file
0m Args:
{
  "File": "virt/kvm/pfncache.c",
  "FirstLine": 500,
  "LineCount": 50
}

Results:
{
  "Contents": " 500:\t{\n 501:\t\t/*\n 502:\t\t * Explicitly disallow INVALID_GPA so that the magic value can be used\n 503:\t\t * by KVM to differentiate between GPA-based and HVA-based caches.\n 504:\t\t */\n 505:\t\tif (WARN_ON_ONCE(kvm_is_error_gpa(gpa)))\n 506:\t\t\treturn -EINVAL;\n 507:\t\n 508:\t\treturn __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len, wait);\n 509:\t}\n 510:\t\n 511:\tint kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva,\n 512:\t\t\t\t unsigned long len)\n 513:\t{\n 514:\t\tif (!access_ok((void __user *)uhva, len))\n 515:\t\t\treturn -EINVAL;\n 516:\t\n 517:\t\t/* An HVA-based cache never consults the memslots, so never waits. */\n 518:\t\treturn __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len, false);\n 519:\t}\n 520:\t\n 521:\tvoid kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc)\n 522:\t{\n 523:\t\tstruct kvm *kvm = gpc-\u003ekvm;\n 524:\t\tkvm_pfn_t old_pfn;\n 525:\t\tvoid *old_khva;\n 526:\t\n 527:\t\tguard(mutex)(\u0026gpc-\u003erefresh_lock);\n 528:\t\n 529:\t\tif (gpc-\u003eactive) {\n 530:\t\t\t/*\n 531:\t\t\t * Deactivate the cache before removing it from the list, KVM\n 532:\t\t\t * must stall mmu_notifier events until all users go away, i.e.\n 533:\t\t\t * until gpc-\u003elock is dropped and refresh is guaranteed to fail.\n 534:\t\t\t */\n 535:\t\t\twrite_lock_irq(\u0026gpc-\u003elock);\n 536:\t\t\tgpc-\u003eactive = false;\n 537:\t\t\tgpc-\u003evalid = false;\n 538:\t\n 539:\t\t\t/*\n 540:\t\t\t * Leave the GPA =\u003e uHVA cache intact, it's protected by the\n 541:\t\t\t * memslot generation.  The PFN lookup needs to be redone every\n 542:\t\t\t * time as mmu_notifier protection is lost when the cache is\n 543:\t\t\t * removed from the VM's gpc_list.\n 544:\t\t\t */\n 545:\t\t\told_khva = gpc-\u003ekhva - offset_in_page(gpc-\u003ekhva);\n 546:\t\t\tgpc-\u003ekhva = NULL;\n 547:\t\n 548:\t\t\told_pfn = gpc-\u003epfn;\n 549:\t\t\tgpc-\u003epfn = KVM_PFN_ERR_FAULT;\n"
}

31/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41911
							output: 35
							thoughts: 946
						

Thoughts:
**Analyzing KVM Module Symbols for Ubiquity**

Okay, so I'm looking at `pfncache.c`, which compiles into either `kvm.ko` or gets built into `vmlinux`. This means functions like `kvm_gpc_refresh` and `kvm_gpc_activate` are non-static symbols within the KVM module, and I need to assess their relevance to our review. I'm focusing on whether they're "ubiquitous lifecycle hot-paths" according to the guidelines.

My initial thought is to examine functions within `arch/x86/kvm/xen.c`. I've identified `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`, `kvm_xen_hvm_evtchn_send`, `kvm_xen_set_evtchn_fast`, `kvm_xen_hypercall`, `kvm_xen_inject_timer_irqs`, and the `gpc` functions I mentioned before, along with `record_steal_time`.

Now, the crucial question is: are any of these functions *ubiquitous*? I'm quickly realizing that `kvm_gpc_refresh` and `kvm_gpc_activate` are definitely *not* ubiquitous. They're specific to the KVM guest physical page cache (gpc), and only the KVM tests touch them. Similarly, `kvm_xen_hypercall` is a specific entry point for Xen hypercalls in KVM, `kvm_xen_set_evtchn_fast` is specific to Xen event channel raising, and the various `kvm_xen_*_attr` functions are specific ioctl entrypoints. `kvm_xen_inject_timer_irqs` is specific to Xen timer irqs. Finally, `record_steal_time` is also specific, as it is related to KVM pv steal time.

Okay, so what about `vcpu_enter_guest`? It's called on *every* vCPU run, which means it's a lifecycle hot-path. But, according to Guideline 4, I need to AVOID these ubiquitous functions. Listing them would mess up the fuzzing effort by classifying too many unrelated tests as focused, which would dilute the effort away from the actual changes. So, I *will* NOT include it.

Now, let's circle back to `record_steal_time`. I need to confirm if it's static. Let me see... yes, it's defined as `static void record_steal_time`. If it's static, could it be inlined into `vcpu_enter_guest`? I need to check where `record_steal_time` is called.



32/2 2026/10/15 02:33 tool grepper
0m Args:
{
  "Expression": "record_steal_time",
  "PathPrefixes": [
    "arch/x86/kvm/"
  ]
}

Results:
{
  "Output": "arch/x86/kvm/x86.c=2046=EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_service_local_tlb_flush_requests);\narch/x86/kvm/x86.c-2047-\narch/x86/kvm/x86.c:2048:static void record_steal_time(struct kvm_vcpu *vcpu)\narch/x86/kvm/x86.c-2049-{\n--\narch/x86/kvm/x86.c=8065=static int vcpu_enter_guest(struct kvm_vcpu *vcpu)\n--\narch/x86/kvm/x86.c-8107-\t\t * Process the steal time update before the TLB flush requests\narch/x86/kvm/x86.c:8108:\t\t * are serviced below; record_steal_time() requests\narch/x86/kvm/x86.c-8109-\t\t * KVM_REQ_TLB_FLUSH_GUEST on the guest's behalf rather than\n--\narch/x86/kvm/x86.c-8112-\t\tif (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))\narch/x86/kvm/x86.c:8113:\t\t\trecord_steal_time(vcpu);\narch/x86/kvm/x86.c-8114-\t\tif (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))\n"
}

33/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43920
							output: 43
							thoughts: 16
						

Thoughts:
Here's my thought process, as if I were analyzing that prompt:

**Analyzing the Request: `record_steal_time` and Summary Generation**

Okay, so I see the prompt focuses on `record_steal_time`. My immediate instinct is to understand its context. Is it a variable, a table, a function? What system or domain are we dealing with? Based on the name, my first guess is some kind of performance monitoring or resource tracking, perhaps related to CPU steal time in a virtualized environment. "Steal time" is a key indicator, so this is about understanding its behavior, size, and contents. The prompt explicitly asks for a summary of this "thought process," implying a requirement for explanation of the steps I am taking rather than just the end result. It also points to the user being an expert in their field, so I can assume this will be presented at an appropriate technical level.



34/2 2026/10/15 02:33 tool read-file
0m Args:
{
  "File": "arch/x86/kvm/x86.c",
  "FirstLine": 2048,
  "LineCount": 70
}

Results:
{
  "Contents": "2048:\tstatic void record_steal_time(struct kvm_vcpu *vcpu)\n2049:\t{\n2050:\t\tstruct gfn_to_hva_cache *ghc = \u0026vcpu-\u003earch.st.cache;\n2051:\t\tstruct kvm_steal_time __user *st;\n2052:\t\tstruct kvm_memslots *slots;\n2053:\t\tgpa_t gpa = vcpu-\u003earch.st.msr_val \u0026 KVM_STEAL_VALID_BITS;\n2054:\t\tu64 steal;\n2055:\t\tu32 version;\n2056:\t\n2057:\t\tif (kvm_xen_msr_enabled(vcpu-\u003ekvm)) {\n2058:\t\t\tkvm_xen_runstate_set_running(vcpu);\n2059:\t\t\treturn;\n2060:\t\t}\n2061:\t\n2062:\t\tif (!(vcpu-\u003earch.st.msr_val \u0026 KVM_MSR_ENABLED))\n2063:\t\t\treturn;\n2064:\t\n2065:\t\tif (WARN_ON_ONCE(current-\u003emm != vcpu-\u003ekvm-\u003emm))\n2066:\t\t\treturn;\n2067:\t\n2068:\t\tslots = kvm_memslots(vcpu-\u003ekvm);\n2069:\t\n2070:\t\tif (unlikely(slots-\u003egeneration != ghc-\u003egeneration ||\n2071:\t\t\t     gpa != ghc-\u003egpa ||\n2072:\t\t\t     kvm_is_error_hva(ghc-\u003ehva) || !ghc-\u003ememslot)) {\n2073:\t\t\t/* We rely on the fact that it fits in a single page. */\n2074:\t\t\tBUILD_BUG_ON((sizeof(*st) - 1) \u0026 KVM_STEAL_VALID_BITS);\n2075:\t\n2076:\t\t\tif (kvm_gfn_to_hva_cache_init(vcpu-\u003ekvm, ghc, gpa, sizeof(*st)) ||\n2077:\t\t\t    kvm_is_error_hva(ghc-\u003ehva) || !ghc-\u003ememslot)\n2078:\t\t\t\treturn;\n2079:\t\t}\n2080:\t\n2081:\t\tst = (struct kvm_steal_time __user *)ghc-\u003ehva;\n2082:\t\t/*\n2083:\t\t * Doing a TLB flush here, on the guest's behalf, can avoid\n2084:\t\t * expensive IPIs.\n2085:\t\t */\n2086:\t\tif (guest_pv_has(vcpu, KVM_FEATURE_PV_TLB_FLUSH)) {\n2087:\t\t\tu8 st_preempted = 0;\n2088:\t\t\tint err = -EFAULT;\n2089:\t\n2090:\t\t\tif (!user_access_begin(st, sizeof(*st)))\n2091:\t\t\t\treturn;\n2092:\t\n2093:\t\t\tasm volatile(\"1: xchgb %0, %2\\n\"\n2094:\t\t\t\t     \"xor %1, %1\\n\"\n2095:\t\t\t\t     \"2:\\n\"\n2096:\t\t\t\t     _ASM_EXTABLE_UA(1b, 2b)\n2097:\t\t\t\t     : \"+q\" (st_preempted),\n2098:\t\t\t\t       \"+\u0026r\" (err),\n2099:\t\t\t\t       \"+m\" (st-\u003epreempted));\n2100:\t\t\tif (err)\n2101:\t\t\t\tgoto out;\n2102:\t\n2103:\t\t\tuser_access_end();\n2104:\t\n2105:\t\t\tvcpu-\u003earch.st.preempted = 0;\n2106:\t\n2107:\t\t\ttrace_kvm_pv_tlb_flush(vcpu-\u003evcpu_id,\n2108:\t\t\t\t\t       st_preempted \u0026 KVM_VCPU_FLUSH_TLB);\n2109:\t\t\t/*\n2110:\t\t\t * Request the flush instead of performing it inline. With\n2111:\t\t\t * shadow paging kvm_vcpu_flush_tlb_guest() can reschedule (via\n2112:\t\t\t * mmu_sync_children()), which is why the user access above has\n2113:\t\t\t * to be closed before it. Requesting the flush is just a bit\n2114:\t\t\t * set on the running vCPU, and the request is serviced before\n2115:\t\t\t * the vCPU enters the guest; nothing requires the flush to\n2116:\t\t\t * have completed any earlier than that.\n2117:\t\t\t *\n"
}

35/2 2026/10/15 02:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45377
							output: 317
							thoughts: 1282
						

Thoughts:
**Fuzzing Target Assessment**

Okay, let's break this down. First, `record_steal_time` is a function of moderate size, about 90 lines. It appears to be the core function for the PV TLB flush request logic modified by the patch. Given its specific purpose, it's a good candidate to focus on. I'm going to determine what other functions this patch touches to gain a sense of the system and function calls at play.

I've got a list of other non-static functions this patch interacts with: `kvm_gpc_refresh`, `kvm_gpc_activate`, `kvm_xen_set_evtchn_fast`, `kvm_xen_hvm_evtchn_send`, `kvm_xen_inject_timer_irqs`, `kvm_xen_hypercall`, `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`, and `kvm_xen_write_hypercall_page`.

Now, I'm checking dependencies. `__kvm_gpc_init` is just an initialization function, so not a high priority. I see that `kvm_xen_shared_info_init` is static within `arch/x86/kvm/xen.c` and is called by `kvm_xen_hvm_set_attr` and `kvm_xen_write_hypercall_page`. So, targeting those two functions also covers `kvm_xen_shared_info_init`. Likewise, `kvm_xen_hcall_evtchn_send` is static and called from `kvm_xen_hypercall`, thus targeting `kvm_xen_hypercall` directly exercises `kvm_xen_hcall_evtchn_send`. And, `kvm_xen_set_evtchn` is static, called by several functions including `kvm_xen_hypercall`, `kvm_xen_hvm_evtchn_send`, and `kvm_xen_inject_timer_irqs`. `__kvm_xen_set_evtchn_fast` is called from `kvm_xen_set_evtchn_fast`, which in turn is called from `kvm_xen_set_evtchn`.

I'm also looking at `kvm_setup_guest_pvclock` in `arch/x86/kvm/x86.c`, which is called from `kvm_guest_time_update`. Writing to MSR_KVM_SYSTEM_TIME / MSR_KVM_SYSTEM_TIME_NEW leads to `kvm_write_system_time`.

My initial list of functions to focus on looks like this: `kvm_gpc_refresh`, `kvm_gpc_activate`, `kvm_xen_hypercall`, `kvm_xen_set_evtchn_fast`, `kvm_xen_hvm_evtchn_send`, `kvm_xen_inject_timer_irqs`, `kvm_xen_hvm_set_attr`, `kvm_xen_vcpu_set_attr`, `kvm_xen_vcpu_get_attr`, `kvm_xen_write_hypercall_page`, and of course `record_steal_time`. Since `record_steal_time` implements the modified PV TLB flush request logic, it is the best starting point.

Now, let's verify the kernel configs. We need `CONFIG_KVM`, `CONFIG_KVM_INTEL` (or `CONFIG_KVM_AMD`), and `CONFIG_KVM_XEN`. I see that `KVM_XEN` depends on `KVM_X86`, which in turn is conditionally defined by `KVM_INTEL` or `KVM_AMD`. `KVM` requires `X86_LOCAL_APIC`. So, the necessary configs are "KVM", "KVM_INTEL", and "KVM_XEN".

Finally, I'm reviewing the instructions to confirm everything aligns: "WorthFuzzing" is true because this patch modifies reachable code. The list of "FocusSymbols" targets specific feature logic and entrypoints, avoiding generic functions, thus meeting the criteria. The "EnableConfigs" are as expected, and the reasoning is concise. Looks like we're good to go. Let's call `set-results`.



36/2 2026/10/15 02:34 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hypercall",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_write_hypercall_page",
    "record_steal_time"
  ],
  "Reasoning": "The patch series addresses deadlock and synchronization issues between KVM guest physical page cache (gfn_to_pfn_cache/GPC) refreshes/activations and kvm-\u003esrcu read sections during memslot updates. It refactors GPC wait/retry behavior, introduces lockdep synchronization assertions (srcu_lock_sync), updates Xen event channel delivery paths and error handling (-EAGAIN vs -EFAULT), modifies steal time TLB flush request sequencing, and adjusts lock scopes in KVM Xen emulation. All changes affect reachable virtualization code that is actively fuzzed via KVM ioctls and guest hypercalls.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KVM",
    "KVM_INTEL",
    "KVM_XEN"
  ],
  "FocusSymbols": [
    "kvm_gpc_refresh",
    "kvm_gpc_activate",
    "kvm_xen_hypercall",
    "kvm_xen_set_evtchn_fast",
    "kvm_xen_hvm_evtchn_send",
    "kvm_xen_inject_timer_irqs",
    "kvm_xen_hvm_set_attr",
    "kvm_xen_vcpu_set_attr",
    "kvm_xen_vcpu_get_attr",
    "kvm_xen_write_hypercall_page",
    "record_steal_time"
  ],
  "Reasoning": "The patch series addresses deadlock and synchronization issues between KVM guest physical page cache (gfn_to_pfn_cache/GPC) refreshes/activations and kvm-\u003esrcu read sections during memslot updates. It refactors GPC wait/retry behavior, introduces lockdep synchronization assertions (srcu_lock_sync), updates Xen event channel delivery paths and error handling (-EAGAIN vs -EFAULT), modifies steal time TLB flush request sequencing, and adjusts lock scopes in KVM Xen emulation. All changes affect reachable virtualization code that is actively fuzzed via KVM ioctls and guest hypercalls.",
  "WorthFuzzing": true
}

37/1 2026/10/15 02:34 action If
0m Args:
{
  "WorthFuzzing": true
}

Results:
null

38/2 2026/10/15 02:34 agent kmsan-evaluator
0m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series addresses synchronization, locking, and deadlock issues in KVM (specifically within the gfn_to_pfn_cache implementation, x86 steal time handling, and Xen emulation). It resolves an SRCU deadlock where guest exit handling could wait on a memslot update while holding kvm-\u003esrcu, replaces inline TLB flushes in steal time recording with deferred request handling (KVM_REQ_TLB_FLUSH_GUEST), and adds a 'wait' parameter to kvm_gpc_refresh/kvm_gpc_activate.\n\nKMSAN is designed to detect uninitialized memory reads and leaks to userspace. The patch does not introduce or alter any copy_to_user/ioctl data transfers to userspace, does not leave any struct fields or local variables uninitialized, and does not alter buffer length or bounds checking logic that could expose uninitialized memory. Any concurrency, deadlock, or memory lifetime issues introduced by these changes are addressed by LOCKDEP and standard KASAN, making a dedicated KMSAN fuzzing run unnecessary.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit b3aac2f9a3334b2c6c1ecb22b39cbea125204fd6
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 15 02:31:47 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst
index e0430cc750c9e..b24aac070b119 100644
--- a/Documentation/virt/kvm/api.rst
+++ b/Documentation/virt/kvm/api.rst
@@ -385,8 +385,9 @@ The bits in the dirty bitmap are cleared before the ioctl returns, unless
 KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is enabled.  For more information,
 see the description of the capability.
 
-Note that the Xen shared_info page, if configured, shall always be assumed
-to be dirty. KVM will not explicitly mark it such.
+Note that the Xen shared_info page and vcpu_info area, if configured,
+shall always be assumed to be dirty. KVM will not explicitly mark them
+such.
 
 
 4.10 KVM_RUN
diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h
index 3af7395c2430a..6bebc4a79a334 100644
--- a/arch/x86/include/asm/kvm_host.h
+++ b/arch/x86/include/asm/kvm_host.h
@@ -1108,6 +1108,10 @@ struct kvm_hv {
 #ifdef CONFIG_KVM_XEN
 /* Xen emulation context */
 struct kvm_xen {
+	/*
+	 * Never taken inside a kvm->srcu read section: holders may wait
+	 * out memslot updates (synchronize_srcu).
+	 */
 	struct mutex xen_lock;
 	u32 xen_version;
 	bool long_mode;
diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c
index dd3bb04878ca6..4c0fbba6e7aef 100644
--- a/arch/x86/kvm/msrs.c
+++ b/arch/x86/kvm/msrs.c
@@ -1280,7 +1280,7 @@ static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time,
 	/* we verify if the enable bit is set... */
 	if (system_time & 1)
 		kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL,
-				 sizeof(struct pvclock_vcpu_time_info));
+				 sizeof(struct pvclock_vcpu_time_info), false);
 	else
 		kvm_gpc_deactivate(&vcpu->arch.pv_time);
 
diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c
index 79468ddfe4736..20119d07b477b 100644
--- a/arch/x86/kvm/x86.c
+++ b/arch/x86/kvm/x86.c
@@ -1727,7 +1727,7 @@ static void kvm_setup_guest_pvclock(struct pvclock_vcpu_time_info *ref_hv_clock,
 	while (!kvm_gpc_check(gpc, offset + sizeof(*guest_hv_clock))) {
 		read_unlock_irqrestore(&gpc->lock, flags);
 
-		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock)))
+		if (kvm_gpc_refresh(gpc, offset + sizeof(*guest_hv_clock), false))
 			return;
 
 		read_lock_irqsave(&gpc->lock, flags);
@@ -2106,8 +2106,22 @@ static void record_steal_time(struct kvm_vcpu *vcpu)
 
 		trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
 				       st_preempted & KVM_VCPU_FLUSH_TLB);
+		/*
+		 * Request the flush instead of performing it inline. With
+		 * shadow paging kvm_vcpu_flush_tlb_guest() can reschedule (via
+		 * mmu_sync_children()), which is why the user access above has
+		 * to be closed before it. Requesting the flush is just a bit
+		 * set on the running vCPU, and the request is serviced before
+		 * the vCPU enters the guest; nothing requires the flush to
+		 * have completed any earlier than that.
+		 *
+		 * Note the xchg above must remain as-is: it atomically
+		 * consumes any KVM_VCPU_FLUSH_TLB the guest set, as required
+		 * by commit b043138246a4 ("x86/KVM: Make sure
+		 * KVM_VCPU_FLUSH_TLB flag is not missed").
+		 */
 		if (st_preempted & KVM_VCPU_FLUSH_TLB)
-			kvm_vcpu_flush_tlb_guest(vcpu);
+			kvm_make_request(KVM_REQ_TLB_FLUSH_GUEST, vcpu);
 
 		if (!user_access_begin(st, sizeof(*st)))
 			goto dirty;
@@ -8089,6 +8103,14 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 			if (unlikely(r))
 				goto out;
 		}
+		/*
+		 * Process the steal time update before the TLB flush requests
+		 * are serviced below; record_steal_time() requests
+		 * KVM_REQ_TLB_FLUSH_GUEST on the guest's behalf rather than
+		 * performing the flush itself.
+		 */
+		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
+			record_steal_time(vcpu);
 		if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
 			kvm_mmu_sync_roots(vcpu);
 		if (kvm_check_request(KVM_REQ_LOAD_MMU_PGD, vcpu))
@@ -8138,8 +8160,6 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 			r = 1;
 			goto out;
 		}
-		if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
-			record_steal_time(vcpu);
 		if (kvm_check_request(KVM_REQ_PMU, vcpu))
 			kvm_pmu_handle_event(vcpu);
 		if (kvm_check_request(KVM_REQ_PMI, vcpu))
diff --git a/arch/x86/kvm/xen.c b/arch/x86/kvm/xen.c
index 6aa00f746cba3..e72c0b3d21091 100644
--- a/arch/x86/kvm/xen.c
+++ b/arch/x86/kvm/xen.c
@@ -30,13 +30,14 @@
 #include "cpuid.h"
 #include "trace.h"
 
-static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm);
+static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,
+			      bool wait);
 static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data);
-static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);
+static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r);
 
 DEFINE_STATIC_KEY_DEFERRED_FALSE(kvm_xen_enabled, HZ);
 
-static int kvm_xen_shared_info_init(struct kvm *kvm)
+static int kvm_xen_shared_info_init(struct kvm *kvm, bool wait)
 {
 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
 	struct pvclock_wall_clock *wc;
@@ -44,17 +45,24 @@ static int kvm_xen_shared_info_init(struct kvm *kvm)
 	u32 wc_version;
 	u64 wall_nsec;
 	int ret = 0;
-	int idx = srcu_read_lock(&kvm->srcu);
+	int idx;
 
-	read_lock_irq(&gpc->lock);
-	while (!kvm_gpc_check(gpc, PAGE_SIZE)) {
+	/*
+	 * kvm_gpc_check() consults the memslots, so take kvm->srcu around
+	 * each check and the write through the mapping — but not across
+	 * the refresh, which may wait for a memslot update to complete.
+	 */
+	for (;;) {
+		idx = srcu_read_lock(&kvm->srcu);
+		read_lock_irq(&gpc->lock);
+		if (kvm_gpc_check(gpc, PAGE_SIZE))
+			break;
 		read_unlock_irq(&gpc->lock);
+		srcu_read_unlock(&kvm->srcu, idx);
 
-		ret = kvm_gpc_refresh(gpc, PAGE_SIZE);
+		ret = kvm_gpc_refresh(gpc, PAGE_SIZE, wait);
 		if (ret)
 			goto out;
-
-		read_lock_irq(&gpc->lock);
 	}
 
 	/*
@@ -98,9 +106,9 @@ static int kvm_xen_shared_info_init(struct kvm *kvm)
 
 	wc->version = wc_version + 1;
 	read_unlock_irq(&gpc->lock);
+	srcu_read_unlock(&kvm->srcu, idx);
 
 out:
-	srcu_read_unlock(&kvm->srcu, idx);
 	return ret;
 }
 
@@ -108,13 +116,35 @@ void kvm_xen_inject_timer_irqs(struct kvm_vcpu *vcpu)
 {
 	if (atomic_read(&vcpu->arch.xen.timer_pending) > 0) {
 		struct kvm_xen_evtchn e;
+		int rc;
 
 		e.vcpu_id = vcpu->vcpu_id;
 		e.vcpu_idx = vcpu->vcpu_idx;
 		e.port = vcpu->arch.xen.timer_virq;
 		e.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;
 
-		kvm_xen_set_evtchn(&e, vcpu->kvm);
+		rc = kvm_xen_set_evtchn(&e, vcpu->kvm, false);
+
+		/*
+		 * Leave timer_pending set if the memslot is being updated
+		 * (-EAGAIN); delivery is retried on the next entry pass.
+		 */
+		if (rc == -EAGAIN)
+			return;
+
+		/*
+		 * If the event cannot currently be delivered (-EINVAL:
+		 * deactivated shared_info, or an out-of-range port), clear
+		 * timer_pending — a halted vCPU would otherwise spin on
+		 * kvm_cpu_has_pending_timer() — but keep timer_expires,
+		 * which still reports the event as owed through
+		 * KVM_XEN_VCPU_GET_ATTR; re-arming the timer with an expiry
+		 * in the past fires it again.
+		 */
+		if (rc == -EINVAL) {
+			atomic_set(&vcpu->arch.xen.timer_pending, 0);
+			return;
+		}
 
 		vcpu->arch.xen.timer_expires = 0;
 		atomic_set(&vcpu->arch.xen.timer_pending, 0);
@@ -161,7 +191,7 @@ static int xen_get_guest_pvclock(struct kvm_vcpu *vcpu,
 	while (!kvm_gpc_check(gpc, offset + sizeof(*hv_clock))) {
 		read_unlock_irqrestore(&gpc->lock, flags);
 
-		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock));
+		r = kvm_gpc_refresh(gpc, offset + sizeof(*hv_clock), false);
 		if (r)
 			return r;
 
@@ -435,7 +465,7 @@ static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)
 		if (atomic)
 			return;
 
-		if (kvm_gpc_refresh(gpc1, user_len1))
+		if (kvm_gpc_refresh(gpc1, user_len1, false))
 			return;
 
 		read_lock_irqsave(&gpc1->lock, flags);
@@ -488,7 +518,7 @@ static void kvm_xen_update_runstate_guest(struct kvm_vcpu *v, bool atomic)
 			 * 64-bit mode, the second GPC won't have been set up.
 			 */
 			if (kvm_gpc_activate(gpc2, gpc1->gpa + user_len1,
-					     user_len2))
+					     user_len2, false))
 				return;
 
 			/*
@@ -669,7 +699,7 @@ void kvm_xen_inject_pending_events(struct kvm_vcpu *v)
 	while (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
 		read_unlock_irqrestore(&gpc->lock, flags);
 
-		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info)))
+		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info), false))
 			return;
 
 		read_lock_irqsave(&gpc->lock, flags);
@@ -705,7 +735,6 @@ void kvm_xen_inject_pending_events(struct kvm_vcpu *v)
 		WRITE_ONCE(vi->evtchn_upcall_pending, 1);
 	}
 
-	kvm_gpc_mark_dirty_in_slot(gpc);
 	read_unlock_irqrestore(&gpc->lock, flags);
 
 	/* For the per-vCPU lapic vector, deliver it as MSI. */
@@ -757,7 +786,7 @@ int __kvm_xen_has_interrupt(struct kvm_vcpu *v)
 		if (in_atomic() || !task_is_running(current))
 			return 1;
 
-		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info))) {
+		if (kvm_gpc_refresh(gpc, sizeof(struct vcpu_info), false)) {
 			/*
 			 * If this failed, userspace has screwed up the
 			 * vcpu_info mapping. No interrupts for you.
@@ -792,19 +821,15 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 			 * to make the call anyway.
 			 */
 			r = kvm->arch.xen.shinfo_cache.active ?
-				kvm_xen_shared_info_init(kvm) : 0;
+				kvm_xen_shared_info_init(kvm, true) : 0;
 			mutex_unlock(&kvm->arch.xen.xen_lock);
 		}
 		break;
 
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO:
 	case KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA: {
-		int idx;
-
 		mutex_lock(&kvm->arch.xen.xen_lock);
 
-		idx = srcu_read_lock(&kvm->srcu);
-
 		if (data->type == KVM_XEN_ATTR_TYPE_SHARED_INFO) {
 			gfn_t gfn = data->u.shared_info.gfn;
 
@@ -813,7 +838,7 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 				r = 0;
 			} else {
 				r = kvm_gpc_activate(&kvm->arch.xen.shinfo_cache,
-						     gfn_to_gpa(gfn), PAGE_SIZE);
+						     gfn_to_gpa(gfn), PAGE_SIZE, true);
 			}
 		} else {
 			void __user * hva = u64_to_user_ptr(data->u.shared_info.hva);
@@ -829,10 +854,8 @@ int kvm_xen_hvm_set_attr(struct kvm *kvm, struct kvm_xen_hvm_attr *data)
 			}
 		}
 
-		srcu_read_unlock(&kvm->srcu, idx);
-
 		if (!r && kvm->arch.xen.shinfo_cache.active)
-			r = kvm_xen_shared_info_init(kvm);
+			r = kvm_xen_shared_info_init(kvm, true);
 
 		mutex_unlock(&kvm->arch.xen.xen_lock);
 		break;
@@ -937,7 +960,6 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 	int idx, r = -ENOENT;
 
 	mutex_lock(&vcpu->kvm->arch.xen.xen_lock);
-	idx = srcu_read_lock(&vcpu->kvm->srcu);
 
 	switch (data->type) {
 	case KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO:
@@ -960,7 +982,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 				break;
 
 			r = kvm_gpc_activate(&vcpu->arch.xen.vcpu_info_cache,
-					     data->u.gpa, sizeof(struct vcpu_info));
+					     data->u.gpa, sizeof(struct vcpu_info), true);
 		} else {
 			if (data->u.hva == 0) {
 				kvm_gpc_deactivate(&vcpu->arch.xen.vcpu_info_cache);
@@ -990,7 +1012,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 
 		r = kvm_gpc_activate(&vcpu->arch.xen.vcpu_time_info_cache,
 				     data->u.gpa,
-				     sizeof(struct pvclock_vcpu_time_info));
+				     sizeof(struct pvclock_vcpu_time_info), true);
 		if (!r)
 			kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
 		break;
@@ -1023,7 +1045,7 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		/* How much fits in the (first) page? */
 		sz1 = PAGE_SIZE - (data->u.gpa & ~PAGE_MASK);
 		r = kvm_gpc_activate(&vcpu->arch.xen.runstate_cache,
-				     data->u.gpa, sz1);
+				     data->u.gpa, sz1, true);
 		if (r)
 			goto deactivate_out;
 
@@ -1034,12 +1056,14 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			sz2 = sz - sz1;
 			BUG_ON((data->u.gpa + sz1) & ~PAGE_MASK);
 			r = kvm_gpc_activate(&vcpu->arch.xen.runstate2_cache,
-					     data->u.gpa + sz1, sz2);
+					     data->u.gpa + sz1, sz2, true);
 			if (r)
 				goto deactivate_out;
 		}
 
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
 		kvm_xen_update_runstate_guest(vcpu, false);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 		break;
 	}
 	case KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT:
@@ -1052,7 +1076,9 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 			break;
 		}
 
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
 		kvm_xen_update_runstate(vcpu, data->u.runstate.state);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 		r = 0;
 		break;
 
@@ -1132,10 +1158,12 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		vcpu->arch.xen.runstate_times[RUNSTATE_offline] +=
 			data->u.runstate.time_offline;
 
+		idx = srcu_read_lock(&vcpu->kvm->srcu);
 		if (data->u.runstate.state <= RUNSTATE_offline)
 			kvm_xen_update_runstate(vcpu, data->u.runstate.state);
 		else if (vcpu->arch.xen.runstate_cache.active)
 			kvm_xen_update_runstate_guest(vcpu, false);
+		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 		r = 0;
 		break;
 
@@ -1181,7 +1209,6 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		break;
 	}
 
-	srcu_read_unlock(&vcpu->kvm->srcu, idx);
 	mutex_unlock(&vcpu->kvm->arch.xen.xen_lock);
 	return r;
 }
@@ -1267,12 +1294,13 @@ int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 
 	case KVM_XEN_VCPU_ATTR_TYPE_TIMER:
 		/*
-		 * Ensure a consistent snapshot of state is captured, with a
-		 * timer either being pending, or the event channel delivered
-		 * to the corresponding bit in the shared_info. Not still
-		 * lurking in the timer_pending flag for deferred delivery.
-		 * Purely as an optimisation, if the timer_expires field is
-		 * zero, that means the timer isn't active (or even in the
+		 * Ensure a consistent snapshot of state is captured: a timer
+		 * which already fired has either been delivered to the
+		 * corresponding bit in the shared_info, or is reported as
+		 * still owed (expires_ns != 0, if the shared_info page was
+		 * unavailable). Purely
+		 * as an optimisation, if the timer_expires field is zero,
+		 * that means the timer isn't active (or even in the
 		 * timer_pending flag) and there is no need to cancel it.
 		 */
 		if (vcpu->arch.xen.timer_expires) {
@@ -1291,8 +1319,20 @@ int kvm_xen_vcpu_get_attr(struct kvm_vcpu *vcpu, struct kvm_xen_vcpu_attr *data)
 		 * That's fine, as the guest won't even have had a chance
 		 * to run and handle the interrupt. Asserting an already
 		 * pending event channel is idempotent.
+		 *
+		 * Don't re-arm if the flush above failed transiently and
+		 * left the timer pending: delivery is owned by the retry
+		 * on the guest entry path, and an immediate hrtimer fire
+		 * would race it — the callback's timer_pending suppression
+		 * check is not serialized against the entry path, so a
+		 * late callback could re-assert a port the entry path had
+		 * already delivered and the guest already consumed.
+		 *
+		 * An expiry already in the past fires immediately: the
+		 * event is still owed.
 		 */
-		if (vcpu->arch.xen.timer_expires)
+		if (vcpu->arch.xen.timer_expires &&
+		    !atomic_read(&vcpu->arch.xen.timer_pending))
 			hrtimer_start_expires(&vcpu->arch.xen.timer,
 					      HRTIMER_MODE_ABS_HARD);
 
@@ -1320,7 +1360,15 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
 	bool lm = is_long_mode(vcpu);
 	int r = 0;
 
+	/*
+	 * The attribute ioctls wait out memslot updates while holding
+	 * xen_lock; a memslot update waits for this vCPU's kvm->srcu
+	 * read section to quiesce. Blocking on xen_lock inside that
+	 * read section would close the cycle, so step out of it first.
+	 */
+	kvm_vcpu_srcu_read_unlock(vcpu);
 	mutex_lock(&kvm->arch.xen.xen_lock);
+	kvm_vcpu_srcu_read_lock(vcpu);
 	if (kvm->arch.xen.long_mode != lm) {
 		kvm->arch.xen.long_mode = lm;
 
@@ -1329,7 +1377,7 @@ int kvm_xen_write_hypercall_page(struct kvm_vcpu *vcpu, u64 data)
 		 * correct place.
 		 */
 		if (kvm->arch.xen.shinfo_cache.active &&
-		    kvm_xen_shared_info_init(kvm))
+		    kvm_xen_shared_info_init(kvm, false))
 			r = 1;
 	}
 	mutex_unlock(&kvm->arch.xen.xen_lock);
@@ -1775,8 +1823,21 @@ int kvm_xen_hypercall(struct kvm_vcpu *vcpu)
 		}
 		break;
 	case __HYPERVISOR_event_channel_op:
-		if (params[0] == EVTCHNOP_send)
-			handled = kvm_xen_hcall_evtchn_send(vcpu, params[1], &r);
+		if (params[0] == EVTCHNOP_send) {
+			int ret = kvm_xen_hcall_evtchn_send(vcpu, params[1], &r);
+
+			/*
+			 * Delivery raced a memslot update; waiting for it
+			 * here would deadlock under vcpu_run's kvm->srcu
+			 * read section. Leave the hypercall uncompleted —
+			 * RIP not advanced — so the guest re-executes it.
+			 * Each attempt cycles the srcu read section on the
+			 * way back in, letting the update complete.
+			 */
+			if (ret == -EAGAIN)
+				return 1;
+			handled = !ret;
+		}
 		break;
 	case __HYPERVISOR_sched_op:
 		handled = kvm_xen_hcall_sched_op(vcpu, is_64bit, params[0],
@@ -1831,6 +1892,89 @@ static void kvm_xen_check_poller(struct kvm_vcpu *vcpu, int port)
 	}
 }
 
+static void __kvm_xen_set_evtchn_fast(struct kvm_vcpu *vcpu, int port_word_bit,
+				      bool has_64bit_shinfo)
+{
+	struct gfn_to_pfn_cache *gpc = &vcpu->arch.xen.vcpu_info_cache;
+	unsigned long vi_pending_sel_ofs;
+	bool inject_upcall = false;
+	bool kick_vcpu = false;
+	unsigned long flags;
+	bool old;
+
+	vi_pending_sel_ofs = has_64bit_shinfo ?
+		offsetof(struct vcpu_info, evtchn_pending_sel) :
+		offsetof(struct compat_vcpu_info, evtchn_pending_sel);
+
+	/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */
+	read_lock_irqsave(&gpc->lock, flags);
+	if (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
+		/*
+		 * Could not access the vcpu_info. Set the bit in-kernel and
+		 * prod the vCPU to deliver it for itself. Note that an MSI is
+		 * *not* an acceptable substitute here even if the vCPU has an
+		 * upcall vector: the pending bit only exists in
+		 * evtchn_pending_sel so far, and the vCPU has to be forced
+		 * out of the guest so that kvm_xen_inject_pending_events()
+		 * can refresh the cache and propagate it to the guest.
+		 */
+		if (!test_and_set_bit(port_word_bit, &vcpu->arch.xen.evtchn_pending_sel))
+			kick_vcpu = true;
+		goto out_unlock;
+	}
+	inject_upcall = true;
+
+	/*
+	 * Explicitly use a 32-bit btsl instead of test_and_set_bit(), which
+	 * would use btsq on x86-64. The vcpu_info is guest-controlled and only
+	 * required to be 32-bit aligned, so a 64-bit access could generate a
+	 * split-lock #AC.
+	 *
+	 * Note, this does not apply to the test_and_set_bit() on pending_bits
+	 * in the caller: that is in the per-VM shared_info, which is page
+	 * aligned, so the access is guaranteed to be 64-bit aligned.
+	 */
+	old = GEN_BINARY_RMWcc(LOCK_PREFIX "btsl",
+			       *(u32 *)(gpc->khva + vi_pending_sel_ofs),
+			       c, "Ir", port_word_bit);
+	if (!old) {
+		struct vcpu_info *vi = gpc->khva;
+
+		/* No need for compat handling */
+		BUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=
+			     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));
+
+		WRITE_ONCE(vi->evtchn_upcall_pending, 1);
+		kick_vcpu = true;
+	}
+
+out_unlock:
+	read_unlock_irqrestore(&gpc->lock, flags);
+
+	/*
+	 * Deliver the upcall or kick the vCPU only after dropping the GPC
+	 * read lock. Both paths end up in kvm_vcpu_kick(), and the MSI
+	 * delivery also walks the APIC map and takes APIC locks; none of
+	 * that wants to be nested inside the GPC read lock, which a
+	 * concurrent invalidation may be waiting to take for write.
+	 */
+	if (!kick_vcpu)
+		return;
+
+	/*
+	 * For the per-vCPU lapic vector, deliver it as MSI — but only if the
+	 * vcpu_info was actually updated above. If it wasn't, the vCPU must
+	 * be kicked instead (see above).
+	 */
+	if (inject_upcall && vcpu->arch.xen.upcall_vector) {
+		kvm_xen_inject_vcpu_vector(vcpu);
+		return;
+	}
+
+	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
+	kvm_vcpu_kick(vcpu);
+}
+
 /*
  * The return value from this function is propagated to kvm_set_irq() API,
  * so it returns:
@@ -1845,11 +1989,10 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 {
 	struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
 	bool has_64bit_shinfo = kvm_xen_has_64bit_shinfo(kvm);
-	unsigned long *pending_bits, *mask_bits, vi_pending_sel_ofs;
+	unsigned long *pending_bits, *mask_bits;
 	struct kvm_vcpu *vcpu;
 	unsigned long flags;
 	int port_word_bit;
-	bool kick_vcpu = false;
 	int vcpu_idx, idx, rc;
 
 	vcpu_idx = READ_ONCE(xe->vcpu_idx);
@@ -1871,23 +2014,19 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 
 	read_lock_irqsave(&gpc->lock, flags);
 	if (!kvm_gpc_check(gpc, PAGE_SIZE))
-		goto out_rcu;
+		goto out_unlock;
 
 	if (has_64bit_shinfo) {
 		struct shared_info *shinfo = gpc->khva;
 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
 		mask_bits = (unsigned long *)&shinfo->evtchn_mask;
 		port_word_bit = xe->port / 64;
-
-		vi_pending_sel_ofs = offsetof(struct vcpu_info, evtchn_pending_sel);
 	} else {
 		struct compat_shared_info *shinfo = gpc->khva;
 		pending_bits = (unsigned long *)&shinfo->evtchn_pending;
 		mask_bits = (unsigned long *)&shinfo->evtchn_mask;
 		port_word_bit = xe->port / 32;
 
-		vi_pending_sel_ofs = offsetof(struct compat_vcpu_info, evtchn_pending_sel);
-
 		/* test_and_set_bit() needs 64-bit alignment, but that's OK */
 		BUILD_BUG_ON(offsetof(struct compat_shared_info, evtchn_pending) & 7);
 	}
@@ -1903,71 +2042,30 @@ int kvm_xen_set_evtchn_fast(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 		rc = 0; /* It was already raised */
 	} else if (test_bit(xe->port, mask_bits)) {
 		rc = -ENOTCONN; /* Masked */
-		kvm_xen_check_poller(vcpu, xe->port);
 	} else {
-		bool old;
-
 		rc = 1; /* Delivered to the bitmap in shared_info. */
-		/* Now switch to the vCPU's vcpu_info to set the index and pending_sel */
-		read_unlock_irqrestore(&gpc->lock, flags);
-		gpc = &vcpu->arch.xen.vcpu_info_cache;
-
-		read_lock_irqsave(&gpc->lock, flags);
-		if (!kvm_gpc_check(gpc, sizeof(struct vcpu_info))) {
-			/*
-			 * Could not access the vcpu_info. Set the bit in-kernel
-			 * and prod the vCPU to deliver it for itself.
-			 */
-			if (!test_and_set_bit(port_word_bit, &vcpu->arch.xen.evtchn_pending_sel))
-				kick_vcpu = true;
-			goto out_rcu;
-		}
-
-		/*
-		 * Explicitly use a 32-bit btsl instead of test_and_set_bit(),
-		 * which would use btsq on x86-64. The vcpu_info is guest-
-		 * controlled and only required to be 32-bit aligned, so a
-		 * 64-bit access could generate a split-lock #AC.
-		 *
-		 * Note, this does not apply to the test_and_set_bit() on
-		 * pending_bits above: that is in the per-VM shared_info, which
-		 * is page aligned, so the access is guaranteed to be 64-bit
-		 * aligned.
-		 */
-		old = GEN_BINARY_RMWcc(LOCK_PREFIX "btsl",
-				       *(u32 *)(gpc->khva + vi_pending_sel_ofs),
-				       c, "Ir", port_word_bit);
-		if (!old) {
-			struct vcpu_info *vi = gpc->khva;
-
-			/* No need for compat handling */
-			BUILD_BUG_ON(offsetof(struct vcpu_info, evtchn_upcall_pending) !=
-				     offsetof(struct compat_vcpu_info, evtchn_upcall_pending));
-
-			WRITE_ONCE(vi->evtchn_upcall_pending, 1);
-			kick_vcpu = true;
-		}
-
-		/* For the per-vCPU lapic vector, deliver it as MSI. */
-		if (kick_vcpu && vcpu->arch.xen.upcall_vector) {
-			kvm_xen_inject_vcpu_vector(vcpu);
-			kick_vcpu = false;
-		}
 	}
 
- out_rcu:
+ out_unlock:
 	read_unlock_irqrestore(&gpc->lock, flags);
-	srcu_read_unlock(&kvm->srcu, idx);
 
-	if (kick_vcpu) {
-		kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
-		kvm_vcpu_kick(vcpu);
-	}
+	/*
+	 * Both of these can kick the vCPU, so keep them outside the GPC
+	 * read lock; an invalidation may be waiting to take it for write.
+	 */
+	if (rc == -ENOTCONN)
+		kvm_xen_check_poller(vcpu, xe->port);
+	else if (rc == 1)
+		__kvm_xen_set_evtchn_fast(vcpu, port_word_bit,
+					  has_64bit_shinfo);
+
+	srcu_read_unlock(&kvm->srcu, idx);
 
 	return rc;
 }
 
-static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
+static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm,
+			      bool wait)
 {
 	bool mm_borrowed = false;
 	int rc;
@@ -2004,16 +2102,13 @@ static int kvm_xen_set_evtchn(struct kvm_xen_evtchn *xe, struct kvm *kvm)
 	 */
 	do {
 		struct gfn_to_pfn_cache *gpc = &kvm->arch.xen.shinfo_cache;
-		int idx;
 
 		rc = kvm_xen_set_evtchn_fast(xe, kvm);
 		if (rc != -EWOULDBLOCK)
 			break;
 
-		idx = srcu_read_lock(&kvm->srcu);
-		rc = kvm_gpc_refresh(gpc, PAGE_SIZE);
-		srcu_read_unlock(&kvm->srcu, idx);
-	} while(!rc);
+		rc = kvm_gpc_refresh(gpc, PAGE_SIZE, wait);
+	} while (!rc);
 
 	if (mm_borrowed)
 		kthread_unuse_mm(kvm->mm);
@@ -2028,7 +2123,7 @@ static int evtchn_set_fn(struct kvm_kernel_irq_routing_entry *e, struct kvm *kvm
 	if (!level)
 		return -EINVAL;
 
-	return kvm_xen_set_evtchn(&e->xen_evtchn, kvm);
+	return kvm_xen_set_evtchn(&e->xen_evtchn, kvm, true);
 }
 
 /*
@@ -2102,7 +2197,7 @@ int kvm_xen_hvm_evtchn_send(struct kvm *kvm, struct kvm_irq_routing_xen_evtchn *
 	e.vcpu_idx = -1;
 	e.priority = uxe->priority;
 
-	ret = kvm_xen_set_evtchn(&e, kvm);
+	ret = kvm_xen_set_evtchn(&e, kvm, true);
 
 	/*
 	 * None of that 'return 1 if it actually got delivered' nonsense.
@@ -2331,7 +2426,11 @@ static int kvm_xen_setattr_evtchn(struct kvm *kvm, struct kvm_xen_hvm_attr *data
 	return kvm_xen_eventfd_assign(kvm, data);
 }
 
-static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
+/*
+ * Returns 0 with *r set if handled, -EAGAIN if the hypercall should be
+ * re-executed by the guest, or -ENOENT to hand it to userspace.
+ */
+static int kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
 {
 	struct evtchnfd *evtchnfd;
 	struct evtchn_send send;
@@ -2341,7 +2440,7 @@ static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
 	BUILD_BUG_ON(sizeof(send) != 4);
 	if (kvm_read_guest_virt(vcpu, param, &send, sizeof(send), &e)) {
 		*r = -EFAULT;
-		return true;
+		return 0;
 	}
 
 	/*
@@ -2350,18 +2449,22 @@ static bool kvm_xen_hcall_evtchn_send(struct kvm_vcpu *vcpu, u64 param, u64 *r)
 	 */
 	evtchnfd = xa_load(&vcpu->kvm->arch.xen.evtchn_ports, send.port);
 	if (!evtchnfd)
-		return false;
+		return -ENOENT;
 
 	if (evtchnfd->deliver.port.port) {
-		int ret = kvm_xen_set_evtchn(&evtchnfd->deliver.port, vcpu->kvm);
+		int ret = kvm_xen_set_evtchn(&evtchnfd->deliver.port,
+					     vcpu->kvm, false);
+
+		if (ret == -EAGAIN)
+			return ret;
 		if (ret < 0 && ret != -ENOTCONN)
-			return false;
+			return -ENOENT;
 	} else {
 		eventfd_signal(evtchnfd->deliver.eventfd.ctx);
 	}
 
 	*r = 0;
-	return true;
+	return 0;
 }
 
 void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)
@@ -2375,7 +2478,7 @@ void kvm_xen_init_vcpu(struct kvm_vcpu *vcpu)
 
 	kvm_gpc_init(&vcpu->arch.xen.runstate_cache, vcpu->kvm);
 	kvm_gpc_init(&vcpu->arch.xen.runstate2_cache, vcpu->kvm);
-	kvm_gpc_init(&vcpu->arch.xen.vcpu_info_cache, vcpu->kvm);
+	__kvm_gpc_init(&vcpu->arch.xen.vcpu_info_cache, vcpu->kvm, true);
 	kvm_gpc_init(&vcpu->arch.xen.vcpu_time_info_cache, vcpu->kvm);
 }
 
@@ -2396,7 +2499,7 @@ void kvm_xen_init_vm(struct kvm *kvm)
 {
 	mutex_init(&kvm->arch.xen.xen_lock);
 	xa_init(&kvm->arch.xen.evtchn_ports);
-	kvm_gpc_init(&kvm->arch.xen.shinfo_cache, kvm);
+	__kvm_gpc_init(&kvm->arch.xen.shinfo_cache, kvm, true);
 }
 
 void kvm_xen_destroy_vm(struct kvm *kvm)
diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h
index 3dd04605f2e55..debce84f4177c 100644
--- a/include/linux/kvm_host.h
+++ b/include/linux/kvm_host.h
@@ -1465,7 +1465,13 @@ int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by
  * the caller before init).
  */
-void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);
+void __kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm,
+		    bool never_dirty);
+
+static inline void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)
+{
+	__kvm_gpc_init(gpc, kvm, false);
+}
 
 /**
  * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest
@@ -1474,16 +1480,24 @@ void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);
  * @gpc:	   struct gfn_to_pfn_cache object.
  * @gpa:	   guest physical address to map.
  * @len:	   sanity check; the range being access must fit a single page.
+ * @wait:	   wait out a concurrent memslot update instead of returning
+ *		   -EAGAIN. May not be used while this task holds any kvm->srcu
+ *		   read section, and no lock held across the wait may ever be
+ *		   taken within one: the update's synchronize_srcu() would
+ *		   deadlock against the wait. Lockdep checks both.
  *
  * @return:	   0 for success.
  *		   -EINVAL for a mapping which would cross a page boundary.
  *		   -EFAULT for an untranslatable guest physical address.
+ *		   -EAGAIN if the memslot is being updated (only with
+ *		   wait == false, or on a fatal signal while waiting).
  *
  * This primes a gfn_to_pfn_cache and links it into the @gpc->kvm's list for
  * invalidations to be processed.  Callers are required to use kvm_gpc_check()
  * to ensure that the cache is valid before accessing the target page.
  */
-int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len);
+int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len,
+		     bool wait);
 
 /**
  * kvm_gpc_activate_hva - prepare a cached kernel mapping and HPA for a given HVA.
@@ -1499,7 +1513,8 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
  * The semantics of this function are the same as those of kvm_gpc_activate(). It
  * merely bypasses a layer of address translation.
  */
-int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva, unsigned long len);
+int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva,
+			 unsigned long len);
 
 /**
  * kvm_gpc_check - check validity of a gfn_to_pfn_cache.
@@ -1524,10 +1539,13 @@ bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);
  *
  * @gpc:	   struct gfn_to_pfn_cache object.
  * @len:	   sanity check; the range being access must fit a single page.
+ * @wait:	   as kvm_gpc_activate().
  *
  * @return:	   0 for success.
  *		   -EINVAL for a mapping which would cross a page boundary.
  *		   -EFAULT for an untranslatable guest physical address.
+ *		   -EAGAIN if the memslot is being updated (only with
+ *		   wait == false, or on a fatal signal while waiting).
  *
  * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful
  * return from this function does not mean the page can be immediately
@@ -1535,7 +1553,7 @@ bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);
  * still lock and check the cache status, as this function does not return
  * with the lock still held to permit access.
  */
-int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len);
+int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait);
 
 /**
  * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache.
@@ -1976,7 +1994,7 @@ static inline void kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache *gpc)
 {
 	lockdep_assert_held(&gpc->lock);
 
-	if (!gpc->memslot)
+	if (!gpc->memslot || gpc->never_dirty)
 		return;
 
 	mark_page_dirty_in_slot(gpc->kvm, gpc->memslot, gpa_to_gfn(gpc->gpa));
diff --git a/include/linux/kvm_types.h b/include/linux/kvm_types.h
index a568d8e6f4e82..e850adc3f47ef 100644
--- a/include/linux/kvm_types.h
+++ b/include/linux/kvm_types.h
@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {
 	kvm_pfn_t pfn;
 	bool active;
 	bool valid;
+	bool never_dirty;
 };
 
 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selftests/kvm/Makefile.kvm
index 96bab7002d39e..e7e17d19d6cbb 100644
--- a/tools/testing/selftests/kvm/Makefile.kvm
+++ b/tools/testing/selftests/kvm/Makefile.kvm
@@ -144,6 +144,7 @@ TEST_GEN_PROGS_x86 += x86/xss_msr_test
 TEST_GEN_PROGS_x86 += x86/debug_regs
 TEST_GEN_PROGS_x86 += x86/tsc_msrs_test
 TEST_GEN_PROGS_x86 += x86/vmx_pmu_caps_test
+TEST_GEN_PROGS_x86 += x86/xen_evtchn_memslot_race_test
 TEST_GEN_PROGS_x86 += x86/xen_shinfo_test
 TEST_GEN_PROGS_x86 += x86/xen_vmcall_test
 TEST_GEN_PROGS_x86 += x86/sev_dbg_test
diff --git a/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c b/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c
new file mode 100644
index 0000000000000..2b6974d3d4645
--- /dev/null
+++ b/tools/testing/selftests/kvm/x86/xen_evtchn_memslot_race_test.c
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * xen_evtchn_memslot_race_test
+ *
+ * A guest EVTCHNOP_send whose delivery races a DELETE/re-CREATE of the
+ * memslot holding the shared_info page. The delivery path runs in the
+ * vCPU's exit-handling context, under vcpu_run's kvm->srcu read
+ * section; if it waits there for the memslot update to complete, it
+ * deadlocks against kvm_swap_active_memslots()'s
+ * synchronize_srcu_expedited() waiting out that very read section.
+ * Regression test for that deadlock: KVM must defer the delivery to
+ * the next guest entry rather than spin in exit context.
+ *
+ * The guest sends events in a tight loop; a host thread deletes and
+ * recreates the shared_info slot in a tight loop. On a broken host
+ * this livelocks within a second or two (the test then dies by
+ * timeout); on a fixed host every send eventually delivers and the
+ * test completes N iterations.
+ */
+#include <pthread.h>
+#include <stdatomic.h>
+
+#include "test_util.h"
+#include "kvm_util.h"
+#include "processor.h"
+
+#include <stdint.h>
+
+#define SHINFO_REGION_GPA	0xc0000000ULL
+#define SHINFO_REGION_SLOT	10
+
+#define EVTCHN_PORT		15
+#define TEST_ITERATIONS		4000
+
+#define EVTCHNOP_send		4
+#define __HYPERVISOR_event_channel_op	32
+
+#define XEN_HYPERCALL_MSR	0x40000000
+
+#define EVTCHNSTAT_ipi		5
+
+struct evtchn_send {
+	uint32_t port;
+};
+
+static void guest_code(void)
+{
+	struct evtchn_send s = { .port = EVTCHN_PORT };
+	int i;
+
+	for (i = 0; i < TEST_ITERATIONS; i++) {
+		/*
+		 * The delivery may legitimately fail while the shared_info
+		 * slot is mid-churn (between DELETE and re-CREATE there is
+		 * no slot at all, which is -EFAULT, not a transient). The
+		 * failure mode under test is the vCPU never coming back at
+		 * all (deadlock -> timeout), not the hypercall rc.
+		 */
+		__xen_hypercall(__HYPERVISOR_event_channel_op, EVTCHNOP_send, &s);
+		GUEST_SYNC(i);
+	}
+
+	GUEST_DONE();
+}
+
+static atomic_bool churn_stop;
+
+static void *memslot_churn(void *arg)
+{
+	struct kvm_vm *vm = arg;
+
+	while (!atomic_load(&churn_stop)) {
+		vm_mem_region_delete(vm, SHINFO_REGION_SLOT);
+		vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
+					    SHINFO_REGION_GPA,
+					    SHINFO_REGION_SLOT, 2, 0);
+	}
+	return NULL;
+}
+
+int main(int argc, char *argv[])
+{
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	pthread_t thread;
+	struct ucall uc;
+	int done = 0;
+	int r;
+
+	int xen_caps = kvm_check_cap(KVM_CAP_XEN_HVM);
+
+	TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_SHARED_INFO);
+	TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_EVTCHN_SEND);
+
+	vm = vm_create_with_one_vcpu(&vcpu, guest_code);
+
+	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
+				    SHINFO_REGION_GPA, SHINFO_REGION_SLOT, 2, 0);
+
+	struct kvm_xen_hvm_config hvmc = {
+		.flags = KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL |
+			 KVM_XEN_HVM_CONFIG_EVTCHN_SEND,
+		.msr = XEN_HYPERCALL_MSR,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_CONFIG, &hvmc);
+
+	struct kvm_xen_hvm_attr lm = {
+		.type = KVM_XEN_ATTR_TYPE_LONG_MODE,
+		.u.long_mode = 1,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &lm);
+
+	struct kvm_xen_hvm_attr ha = {
+		.type = KVM_XEN_ATTR_TYPE_SHARED_INFO,
+		.u.shared_info.gfn = SHINFO_REGION_GPA / PAGE_SIZE,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &ha);
+
+	struct kvm_xen_vcpu_attr vi = {
+		.type = KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO,
+		.u.gpa = SHINFO_REGION_GPA + 0x40,
+	};
+	vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &vi);
+
+	/* Loop the port back to this vCPU as an IPI. */
+	struct kvm_xen_hvm_attr evt = {
+		.type = KVM_XEN_ATTR_TYPE_EVTCHN,
+		.u.evtchn.send_port = EVTCHN_PORT,
+		.u.evtchn.type = EVTCHNSTAT_ipi,
+		.u.evtchn.flags = 0,
+		.u.evtchn.deliver.port.port = EVTCHN_PORT,
+		.u.evtchn.deliver.port.vcpu = vcpu->id,
+		.u.evtchn.deliver.port.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL,
+	};
+	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &evt);
+
+	r = pthread_create(&thread, NULL, memslot_churn, vm);
+	TEST_ASSERT(!r, "pthread_create() failed: %d", r);
+
+	while (!done) {
+		vcpu_run(vcpu);
+
+		/*
+		 * In the window where the shared_info slot is fully deleted
+		 * (between the churn thread's DELETE and re-CREATE), the
+		 * delivery fails with -EFAULT and the hypercall bounces to
+		 * userspace as KVM_EXIT_XEN. Complete it with an error
+		 * result and keep going; the failure mode under test is
+		 * the vCPU never coming back (deadlock -> timeout), not
+		 * the hypercall rc.
+		 */
+		if (vcpu->run->exit_reason == KVM_EXIT_XEN &&
+		    vcpu->run->xen.type == KVM_EXIT_XEN_HCALL) {
+			vcpu->run->xen.u.hcall.result = -EFAULT;
+			continue;
+		}
+
+		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
+
+		switch (get_ucall(vcpu, &uc)) {
+		case UCALL_SYNC:
+			break;
+		case UCALL_DONE:
+			done = 1;
+			break;
+		case UCALL_ABORT:
+			REPORT_GUEST_ASSERT(uc);
+		default:
+			TEST_FAIL("Unexpected ucall %lu", uc.cmd);
+		}
+	}
+
+	atomic_store(&churn_stop, true);
+	pthread_join(thread, NULL);
+
+	kvm_vm_free(vm);
+	return 0;
+}
diff --git a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
index aaa414c677add..3b11d0ee253f5 100644
--- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
+++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c
@@ -356,11 +356,12 @@ static void guest_code(void)
 wait_for_timer:
 	/*
 	 * Poll for a timer wake event while the worker thread is mucking with
-	 * the shared info.  KVM XEN drops timer IRQs if the shared info is
-	 * invalid when the timer expires.  Arbitrarily poll 100 times before
-	 * giving up and asking the VMM to re-arm the timer.  100 polls should
-	 * consume enough time to beat on KVM without taking too long if the
-	 * timer IRQ is dropped due to an invalid event channel.
+	 * the shared info.  KVM is now supposed to retry a timer IRQ whose
+	 * delivery hit an invalid shared info rather than drop it, but older
+	 * kernels drop it on the floor.  Arbitrarily poll 100 times before
+	 * giving up and asking the VMM to re-arm the timer, so the test still
+	 * completes (and documents the VMM-side recovery protocol) on
+	 * unfixed kernels.
 	 */
 	for (i = 0; i < 100 && !guest_saw_irq; i++)
 		__xen_hypercall(__HYPERVISOR_sched_op, SCHEDOP_poll, &p);
diff --git a/virt/kvm/pfncache.c b/virt/kvm/pfncache.c
index 3659686b97c24..8498abb746ade 100644
--- a/virt/kvm/pfncache.c
+++ b/virt/kvm/pfncache.c
@@ -304,7 +304,22 @@ static int __kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned l
 			gpc->uhva = gfn_to_hva_memslot(gpc->memslot, gfn);
 
 			if (kvm_is_error_hva(gpc->uhva)) {
-				ret = -EFAULT;
+				/*
+				 * A slot being deleted or moved is present
+				 * but flagged invalid; the lookup failure is
+				 * transient, resolved when the update
+				 * completes (or reverts) and announced by a
+				 * new memslot generation. Distinguish that
+				 * from a genuinely unbacked gfn so that the
+				 * caller may retry rather than report an
+				 * error, as RET_PF_RETRY does for ordinary
+				 * guest faults.
+				 */
+				if (gpc->memslot &&
+				    (gpc->memslot->flags & KVM_MEMSLOT_INVALID))
+					ret = -EAGAIN;
+				else
+					ret = -EFAULT;
 				goto out;
 			}
 
@@ -363,26 +378,67 @@ static int __kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned l
 	return ret;
 }
 
-int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len)
+/*
+ * One refresh attempt, under the caller's refresh_lock. Takes a kvm->srcu
+ * read section for the attempt, as the memslot lookups consult the active
+ * memslots.
+ */
+static int gpc_refresh_locked(struct gfn_to_pfn_cache *gpc, gpa_t gpa,
+			      unsigned long uhva)
 {
-	unsigned long uhva;
+	int idx, ret;
 
-	guard(mutex)(&gpc->refresh_lock);
+	idx = srcu_read_lock(&gpc->kvm->srcu);
+	ret = __kvm_gpc_refresh(gpc, gpa, uhva);
+	srcu_read_unlock(&gpc->kvm->srcu, idx);
 
-	if (!kvm_gpc_is_valid_len(gpc->gpa, gpc->uhva, len))
-		return -EINVAL;
+	return ret;
+}
+
+int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len, bool wait)
+{
+	unsigned long uhva;
+	int ret;
 
 	/*
-	 * If the GPA is valid then ignore the HVA, as a cache can be GPA-based
-	 * or HVA-based, not both.  For GPA-based caches, the HVA will be
-	 * recomputed during refresh if necessary.
+	 * The wait completes only after a memslot update's
+	 * synchronize_srcu(&kvm->srcu), so it functions as one for lockdep:
+	 * taking any lock held across it within a kvm->srcu read section
+	 * is reported as the deadlock it would be.
 	 */
-	uhva = kvm_is_error_gpa(gpc->gpa) ? gpc->uhva : KVM_HVA_ERR_BAD;
+	if (wait)
+		srcu_lock_sync(&gpc->kvm->srcu.dep_map);
+
+	for (;;) {
+		scoped_guard(mutex, &gpc->refresh_lock) {
+			if (!kvm_gpc_is_valid_len(gpc->gpa, gpc->uhva, len))
+				return -EINVAL;
 
-	return __kvm_gpc_refresh(gpc, gpc->gpa, uhva);
+			/*
+			 * If the GPA is valid then ignore the HVA, as a cache
+			 * can be GPA-based or HVA-based, not both.  For
+			 * GPA-based caches, the HVA will be recomputed during
+			 * refresh if necessary.
+			 */
+			uhva = kvm_is_error_gpa(gpc->gpa) ? gpc->uhva : KVM_HVA_ERR_BAD;
+
+			ret = gpc_refresh_locked(gpc, gpc->gpa, uhva);
+		}
+
+		if (ret != -EAGAIN || !wait || fatal_signal_pending(current))
+			return ret;
+
+		/*
+		 * Wait with refresh_lock dropped: a kvm->srcu reader blocked
+		 * on it must be able to proceed and quiesce, or the memslot
+		 * update being waited for could never complete.
+		 */
+		cond_resched();
+	}
 }
 
-void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)
+void __kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm,
+		    bool never_dirty)
 {
 	rwlock_init(&gpc->lock);
 	mutex_init(&gpc->refresh_lock);
@@ -392,39 +448,55 @@ void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm)
 	gpc->gpa = INVALID_GPA;
 	gpc->uhva = KVM_HVA_ERR_BAD;
 	gpc->active = gpc->valid = false;
+	gpc->never_dirty = never_dirty;
 }
 
 static int __kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long uhva,
-			      unsigned long len)
+			      unsigned long len, bool wait)
 {
 	struct kvm *kvm = gpc->kvm;
 
 	if (!kvm_gpc_is_valid_len(gpa, uhva, len))
 		return -EINVAL;
 
-	guard(mutex)(&gpc->refresh_lock);
-
-	if (!gpc->active) {
-		if (KVM_BUG_ON(gpc->valid, kvm))
-			return -EIO;
+	/* As in kvm_gpc_refresh(): the wait is a synchronize_srcu() to lockdep. */
+	if (wait)
+		srcu_lock_sync(&kvm->srcu.dep_map);
+
+	for (;;) {
+		int ret;
+
+		scoped_guard(mutex, &gpc->refresh_lock) {
+			if (!gpc->active) {
+				if (KVM_BUG_ON(gpc->valid, kvm))
+					return -EIO;
+
+				spin_lock(&kvm->gpc_lock);
+				list_add(&gpc->list, &kvm->gpc_list);
+				spin_unlock(&kvm->gpc_lock);
+
+				/*
+				 * Activate the cache after adding it to the
+				 * list, a concurrent refresh must not
+				 * establish a mapping until the cache is
+				 * reachable by mmu_notifier events.
+				 */
+				write_lock_irq(&gpc->lock);
+				gpc->active = true;
+				write_unlock_irq(&gpc->lock);
+			}
+			ret = gpc_refresh_locked(gpc, gpa, uhva);
+		}
 
-		spin_lock(&kvm->gpc_lock);
-		list_add(&gpc->list, &kvm->gpc_list);
-		spin_unlock(&kvm->gpc_lock);
+		if (ret != -EAGAIN || !wait || fatal_signal_pending(current))
+			return ret;
 
-		/*
-		 * Activate the cache after adding it to the list, a concurrent
-		 * refresh must not establish a mapping until the cache is
-		 * reachable by mmu_notifier events.
-		 */
-		write_lock_irq(&gpc->lock);
-		gpc->active = true;
-		write_unlock_irq(&gpc->lock);
+		cond_resched();
 	}
-	return __kvm_gpc_refresh(gpc, gpa, uhva);
 }
 
-int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
+int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len,
+		     bool wait)
 {
 	/*
 	 * Explicitly disallow INVALID_GPA so that the magic value can be used
@@ -433,15 +505,17 @@ int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len)
 	if (WARN_ON_ONCE(kvm_is_error_gpa(gpa)))
 		return -EINVAL;
 
-	return __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len);
+	return __kvm_gpc_activate(gpc, gpa, KVM_HVA_ERR_BAD, len, wait);
 }
 
-int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva, unsigned long len)
+int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long uhva,
+			 unsigned long len)
 {
 	if (!access_ok((void __user *)uhva, len))
 		return -EINVAL;
 
-	return __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len);
+	/* An HVA-based cache never consults the memslots, so never waits. */
+	return __kvm_gpc_activate(gpc, INVALID_GPA, uhva, len, false);
 }
 
 void kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc)

39/3 2026/10/15 02:34 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 21410
							output: 23
							thoughts: 1488
						

Thoughts:
**Analyzing the KVM Patch Series for KMSAN Implications**

Okay, let's break down this KVM patch series. My initial thought is to understand the scope: KVM x86, KVM Xen emulation, and `gfn_to_pfn_cache`. It's a fairly focused area, which is good. The key goal is determining if these changes warrant a KMSAN run, which means hunting for potential uninitialized memory reads or leaks.

First, the documentation updates are likely fine. Comments in `kvm_host.h` are also not concerning. The changes in `msrs.c`, `x86.c`, and `xen.c` look related to Xen and guest-virtualized clock synchronization and event handling. The introduction of `wait` parameters to `kvm_gpc_refresh` and associated functions hints that this is all related to synchronization. I'm focusing in on where data *might* be copied to userspace. The `__kvm_gpc_init` usage for `vcpu_info_cache` and `shinfo_cache` with `never_dirty = true` is promising. The `never_dirty` flag implies optimizations, which could easily be a source of uninitialized memory if used incorrectly.

The addition of `never_dirty` to `struct gfn_to_pfn_cache` is worth noting. The new selftest is encouraging, it indicates a focus on specific edge cases. The changes in `pfncache.c` concerning `-EAGAIN` and the `wait` flag suggest the patch is dealing with race conditions. It’s definitely getting my attention now.

Now, the real test: do these patches introduce or modify kernel-to-user data transfers? The KMSAN rule is clear: look for uninitialized memory risks. I need to be *sure*.

I'm specifically looking for `copy_to_user`, `put_user`, netlink skb attributes, ioctl output arguments, socket options, or BPF buffers. I'll focus on `kvm_xen_vcpu_get_attr` and other `get_attr` calls and ioctls. I'm looking for where a structure is passed to userspace and if the data is *fully* initialized.

Checking `kvm_xen_vcpu_get_attr` shows it is not, but I'll continue to examine all the patches.

Inspecting `kvm_xen_inject_timer_irqs` reveals uninitialized values inside `struct kvm_xen_evtchn` being copied. I'll need to figure out how `e` is constructed. This *definitely* requires further investigation using `grepper` to see if the structure is initialized completely, or if some fields are read from uninitialized memory. This could be where the risk lies. The way `e` is being constructed is a red flag.



40/3 2026/10/15 02:34 tool grepper
0m Args:
{
  "Expression": "struct kvm_xen_evtchn \\{"
}

Results:
{
  "Output": "include/linux/kvm_host.h=655=struct kvm_hv_sint {\n--\ninclude/linux/kvm_host.h-659-\ninclude/linux/kvm_host.h:660:struct kvm_xen_evtchn {\ninclude/linux/kvm_host.h-661-\tu32 port;\n"
}

41/3 2026/10/15 02:34 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23640
							output: 38
							thoughts: 28
						

Thoughts:
Okay, let's dive into this. I need to understand how KVM interacts with Xen's event channels, so I should start by examining the `struct kvm_xen_evtchn` definition. Let's see... I'll pull up `include/linux/kvm_host.h` and get that definition. I'm going to look for any clues there about how these are used.



42/3 2026/10/15 02:34 tool read-file
0m Args:
{
  "File": "include/linux/kvm_host.h",
  "FirstLine": 658,
  "LineCount": 20
}

Results:
{
  "Contents": " 658:\t};\n 659:\t\n 660:\tstruct kvm_xen_evtchn {\n 661:\t\tu32 port;\n 662:\t\tu32 vcpu_id;\n 663:\t\tint vcpu_idx;\n 664:\t\tu32 priority;\n 665:\t};\n 666:\t\n 667:\tstruct kvm_kernel_irq_routing_entry {\n 668:\t\tu32 gsi;\n 669:\t\tu32 type;\n 670:\t\tint (*set)(struct kvm_kernel_irq_routing_entry *e,\n 671:\t\t\t   struct kvm *kvm, int irq_source_id, int level,\n 672:\t\t\t   bool line_status);\n 673:\t\tunion {\n 674:\t\t\tstruct {\n 675:\t\t\t\tunsigned irqchip;\n 676:\t\t\t\tunsigned pin;\n 677:\t\t\t} irqchip;\n"
}

43/3 2026/10/15 02:34 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24065
							output: 246
							thoughts: 2927
						

Thoughts:
**KMSAN Assessment: KVM Xen Synchronization Patch Series**

Okay, let's break down this patch series. My initial thought process is to systematically analyze it for potential uninitialized memory issues, which is where KMSAN comes into play. I need to be thorough.

First, I examined the initialization of various fields within the `e` structure, confirming they are correctly initialized. The patch's core logic, which involves setting up event channels via `kvm_xen_set_evtchn`, doesn't seem to have any issues here, as the crucial variables (`port`, `vcpu_id`, etc.) were already initialized before the patch, and the added code is straightforward.

Next, I looked at the introduction of the `never_dirty` flag in `struct gfn_to_pfn_cache`. I confirmed that the flag is initialized correctly and that it's being used to optimize interactions with the guest's memory. The relevant functions, `__kvm_gpc_init` and `kvm_gpc_init`, handle this. The `never_dirty` flag is passed correctly from these initialization functions. I confirmed that these cache structures are allocated and initialized correctly via `kzalloc` in `kvm_xen_init_vcpu` and `kvm_xen_init_vm`.

The most complex section, `kvm_xen_hcall_evtchn_send`, looked like a potential hotspot. However, I carefully examined the function, particularly the path involving `kvm_read_guest_virt`, which populates the `send` structure. I checked that this is handled correctly and that the code protects against failures, ensuring `send` is properly initialized before any usage. The subsequent branching based on the return values is also logically sound and doesn't introduce uninitialized memory vulnerabilities. The hypercall code is robust and correct. I also made sure that `r` is handled correctly in all execution paths where `handled` is `true`.

I then analyzed `__kvm_xen_set_evtchn_fast`. This code is crucial, but I systematically verified that all local variables (`inject_upcall`, `kick_vcpu`) are explicitly initialized to `false`. The use of `GEN_BINARY_RMWcc` for atomic bit operations on guest-controlled memory is also safe, as the code correctly handles both 32-bit and 64-bit architectures, and does not depend on uninitialized variables.

I investigated `pfncache.c`, specifically `gpc_refresh_locked` and `kvm_gpc_refresh`.  Here, I confirmed that `ret` is initialized before each usage, which means it is assigned a value before being checked or returned. The same holds true for `__kvm_gpc_activate`.

I then examined `record_steal_time` and `vcpu_enter_guest`, which included changes related to TLB flushing requests. The patch defers TLB flush via `KVM_REQ_TLB_FLUSH_GUEST`, which is related to scheduling and request handling logic, and avoids scheduling in atomic context or direct user access.

In summary, the patch series addresses synchronization problems. I concluded that it deals with SRCU, mutexes, rwlocks, and request handling for KVM's Xen emulation and `gfn_to_pfn_cache`.

Now, considering the entire scope of the patch series, I can confidently answer the key questions regarding KMSAN:

1.  **Does it send kernel structures to userspace with potential uninitialized fields?** No.
2.  **Does it introduce conditional logic dependent on uninitialized variables?** No.
3.  **Does it allocate complex data structures where uninitialized fields are read?** No.
4.  **Does it introduce bounds check issues that could lead to reading uninitialized memory?** No.

Since the patch series focuses on locking, synchronization, and request deferral within the KVM infrastructure, any issues would likely manifest as deadlocks, race conditions, or lockdep warnings, which are the domain of KASAN and LOCKDEP. It doesn't introduce any new pathways for uninitialized memory to be read or leaked to userspace. Therefore, this patch is **not** a candidate for KMSAN analysis. The primary concerns here are concurrency-related, not memory initialization-related. This is a KASAN and LOCKDEP case.



44/3 2026/10/15 02:34 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series addresses synchronization, locking, and deadlock issues in KVM (specifically within the gfn_to_pfn_cache implementation, x86 steal time handling, and Xen emulation). It resolves an SRCU deadlock where guest exit handling could wait on a memslot update while holding kvm-\u003esrcu, replaces inline TLB flushes in steal time recording with deferred request handling (KVM_REQ_TLB_FLUSH_GUEST), and adds a 'wait' parameter to kvm_gpc_refresh/kvm_gpc_activate.\n\nKMSAN is designed to detect uninitialized memory reads and leaks to userspace. The patch does not introduce or alter any copy_to_user/ioctl data transfers to userspace, does not leave any struct fields or local variables uninitialized, and does not alter buffer length or bounds checking logic that could expose uninitialized memory. Any concurrency, deadlock, or memory lifetime issues introduced by these changes are addressed by LOCKDEP and standard KASAN, making a dedicated KMSAN fuzzing run unnecessary.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series addresses synchronization, locking, and deadlock issues in KVM (specifically within the gfn_to_pfn_cache implementation, x86 steal time handling, and Xen emulation). It resolves an SRCU deadlock where guest exit handling could wait on a memslot update while holding kvm-\u003esrcu, replaces inline TLB flushes in steal time recording with deferred request handling (KVM_REQ_TLB_FLUSH_GUEST), and adds a 'wait' parameter to kvm_gpc_refresh/kvm_gpc_activate.\n\nKMSAN is designed to detect uninitialized memory reads and leaks to userspace. The patch does not introduce or alter any copy_to_user/ioctl data transfers to userspace, does not leave any struct fields or local variables uninitialized, and does not alter buffer length or bounds checking logic that could expose uninitialized memory. Any concurrency, deadlock, or memory lifetime issues introduced by these changes are addressed by LOCKDEP and standard KASAN, making a dedicated KMSAN fuzzing run unnecessary.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)